Linux Documentation
 help / color / mirror / Atom feed
* [PATCH 0/2] Doc, scripts: facilitate phaseout of strlcat
From: Manuel Ebner @ 2026-05-10 16:49 UTC (permalink / raw)
  To: Andy Shevchenko, Kees Cook, Jonathan Corbet, Shuah Khan,
	Andy Whitcroft, Joe Perches, Dwaipayan Ray, Lukas Bulwahn,
	open list:DOCUMENTATION PROCESS, open list:DOCUMENTATION,
	open list
  Cc: Manuel Ebner

The goal of this series is to facilitate the transition from strlcat to better
alternatives.

^ permalink raw reply

* Re: [RFC net-next 0/4] devlink: Add boot-time defaults
From: Jakub Kicinski @ 2026-05-10 16:37 UTC (permalink / raw)
  To: Jiri Pirko
  Cc: Mark Bloch, Eric Dumazet, Paolo Abeni, Andrew Lunn,
	David S. Miller, Jonathan Corbet, Shuah Khan, Simon Horman,
	Saeed Mahameed, Leon Romanovsky, Tariq Toukan, Andrew Morton,
	Borislav Petkov (AMD), Randy Dunlap, Dave Hansen,
	Christian Brauner, Petr Mladek, Peter Zijlstra (Intel),
	Thomas Gleixner, Pawan Gupta, Dapeng Mi, Kees Cook, Marco Elver,
	Eric Biggers, Li RongQing, Paul E. McKenney, linux-doc,
	linux-kernel, netdev, linux-rdma
In-Reply-To: <af7Y4AYv-XDCbK_8@FV6GYCPJ69>

On Sat, 9 May 2026 09:01:23 +0200 Jiri Pirko wrote:
> Sat, May 09, 2026 at 02:52:13AM +0200, kuba@kernel.org wrote:
> >On Fri, 8 May 2026 20:07:44 +0200 Jiri Pirko wrote:  
> >legacy vs switchdev only describes the eswitch configuration.
> >As a non-SR-IOV user I really don't want to see the extra representors
> >hanging around my systems, confusing all daemons. IIRC mlx5 had some
> >limitations around the uplink representor. Maybe that's the disconnect.
> >But for a real, fully featured switchdev eswitches having the
> >PHY and PF representors on boot, always, will not make sense.  
> 
> As "a non-SR-IOV user", what extra representors you talk about? When you
> have pfs only, you don't have anything extra. Just 1 netdev per-pf, one
> devlink port per-pf. What's extra about it? When you don't have VFs/SFs.
> Everyhing is the same:

Some devices have separate uplink ports and PF representors.
As I said, what you're proposing isn't going to work for all drivers.

> >> Well, as any other nv config, it persists across kernels/hosts.
> >> Think about it as "unbreak-my-not-legacy-device" bit.  
> >
> >For most devices the switchdev mode does not change anything
> >substantial about the device. It's purely a kernel / driver config. 
> >It changes what objects and default rules kernel / driver installs. 
> >So I don't get why it would make sense to flash into the device
> >nvmem a Linux SW stack specific config.  
> 
> I look at it from the perspective that from some CX generation,
> switchdev mode should be default. So that is a device-based decision.
> I believe as such it can optionally be permanenty configured (nv config)
> on older device. Why not?

Feels a bit arbitrary and won't cover all cases. The question should be
why you are nacking a more reasonable solution. Keeping Linux config in
Linux params.

^ permalink raw reply

* Re: [PATCH] crypto: af_alg - Document the deprecation of AF_ALG
From: Eric Biggers @ 2026-05-10 16:32 UTC (permalink / raw)
  To: Kamran Khan
  Cc: Jeff Barnes, Andy Lutomirski, linux-crypto@vger.kernel.org,
	Herbert Xu, linux-doc@vger.kernel.org, linux-api@vger.kernel.org,
	linux-kernel@vger.kernel.org, netdev@vger.kernel.org,
	Linus Torvalds
In-Reply-To: <0b8bba44-f6bb-4d69-b9d4-5787c276d41a@inspirated.com>

On Sun, May 10, 2026 at 08:54:07AM -0700, Kamran Khan wrote:
> Hi,
> 
> AF_ALG is useful not just for hardware-offloading, but also for memory
> isolation so that applications only get oracle access to the crypto keys and
> a memory-safety vulnerability in user applications would not immediately put
> the secret key material at risk.

Note that if that memory-safety vulnerability leads to code execution in
the application, then it doesn't matter that it "only" has oracle
access.  It can still decrypt any data encrypted by that key.

The relevant threat model would be arbitrary reads, not any
"memory-safety vulnerability".

> I understand and appreciate the concern with complex attack surface and the
> increased frequency of attacks in this area. But I fear that completely
> removing AF_ALG increases the risk for userspace applications relying on it
> for memory isolation.
> 
> What alternatives do userspace applications have on Linux for ensuring
> crypto keys are not exposed in user memory? That is, FreeBSD and NetBSD
> natively provide /dev/crypto; removing AF_ALG would kill the only equivalent
> option on the Linux side for kernel-delegated cryptography.

The standard solution is simply to use an isolated userspace process
like ssh-agent.  Yes, the keys will be in "user memory".  But "not
exposed in user memory" is *not* a correct statement of the problem.

(Also note that protecting not-actively-in-use data from arbitrary read
primitives doesn't require cryptography at all.  That can be done simply
by using mprotect() to remove read permission from the memory, then
temporarily adding it back when it needs to be accessed.)

In any case, any hypothetical security benefit provided by AF_ALG would
have to be *very high* to outweigh the continuous stream of
vulnerabilities in it.  I understand that people using AF_ALG might not
be familiar with that continuous stream of vulnerabilities, but it would
be worth spending some time researching what has been going on.

- Eric

^ permalink raw reply

* [PATCH v6 2/8] docs/zh_CN: Add acm.rst translation
From: Kefan Bai @ 2026-05-10 13:53 UTC (permalink / raw)
  To: linux-usb, si.yanteng
  Cc: gregkh, seakeel, alexs, dzm91, corbet, skhan, linux-doc, doubled
In-Reply-To: <cover.1778415392.git.baikefan@leap-io-kernel.com>

Translate .../usb/acm.rst into Chinese

Update the translation through commit ecefae6db042
("docs: usb: rename files to .rst and add them to drivers-api")

Reviewed-by: Yanteng Si <siyanteng@cqsoftware.com.cn>
Signed-off-by: Kefan Bai <baikefan@leap-io-kernel.com>
---
 Documentation/translations/zh_CN/usb/acm.rst  | 136 ++++++++++++++++++
 .../translations/zh_CN/usb/index.rst          |   2 +-
 2 files changed, 137 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/translations/zh_CN/usb/acm.rst

diff --git a/Documentation/translations/zh_CN/usb/acm.rst b/Documentation/translations/zh_CN/usb/acm.rst
new file mode 100644
index 000000000000..25ec83afd25f
--- /dev/null
+++ b/Documentation/translations/zh_CN/usb/acm.rst
@@ -0,0 +1,136 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. include:: ../disclaimer-zh_CN.rst
+
+:Original: Documentation/usb/acm.rst
+
+:翻译:
+
+ 白钶凡 Kefan Bai <baikefan@leap-io-kernel.com>
+
+:校译:
+
+
+=======================
+Linux ACM 驱动 v0.16
+=======================
+
+版权所有 (c) 1999 Vojtech Pavlik <vojtech@suse.cz>
+
+由 SuSE 赞助
+
+0. 免责声明
+~~~~~~~~~~~~~
+本程序是自由软件;你可以在自由软件基金会发布的 GNU 通用公共许可证第 2 版,
+或者(按你的选择)任何后续版本的条款下重新发布和/或修改它。
+
+发布本程序是希望它能发挥作用,但它不附带任何担保;甚至不包括对适销性
+或特定用途适用性的默示担保。详情见 GNU 通用公共许可证。
+
+你应该已经随本程序收到了 GNU 通用公共许可证的副本;
+如果没有,请致信:Free Software Foundation, Inc., 59
+Temple Place, Suite 330, Boston, MA 02111-1307 USA。
+
+如需联系作者,可发送电子邮件至 vojtech@suse.cz,
+或邮寄至:
+Vojtech Pavlik, Ucitelska 1576, Prague 8, 182 00, Czech Republic。
+
+为方便起见,软件包中已附带 GNU 通用公共许可证第 2 版:见 COPYING 文件。
+
+1. 使用方法
+~~~~~~~~~~~~~
+``drivers/usb/class/cdc-acm.c`` 驱动可用于符合 USB 通信设备类抽象控制模型
+(USB CDC ACM)规范的 USB 调制解调器和 USB ISDN 终端适配器。
+
+许多调制解调器支持此驱动,以下是我所知道的一些型号:
+
+	- 3Com OfficeConnect 56k
+	- 3Com Voice FaxModem Pro
+	- 3Com Sportster
+	- MultiTech MultiModem 56k
+	- Zoom 2986L FaxModem
+	- Compaq 56k FaxModem
+	- ELSA Microlink 56k
+
+我知道有一款 ISDN 终端适配器可以与 ACM 驱动一起使用:
+
+	- 3Com USR ISDN Pro TA
+
+一些手机也可以通过 USB 连接。我知道以下机型可以正常工作:
+
+	- SonyEricsson K800i
+
+遗憾的是,许多调制解调器和大多数 ISDN TA 都使用专有接口,
+因此无法与此驱动配合工作。购买前请先确认设备是否符合 ACM 规范。
+
+要使用这些调制解调器,需要加载以下模块::
+
+	usbcore.ko
+	uhci-hcd.ko ohci-hcd.ko or ehci-hcd.ko
+	cdc-acm.ko
+
+之后就应该可以访问这些调制解调器了。
+应当可以使用 ``minicom``、``ppp`` 和 ``mgetty`` 与它们通信。
+
+2. 验证驱动是否正常工作
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+第一步是检查 ``/sys/kernel/debug/usb/devices``,其内容应该类似如下::
+
+  T:  Bus=01 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12  MxCh= 2
+  B:  Alloc=  0/900 us ( 0%), #Int=  0, #Iso=  0
+  D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
+  P:  Vendor=0000 ProdID=0000 Rev= 0.00
+  S:  Product=USB UHCI Root Hub
+  S:  SerialNumber=6800
+  C:* #Ifs= 1 Cfg#= 1 Atr=40 MxPwr=  0mA
+  I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
+  E:  Ad=81(I) Atr=03(Int.) MxPS=   8 Ivl=255ms
+  T:  Bus=01 Lev=01 Prnt=01 Port=01 Cnt=01 Dev#=  2 Spd=12  MxCh= 0
+  D:  Ver= 1.00 Cls=02(comm.) Sub=00 Prot=00 MxPS= 8 #Cfgs=  2
+  P:  Vendor=04c1 ProdID=008f Rev= 2.07
+  S:  Manufacturer=3Com Inc.
+  S:  Product=3Com U.S. Robotics Pro ISDN TA
+  S:  SerialNumber=UFT53A49BVT7
+  C:  #Ifs= 1 Cfg#= 1 Atr=60 MxPwr=  0mA
+  I:  If#= 0 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=ff Prot=ff Driver=acm
+  E:  Ad=85(I) Atr=02(Bulk) MxPS=  64 Ivl=  0ms
+  E:  Ad=04(O) Atr=02(Bulk) MxPS=  64 Ivl=  0ms
+  E:  Ad=81(I) Atr=03(Int.) MxPS=  16 Ivl=128ms
+  C:* #Ifs= 2 Cfg#= 2 Atr=60 MxPwr=  0mA
+  I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(comm.) Sub=02 Prot=01 Driver=acm
+  E:  Ad=81(I) Atr=03(Int.) MxPS=  16 Ivl=128ms
+  I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=acm
+  E:  Ad=85(I) Atr=02(Bulk) MxPS=  64 Ivl=  0ms
+  E:  Ad=04(O) Atr=02(Bulk) MxPS=  64 Ivl=  0ms
+
+这三行的存在很关键(以及 ``Cls=`` 字段里出现的 ``comm`` 和 ``data`` 类);
+它说明这是一个 ACM 设备。``Driver=acm`` 表示该设备正在使用 acm 驱动。
+如果只看到 ``Cls=ff(vend.)``,那就无能为力了:这说明你手上的设备使用的是
+厂商专有接口::
+
+    D:  Ver= 1.00 Cls=02(comm.) Sub=00 Prot=00 MxPS= 8 #Cfgs=  2
+    I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(comm.) Sub=02 Prot=01 Driver=acm
+    I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=acm
+
+在系统日志中应该可以看到::
+
+  usb.c: USB new device connect, assigned device number 2
+  usb.c: kmalloc IF c7691fa0, numif 1
+  usb.c: kmalloc IF c7b5f3e0, numif 2
+  usb.c: skipped 4 class/vendor specific interface descriptors
+  usb.c: new device strings: Mfr=1, Product=2, SerialNumber=3
+  usb.c: USB device number 2 default language ID 0x409
+  Manufacturer: 3Com Inc.
+  Product: 3Com U.S. Robotics Pro ISDN TA
+  SerialNumber: UFT53A49BVT7
+  acm.c: probing config 1
+  acm.c: probing config 2
+  ttyACM0: USB ACM device
+  acm.c: acm_control_msg: rq: 0x22 val: 0x0 len: 0x0 result: 0
+  acm.c: acm_control_msg: rq: 0x20 val: 0x0 len: 0x7 result: 7
+  usb.c: acm driver claimed interface c7b5f3e0
+  usb.c: acm driver claimed interface c7b5f3f8
+  usb.c: acm driver claimed interface c7691fa0
+
+如果以上都正常,请启动 ``minicom``,把它配置为连接 ``ttyACM`` 设备,
+然后尝试输入 ``at``。如果返回 ``OK``,说明一切工作正常。
diff --git a/Documentation/translations/zh_CN/usb/index.rst b/Documentation/translations/zh_CN/usb/index.rst
index 7cfe99a4dc0a..449e8ac2dff0 100644
--- a/Documentation/translations/zh_CN/usb/index.rst
+++ b/Documentation/translations/zh_CN/usb/index.rst
@@ -17,10 +17,10 @@ USB 支持
 .. toctree::
     :maxdepth: 1

+    acm

 Todolist:

-* acm
 * authorization
 * chipidea
 * dwc3
--
2.54.0


^ permalink raw reply related

* Re: [PATCH] crypto: af_alg - Document the deprecation of AF_ALG
From: Kamran Khan @ 2026-05-10 15:54 UTC (permalink / raw)
  To: Jeff Barnes, Andy Lutomirski
  Cc: Eric Biggers, linux-crypto@vger.kernel.org, Herbert Xu,
	linux-doc@vger.kernel.org, linux-api@vger.kernel.org,
	linux-kernel@vger.kernel.org, netdev@vger.kernel.org,
	Linus Torvalds
In-Reply-To: <14A441D8-5370-44BE-8732-99BF8107C3FD@getmailspring.com>

Hi,

AF_ALG is useful not just for hardware-offloading, but also for memory 
isolation so that applications only get oracle access to the crypto keys 
and a memory-safety vulnerability in user applications would not 
immediately put the secret key material at risk.

I understand and appreciate the concern with complex attack surface and 
the increased frequency of attacks in this area. But I fear that 
completely removing AF_ALG increases the risk for userspace applications 
relying on it for memory isolation.

What alternatives do userspace applications have on Linux for ensuring 
crypto keys are not exposed in user memory? That is, FreeBSD and NetBSD 
natively provide /dev/crypto; removing AF_ALG would kill the only 
equivalent option on the Linux side for kernel-delegated cryptography.

Thanks,
Kamran.

On 5/6/26 7:42 AM, Jeff Barnes wrote:
> Hi,
> 
> On May 5 2026, at 7:17 pm, Andy Lutomirski <luto@amacapital.net> wrote:
> 
>>> On Apr 29, 2026, at 6:19 PM, Eric Biggers <ebiggers@kernel.org> wrote:
>>>   
>>> AF_ALG is almost completely unnecessary, and it exposes a massive attack
>>> surface that hasn't been standing up to modern vulnerability discovery
>>> tools.  The latest one even has its own website, providing a small
>>> Python script that reliably roots most Linux distros: https://copy.fail/
>>   
>> How about adding a configuration option, defaulted on, that requires
>> capable(CAP_SYS_ADMIN) to create the socket (and maybe also to bind /
>> connect it).  And a sysctl to allow the administrator to override this
>> in the unlikely event that it’s needed.
>>   
>> IIRC cryptsetup used to and maybe even still does require these
>> sockets sometimes and this would let it keep working.  And there's all
>> the FIPS stuff downthread.
> 
> Apologize in advance for the long-winded answer.
> 
> The "FIPS stuff" centers on using sha512hmac -> libkcapi -> AF_ALG for
> verifying integrity. The early‑boot sha512hmac check that some
> distributions use (typically from initramfs) sits at an awkward
> intersection of multiple standards, and it may help to clarify where it
> actually fits and where it doesn't.
> 
>  From a standards perspective, FIPS 140‑3 requires a cryptographic module
> to perform self‑integrity verification using an approved algorithm and
> to prevent the module from entering an operational state on failure. In
> the Linux kernel, the cryptographic module is the kernel crypto
> subsystem, and these requirements are met by the kernel’s internal
> power‑up self‑tests (KATs, etc.) on the crypto code and critical data as
> loaded into memory.
> 
> FIPS 199 / SP 800‑53 (e.g., SI‑7) impose system‑level integrity
> requirements (for Moderate impact systems), i.e., that unauthorized
> modification of critical components is prevented or detected and that
> failures result in a protective action. These controls are explicitly
> technology‑agnostic and are not limited to cryptographic‑module self‑tests.
> 
> The sha512hmac check is not the FIPS 140‑3 cryptographic‑module
> self‑integrity test. Instead, it has historically been used as a system
> integrity control that provides auditors with assurance that the kernel
> image containing the cryptographic module has not been modified prior to
> execution, and that a failure will halt the boot.
> 
> Although FIPS 140‑3 does not mandate an HMAC over the kernel image, the
> early‑boot HMAC became an accepted evidence pattern for satisfying
> system‑integrity expectations (FIPS 199 / SI‑7) alongside a kernel
> crypto validation. This is why it is often perceived as “required” for
> FIPS submissions, even though it is not normatively required by
> FIPS 140‑3 itself.
> 
> With the deprecation/removal of AF_ALG for this use case, there is no
> longer a supported way to perform an early‑boot, userspace‑driven HMAC
> using validated kernel crypto without introducing circular dependencies
> (e.g., relying on userspace crypto before crypto self‑tests complete).
> As a result, there is no drop‑in replacement for sha512hmac that
> preserves all of its historical properties.
> 
> This is a new development that challenges a long‑standing assumption:
> that system‑integrity evidence and cryptographic‑module self‑integrity
> can be cleanly separated while still being demonstrated by a single
> early‑boot mechanism. That assumption no longer holds given proposed
> kernel interfaces.
> 
> A more accurate decomposition (and one that aligns with the intent of
> the standards) is to separate integrity enforcement by system phase.
> 
> 1. Secure Boot (or equivalent platform verification) ensures that a
> modified kernel image is not executed at all. This satisfies the
> requirement that critical components are not loaded in a modified state
> and that integrity failure results in a protective action (boot prevention).
> 
> 2. IMA (with appraisal and enforcement) ensures that modified
> executables, modules, or firmware cannot be loaded or executed once the
> kernel is running.
> 
> 3. Kernel crypto self‑tests continue to satisfy FIPS 140‑3
> self‑integrity requirements independently of the above.
> 
> Taken together, Secure Boot + IMA provide continuous system‑integrity
> enforcement without re‑introducing early‑boot HMACs or AF_ALG
> dependencies, while keeping cryptographic‑module self‑integrity
> correctly scoped to the kernel crypto subsystem.
> 
> The transition away from sha512hmac is therefore not a removal of
> integrity enforcement, but a shift from a single, early‑boot mechanism
> to a phased integrity model that better reflects the separation of
> concerns already present in the standards — even though this separation
> was previously masked by the hacky HMAC approach.
> 
> This change will require updated documentation and auditor education,
> but it reflects the current technical reality and avoids perpetuating an
> interface that no longer has a sustainable implementation path.
> 
>>   
>>   
>>>   
>>> This isn't sustainable, especially as LLMs have accelerated the rate the
>>> vulnerabilities are coming in.  The effort that is being put into this
>>> thing is vastly disproportional to the few programs that actually use
>>> it, and those programs would be better served by userspace code anyway.
>>>   
>>> These issues have been noted in many mailing list discussions already.
>>> But until now they haven't been reflected in the documentation or
>>> kconfig menu itself, and the vulnerabilities are still coming in.
>>>   
>>> Let's go ahead and document the deprecation.
>>>   
>>> This isn't intended to change anything overnight.  After all, most Linux
>>> distros won't be able to disable the kconfig options quite yet, mainly
>>> because of iwd.  But this should create a bit more impetus for these
>>> userspace programs to be fixed, and the documentation update should also
>>> help prevent more users from appearing.
>>>   
>>> Signed-off-by: Eric Biggers <ebiggers@kernel.org>
>>> ---
>>>   
>>> This patch is targeting crypto/master
>>>   
>>> Documentation/crypto/userspace-if.rst | 82 ++++++++++++++++++++-------
>>> crypto/Kconfig                        | 69 ++++++++++++++++------
>>> 2 files changed, 113 insertions(+), 38 deletions(-)
>>>   
>>> diff --git a/Documentation/crypto/userspace-if.rst b/Documentation/crypto/userspace-if.rst
>>> index 021759198fe7..c39f5c79a5b7 100644
>>> --- a/Documentation/crypto/userspace-if.rst
>>> +++ b/Documentation/crypto/userspace-if.rst
>>> @@ -2,30 +2,72 @@ User Space Interface
>>> ====================
>>>   
>>> Introduction
>>> ------------
>>>   
>>> -The concepts of the kernel crypto API visible to kernel space is fully
>>> -applicable to the user space interface as well. Therefore, the kernel
>>> -crypto API high level discussion for the in-kernel use cases applies
>>> -here as well.
>>> -
>>> -The major difference, however, is that user space can only act as a
>>> -consumer and never as a provider of a transformation or cipher
>>> -algorithm.
>>> -
>>> -The following covers the user space interface exported by the kernel
>>> -crypto API. A working example of this description is libkcapi that can
>>> -be obtained from [1]. That library can be used by user space
>>> -applications that require cryptographic services from the kernel.
>>> -
>>> -Some details of the in-kernel kernel crypto API aspects do not apply to
>>> -user space, however. This includes the difference between synchronous
>>> -and asynchronous invocations. The user space API call is fully
>>> -synchronous.
>>> -
>>> -[1] https://www.chronox.de/libkcapi/index.html
>>> +AF_ALG provides unprivileged userspace programs access to arbitrary hash,
>>> +symmetric cipher, AEAD, and RNG algorithms that are implemented in kernel-mode
>>> +code.
>>> +
>>> +AF_ALG is insecure and is deprecated. Originally added to the kernel
>>> in 2010,
>>> +most kernel developers now consider it to be a mistake.
>>> +
>>> +AF_ALG continues to be supported only for backwards compatibility.
>>> On systems
>>> +where no programs using AF_ALG remain, the support for it should be
>>> disabled by
>>> +disabling ``CONFIG_CRYPTO_USER_API_*``.
>>> +
>>> +Deprecation
>>> +-----------
>>> +
>>> +AF_ALG was originally intended to provide userspace programs access
>>> to crypto
>>> +accelerators that they wouldn't otherwise have access to.
>>> +
>>> +However, that capability turned out to not be useful on very many
>>> systems. More
>>> +significantly, the actual implementation exposes a vastly greater
>>> amount of
>>> +functionality than that. It actually provides access to all software algorithms.
>>> +
>>> +This includes arbitrary compositions of different algorithms created
>>> via a
>>> +complex template system, as well as algorithms that only make sense
>>> as internal
>>> +implementation details of other algorithms. It also includes full zero-copy
>>> +support, which is difficult for the kernel to implement securely.
>>> +
>>> +Ultimately, these algorithms are just math computations. They use
>>> the same
>>> +instructions that userspace programs already have access to, just
>>> accessed in a
>>> +much more convoluted and less efficient way.
>>> +
>>> +Indeed, userspace code is nearly always what is being used anyway.
>>> These same
>>> +algorithms are widely implemented in userspace crypto libraries.
>>> +
>>> +Meanwhile, AF_ALG hasn't been withstanding modern vulnerability
>>> discovery tools
>>> +such as syzbot and large language models. It receives a steady
>>> stream of CVEs.
>>> +Some of the examples include:
>>> +
>>> +- CVE-2026-31677
>>> +- CVE-2026-31431 (https://copy.fail)
>>> +- CVE-2025-38079
>>> +- CVE-2025-37808
>>> +- CVE-2024-26824
>>> +- CVE-2022-48781
>>> +- CVE-2019-8912
>>> +- CVE-2018-14619
>>> +- CVE-2017-18075
>>> +- CVE-2017-17806
>>> +- CVE-2017-17805
>>> +- CVE-2016-10147
>>> +- CVE-2015-8970
>>> +- CVE-2015-3331
>>> +- CVE-2014-9644
>>> +- CVE-2013-7421
>>> +- CVE-2011-4081
>>> +
>>> +It is recommended that, whenever possible, userspace programs be
>>> migrated to
>>> +userspace crypto code (which again, is what is normally used anyway) and
>>> +``CONFIG_CRYPTO_USER_API_*`` be disabled.  On systems that use
>>> SELinux, SELinux
>>> +can also be used to restrict the use of AF_ALG to trusted programs.
>>> +
>>> +The remainder of this documentation provides the historical
>>> documentation for
>>> +the deprecated AF_ALG interface.
>>>   
>>> User Space API General Remarks
>>> ------------------------------
>>>   
>>> The kernel crypto API is accessible from user space. Currently, the
>>> diff --git a/crypto/Kconfig b/crypto/Kconfig
>>> index 103d1f58cb7c..6cd1c478d4be 100644
>>> --- a/crypto/Kconfig
>>> +++ b/crypto/Kconfig
>>> @@ -1278,48 +1278,72 @@ config CRYPTO_DF80090A
>>>     tristate
>>>     select CRYPTO_AES
>>>     select CRYPTO_CTR
>>>   
>>> endmenu
>>> -menu "Userspace interface"
>>> +menu "Userspace interface (deprecated)"
>>>   
>>> config CRYPTO_USER_API
>>>     tristate
>>>   
>>> config CRYPTO_USER_API_HASH
>>> -    tristate "Hash algorithms"
>>> +    tristate "Hash algorithms (deprecated)"
>>>     depends on NET
>>>     select CRYPTO_HASH
>>>     select CRYPTO_USER_API
>>>     help
>>> -      Enable the userspace interface for hash algorithms.
>>> +      Enable the AF_ALG userspace interface for hash algorithms.  This
>>> +      provides unprivileged userspace programs access to arbitrary hash
>>> +      algorithms implemented in the kernel's privileged execution context.
>>>   
>>> -      See Documentation/crypto/userspace-if.rst and
>>> -      https://www.chronox.de/libkcapi/html/index.html
>>> +      This interface is deprecated and is supported only for backwards
>>> +      compatibility.  It regularly has vulnerabilities, and the capabilities
>>> +      it provides are redundant with userspace crypto libraries.
>>> +
>>> +      Enable this only if needed for support for a program that
>>> hasn't yet
>>> +      been converted to userspace crypto, for example iwd.
>>> +
>>> +      See also Documentation/crypto/userspace-if.rst
>>>   
>>> config CRYPTO_USER_API_SKCIPHER
>>> -    tristate "Symmetric key cipher algorithms"
>>> +    tristate "Symmetric key cipher algorithms (deprecated)"
>>>     depends on NET
>>>     select CRYPTO_SKCIPHER
>>>     select CRYPTO_USER_API
>>>     help
>>> -      Enable the userspace interface for symmetric key cipher algorithms.
>>> +      Enable the AF_ALG userspace interface for symmetric key algorithms.
>>> +      This provides unprivileged userspace programs access to arbitrary
>>> +      symmetric key algorithms implemented in the kernel's privileged
>>> +      execution context.
>>> +
>>> +      This interface is deprecated and is supported only for backwards
>>> +      compatibility.  It regularly has vulnerabilities, and the capabilities
>>> +      it provides are redundant with userspace crypto libraries.
>>> +
>>> +      Enable this only if needed for support for a program that
>>> hasn't yet
>>> +      been converted to userspace crypto, for example iwd, or cryptsetup
>>> +      with certain algorithms.
>>>   
>>> -      See Documentation/crypto/userspace-if.rst and
>>> -      https://www.chronox.de/libkcapi/html/index.html
>>> +      See also Documentation/crypto/userspace-if.rst
>>>   
>>> config CRYPTO_USER_API_RNG
>>> -    tristate "RNG (random number generator) algorithms"
>>> +    tristate "Random number generation algorithms (deprecated)"
>>>     depends on NET
>>>     select CRYPTO_RNG
>>>     select CRYPTO_USER_API
>>>     help
>>> -      Enable the userspace interface for RNG (random number generator)
>>> -      algorithms.
>>> +      Enable the AF_ALG userspace interface for random number generation
>>> +      (RNG) algorithms.  This provides unprivileged userspace programs
>>> +      access to arbitrary RNG algorithms implemented in the kernel's
>>> +      privileged execution context.
>>>   
>>> -      See Documentation/crypto/userspace-if.rst and
>>> -      https://www.chronox.de/libkcapi/html/index.html
>>> +      This interface is deprecated and is supported only for backwards
>>> +      compatibility.  It regularly has vulnerabilities, and the capabilities
>>> +      it provides are redundant with userspace crypto libraries as
>>> well as
>>> +      the normal kernel RNG (e.g., /dev/urandom and getrandom(2)).
>>> +
>>> +      See also Documentation/crypto/userspace-if.rst
>>>   
>>> config CRYPTO_USER_API_RNG_CAVP
>>>     bool "Enable CAVP testing of DRBG"
>>>     depends on CRYPTO_USER_API_RNG && CRYPTO_DRBG
>>>     help
>>> @@ -1330,20 +1354,29 @@ config CRYPTO_USER_API_RNG_CAVP
>>>   
>>>       This should only be enabled for CAVP testing. You should say
>>>       no unless you know what this is.
>>>   
>>> config CRYPTO_USER_API_AEAD
>>> -    tristate "AEAD cipher algorithms"
>>> +    tristate "AEAD cipher algorithms (deprecated)"
>>>     depends on NET
>>>     select CRYPTO_AEAD
>>>     select CRYPTO_SKCIPHER
>>>     select CRYPTO_USER_API
>>>     help
>>> -      Enable the userspace interface for AEAD cipher algorithms.
>>> +      Enable the AF_ALG userspace interface for authenticated encryption
>>> +      with associated data (AEAD) algorithms.  This provides unprivileged
>>> +      userspace programs access to arbitrary AEAD algorithms
>>> implemented in
>>> +      the kernel's privileged execution context.
>>> +
>>> +      This interface is deprecated and is supported only for backwards
>>> +      compatibility.  It regularly has vulnerabilities, and the capabilities
>>> +      it provides are redundant with userspace crypto libraries.
>>> +
>>> +      Enable this only if needed for support for a program that
>>> hasn't yet
>>> +      been converted to userspace crypto, for example iwd.
>>>   
>>> -      See Documentation/crypto/userspace-if.rst and
>>> -      https://www.chronox.de/libkcapi/html/index.html
>>> +      See also Documentation/crypto/userspace-if.rst
>>>   
>>> config CRYPTO_USER_API_ENABLE_OBSOLETE
>>>     bool "Obsolete cryptographic algorithms"
>>>     depends on CRYPTO_USER_API
>>>     default y
>>>   
>>> base-commit: 57b8e2d666a31fa201432d58f5fe3469a0dd83ba
>>> --
>>> 2.54.0
>>>   
>>>   
>>
> 


^ permalink raw reply

* htmldocs: Documentation/admin-guide/mm/damon/hugepage.rst:3: WARNING: Title overline too short.
From: kernel test robot @ 2026-05-10 15:44 UTC (permalink / raw)
  To: Asier Gutierrez; +Cc: oe-kbuild-all, 0day robot, linux-doc

tree:   https://github.com/intel-lab-lkp/linux/commits/gutierrez-asier-huawei-partners-com/mm-damon-Generalize-ctx_target-creation-for-damon_ops_id-and-add-vaddr-support/20260510-155505
head:   022dc7c281135daee8dd8ad5c6ff6593bcfd2787
commit: 022dc7c281135daee8dd8ad5c6ff6593bcfd2787 Documentation/admin-guide/mm/damon: add DAMON-based Hugepage Management documentation
date:   8 hours ago
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
docutils: docutils (Docutils 0.21.2, Python 3.13.5, on linux)
reproduce: (https://download.01.org/0day-ci/archive/20260510/202605101727.glKBkFJv-lkp@intel.com/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of
the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202605101727.glKBkFJv-lkp@intel.com/

All warnings (new ones prefixed by >>):

   WARNING: Documentation/ABI/testing/sysfs-class-reboot-mode-reboot_modes:36: abi_sys_class_reboot_mode_driver_reboot_modes doesn't have a description
   WARNING: /sys/bus/usb/devices/<busnum>-<devnum>:<config num>.<interface num>/<hid-bus>:<vendor-id>:<product-id>.<num>/os_mode is defined 2 times: Documentation/ABI/testing/sysfs-driver-hid-lenovo-go:364; Documentation/ABI/testing/sysfs-driver-hid-lenovo-go-s:234
   WARNING: /sys/bus/usb/devices/<busnum>-<devnum>:<config num>.<interface num>/<hid-bus>:<vendor-id>:<product-id>.<num>/os_mode_index is defined 2 times: Documentation/ABI/testing/sysfs-driver-hid-lenovo-go:373; Documentation/ABI/testing/sysfs-driver-hid-lenovo-go-s:243
   WARNING: /sys/bus/usb/devices/<busnum>-<devnum>:<config num>.<interface num>/<hid-bus>:<vendor-id>:<product-id>.<num>/touchpad/enabled is defined 2 times: Documentation/ABI/testing/sysfs-driver-hid-lenovo-go:636; Documentation/ABI/testing/sysfs-driver-hid-lenovo-go-s:252
   WARNING: /sys/bus/usb/devices/<busnum>-<devnum>:<config num>.<interface num>/<hid-bus>:<vendor-id>:<product-id>.<num>/touchpad/enabled_index is defined 2 times: Documentation/ABI/testing/sysfs-driver-hid-lenovo-go:645; Documentation/ABI/testing/sysfs-driver-hid-lenovo-go-s:261
>> Documentation/admin-guide/mm/damon/hugepage.rst:3: WARNING: Title overline too short.
--
   =======================
   DAMON-based huge page collapsing
   ======================= [docutils]
>> Documentation/admin-guide/mm/damon/hugepage.rst:11: WARNING: Title underline too short.


vim +3 Documentation/admin-guide/mm/damon/hugepage.rst

     2	
   > 3	=======================
     4	DAMON-based huge page collapsing
     5	=======================
     6	
     7	DAMON-based huge page collapsing (DAMON_HUGEPAGE) is a static kernel module
     8	that aimed to collapse hot regions into huge pages.
     9	
    10	Where Proactive huge page collapsing is Required?
  > 11	========================================
    12	

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

^ permalink raw reply

* [PATCH] cpufreq-stats: document limitations on modern cpufreq drivers
From: NicoErdmann @ 2026-05-10 14:33 UTC (permalink / raw)
  To: linux-pm; +Cc: linux-doc, rafael, viresh.kumar, corbet, skhan, NicoErdmann
In-Reply-To: <20260510143303.120863-1-nicobsc4.ref@yahoo.com>

Signed-off-by: NicoErdmann <nicobsc4@yahoo.com>
---
 Documentation/cpu-freq/cpufreq-stats.rst | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/Documentation/cpu-freq/cpufreq-stats.rst b/Documentation/cpu-freq/cpufreq-stats.rst
index 9ad695b1c7db..e8a8b3a85ad8 100644
--- a/Documentation/cpu-freq/cpufreq-stats.rst
+++ b/Documentation/cpu-freq/cpufreq-stats.rst
@@ -28,6 +28,13 @@ Various statistics will form read_only files under this directory.
 This driver is designed to be independent of any particular cpufreq_driver
 that may be running on your CPU. So, it will work with any cpufreq_driver.
 
+.. note::
+	
+   On some modern systems, this interface may not be available or may not
+   expose meaningful statistics depending on the active CPU frequency scaling driver.
+
+   In particular, drivers such as intel_pstate or amd_pstate may use alternative
+   mechanisms for frequency scaling and accounting
 
 2. Statistics Provided (with example)
 =====================================
-- 
2.54.0


^ permalink raw reply related

* Re: [PATCH v5 2/4] mm/memory-failure: add panic option for unrecoverable pages
From: Lance Yang @ 2026-05-10 14:42 UTC (permalink / raw)
  To: leitao
  Cc: david, linmiaohe, nao.horiguchi, akpm, corbet, skhan, ljs,
	Liam.Howlett, vbabka, rppt, surenb, mhocko, shuah, linux-mm,
	linux-kernel, linux-doc, linux-kselftest, kernel-team, Lance Yang
In-Reply-To: <aftnSfb15G92JON5@gmail.com>


On Wed, May 06, 2026 at 09:18:12AM -0700, Breno Leitao wrote:
>On Tue, Apr 28, 2026 at 11:07:21AM +0800, Lance Yang wrote:
>> 
>> On Mon, Apr 27, 2026 at 05:49:28PM +0200, David Hildenbrand (Arm) wrote:
>> >> +	switch (type) {
>> >> +	case MF_MSG_KERNEL:
>> >> +	case MF_MSG_UNKNOWN:
>> >> +		return true;
>> >> +	case MF_MSG_KERNEL_HIGH_ORDER:
>> >> +		/*
>> >> +		 * Rule out a concurrent buddy allocation: give the
>> >> +		 * allocator a moment to finish prep_new_page() and
>> >> +		 * re-check. A genuine high-order kernel tail page stays
>> >> +		 * unowned; an in-flight allocation will have bumped the
>> >> +		 * refcount, attached a mapping, or placed the page on
>> >> +		 * an LRU by now.
>> >> +		 */
>> >> +		p = pfn_to_online_page(pfn);
>> >> +		if (!p)
>> >> +			return true;
>> >> +		/*
>> >> +		 * Yield so a concurrent allocator on another CPU can
>> >> +		 * finish prep_new_page() and have its writes become
>> >> +		 * visible before we resample the page state.
>> >> +		 */
>> >> +		cpu_relax();
>> >> +		return page_count(p) == 0 &&
>> >> +		       !PageLRU(p) &&
>> >> +		       !page_mapped(p) &&
>> >> +		       !page_folio(p)->mapping &&
>> >> +		       !is_free_buddy_page(p);
>> >
>> >I don't get what you are doing here. The right way to check for a tail page is
>> >not by checking the refcount.
>> >
>> >Further, you are not holding a folio reference? If so, calling
>> >page_mapped/folio_mapped is shaky. On concurrent folio split you can trigger a
>> >VM_WARN_ON_FOLIO().
>> >
>> >
>> >Maybe folio_snapshot() is what you are looking for, if you are in fact not
>> >holding a reference?
>> 
>> Right! Maybe we should not try to make this decision in
>> panic_on_unrecoverable_mf().
>> 
>> By the time we get here, we only know the final MF_MSG_* type. The
>> real reason why get_hwpoison_page() failed is already lost.
>> 
>> Wonder if it would be better to split that earlier, around
>> __get_unpoison_page()/get_any_page(). That code still knows why
>> grabbing the page failed, either an unsupported kernel page or
>> just a temporary race we cannot really trust :)
>> 
>> Then the later panic logic can be simple: panic for the stable
>> unsupported kernel page case, and not for the temporary race case.
>> 
>> That would also avoid trying to guess MF_MSG_KERNEL_HIGH_ORDER here:)
>
>This is a very good feedback, and definitely what I wanted to do, but,
>failed. Once we have the reason, we don't need this dance to guess the
>reason.
>
>I've hacked a patch based on this approach. How does it sound?

Yes. This direction makes sense to me, not an expert though :D

I played with something similar (untested) on top of patch #01:

---8<---
diff --git a/mm/memory-failure.c b/mm/memory-failure.c
index 432d5f996c64..a2799f063913 100644
--- a/mm/memory-failure.c
+++ b/mm/memory-failure.c
@@ -74,6 +74,8 @@ static int sysctl_memory_failure_recovery __read_mostly = 1;

 static int sysctl_enable_soft_offline __read_mostly = 1;

+static int sysctl_panic_on_unrecoverable_mf __read_mostly;
+
 atomic_long_t num_poisoned_pages __read_mostly = ATOMIC_LONG_INIT(0);

 static bool hw_memory_failure __read_mostly = false;
@@ -155,6 +157,15 @@ static const struct ctl_table memory_failure_table[] = {
 		.proc_handler	= proc_dointvec_minmax,
 		.extra1		= SYSCTL_ZERO,
 		.extra2		= SYSCTL_ONE,
+	},
+	{
+		.procname	= "panic_on_unrecoverable_memory_failure",
+		.data		= &sysctl_panic_on_unrecoverable_mf,
+		.maxlen		= sizeof(sysctl_panic_on_unrecoverable_mf),
+		.mode		= 0644,
+		.proc_handler	= proc_dointvec_minmax,
+		.extra1		= SYSCTL_ZERO,
+		.extra2		= SYSCTL_ONE,
 	}
 };

@@ -1281,6 +1292,18 @@ static void update_per_node_mf_stats(unsigned long pfn,
 	++mf_stats->total;
 }

+static bool panic_on_unrecoverable_mf(enum mf_action_page_type type,
+				      enum mf_result result)
+{
+	if (!sysctl_panic_on_unrecoverable_mf || result != MF_IGNORED)
+		return false;
+
+	if (type == MF_MSG_KERNEL)
+		return true;
+
+	return false;
+}
+
 /*
  * "Dirty/Clean" indication is not 100% accurate due to the possibility of
  * setting PG_dirty outside page lock. See also comment above set_page_dirty().
@@ -1298,6 +1321,9 @@ static int action_result(unsigned long pfn, enum mf_action_page_type type,
 	pr_err("%#lx: recovery action for %s: %s\n",
 		pfn, action_page_types[type], action_name[result]);

+	if (panic_on_unrecoverable_mf(type, result))
+		panic("Memory failure: %#lx: unrecoverable page", pfn);
+
 	return (result == MF_RECOVERED || result == MF_DELAYED) ? 0 : -EBUSY;
 }

@@ -1389,11 +1415,27 @@ static int __get_hwpoison_page(struct page *page, unsigned long flags)

 #define GET_PAGE_MAX_RETRY_NUM 3

-static int get_any_page(struct page *p, unsigned long flags)
+enum mf_get_page_status {
+	MF_GET_PAGE_OK = 0,
+	MF_GET_PAGE_RACE,
+	MF_GET_PAGE_UNHANDLABLE,
+};
+
+static void set_mf_get_page_status(enum mf_get_page_status *gp_status,
+				   enum mf_get_page_status value)
+{
+	if (gp_status)
+		*gp_status = value;
+}
+
+static int get_any_page(struct page *p, unsigned long flags,
+			enum mf_get_page_status *gp_status)
 {
 	int ret = 0, pass = 0;
 	bool count_increased = false;

+	set_mf_get_page_status(gp_status, MF_GET_PAGE_OK);
+
 	if (flags & MF_COUNT_INCREASED)
 		count_increased = true;

@@ -1406,11 +1448,13 @@ static int get_any_page(struct page *p, unsigned long flags)
 				if (pass++ < GET_PAGE_MAX_RETRY_NUM)
 					goto try_again;
 				ret = -EBUSY;
+				set_mf_get_page_status(gp_status, MF_GET_PAGE_RACE);
 			} else if (!PageHuge(p) && !is_free_buddy_page(p)) {
 				/* We raced with put_page, retry. */
 				if (pass++ < GET_PAGE_MAX_RETRY_NUM)
 					goto try_again;
 				ret = -EIO;
+				set_mf_get_page_status(gp_status, MF_GET_PAGE_RACE);
 			}
 			goto out;
 		} else if (ret == -EBUSY) {
@@ -1423,6 +1467,7 @@ static int get_any_page(struct page *p, unsigned long flags)
 				goto try_again;
 			}
 			ret = -EIO;
+			set_mf_get_page_status(gp_status, MF_GET_PAGE_UNHANDLABLE);
 			goto out;
 		}
 	}
@@ -1442,6 +1487,7 @@ static int get_any_page(struct page *p, unsigned long flags)
 		}
 		put_page(p);
 		ret = -EIO;
+		set_mf_get_page_status(gp_status, MF_GET_PAGE_UNHANDLABLE);
 	}
 out:
 	if (ret == -EIO)
@@ -1480,6 +1526,7 @@ static int __get_unpoison_page(struct page *page)
  * get_hwpoison_page() - Get refcount for memory error handling
  * @p:		Raw error page (hit by memory error)
  * @flags:	Flags controlling behavior of error handling
+ * @gp_status:	Optional output for the reason get_any_page() failed
  *
  * get_hwpoison_page() takes a page refcount of an error page to handle memory
  * error on it, after checking that the error page is in a well-defined state
@@ -1503,7 +1550,8 @@ static int __get_unpoison_page(struct page *page)
  *         operations like allocation and free,
  *         -EHWPOISON when the page is hwpoisoned and taken off from buddy.
  */
-static int get_hwpoison_page(struct page *p, unsigned long flags)
+static int get_hwpoison_page(struct page *p, unsigned long flags,
+			     enum mf_get_page_status *gp_status)
 {
 	int ret;

@@ -1511,7 +1559,7 @@ static int get_hwpoison_page(struct page *p, unsigned long flags)
 	if (flags & MF_UNPOISON)
 		ret = __get_unpoison_page(p);
 	else
-		ret = get_any_page(p, flags);
+		ret = get_any_page(p, flags, gp_status);
 	zone_pcp_enable(page_zone(p));

 	return ret;
@@ -2341,6 +2389,7 @@ static int memory_failure_pfn(unsigned long pfn, int flags)
  */
 int memory_failure(unsigned long pfn, int flags)
 {
+	enum mf_get_page_status gp_status = MF_GET_PAGE_OK;
 	struct page *p;
 	struct folio *folio;
 	struct dev_pagemap *pgmap;
@@ -2413,7 +2462,7 @@ int memory_failure(unsigned long pfn, int flags)
 	 * that may make page_ref_freeze()/page_ref_unfreeze() mismatch.
 	 */
 	is_reserved = PageReserved(p);
-	res = get_hwpoison_page(p, flags);
+	res = get_hwpoison_page(p, flags, &gp_status);
 	if (!res) {
 		if (is_free_buddy_page(p)) {
 			if (take_page_off_buddy(p)) {
@@ -2437,9 +2486,13 @@ int memory_failure(unsigned long pfn, int flags)
 		/*
 		 * Pages with PG_reserved set are not currently managed by the
 		 * page allocator (memblock-reserved memory, driver reservations,
-		 * etc.), so classify them as kernel-owned for reporting.
+		 * etc.), so classify them as kernel-owned for reporting. Do the
+		 * same for pages that get_any_page() still cannot handle after
+		 * retries: likely non-LRU/non-buddy pages such as slab, kernel
+		 * stack, page table or vmalloc-backed pages. Transient lifecycle
+		 * races stay as MF_MSG_GET_HWPOISON.
 		 */
-		if (is_reserved)
+		if (is_reserved || gp_status == MF_GET_PAGE_UNHANDLABLE)
 			res = action_result(pfn, MF_MSG_KERNEL, MF_IGNORED);
 		else
 			res = action_result(pfn, MF_MSG_GET_HWPOISON,
@@ -2744,7 +2797,7 @@ int unpoison_memory(unsigned long pfn)
 		goto unlock_mutex;
 	}

-	ghp = get_hwpoison_page(p, MF_UNPOISON);
+	ghp = get_hwpoison_page(p, MF_UNPOISON, NULL);
 	if (!ghp) {
 		if (folio_test_hugetlb(folio)) {
 			huge = true;
@@ -2951,7 +3004,7 @@ int soft_offline_page(unsigned long pfn, int flags)

 retry:
 	get_online_mems();
-	ret = get_hwpoison_page(page, flags | MF_SOFT_OFFLINE);
+	ret = get_hwpoison_page(page, flags | MF_SOFT_OFFLINE, NULL);
 	put_online_mems();

 	if (hwpoison_filter(page)) {
---

I would leave MF_MSG_KERNEL_HIGH_ORDER out for now. That path still
has the allocator race David pointed out, unless there is easy way to
rule that out ...

Also would leave MF_MSG_UNKNOWN out. We don't really know what it is no?
So it's not good basis for a panic decision :)

Maybe better to keep panic_on_unrecoverable_mf simple: classify the
get_any_page() failure reason earlier, but only panic on MF_MSG_KERNEL.

IMHO, making the knob too complicated for memory failures that should be
rare does not seem worth it. Just covering MF_MSG_KERNEL should already
help crash analysis a lot :)

Feel free to pick up any bits that look useful :)

Cheers, Lance

[...]

^ permalink raw reply related

* [PATCH v6 8/8] docs/zh_CN: Add CREDITS translation
From: Kefan Bai @ 2026-05-10 13:53 UTC (permalink / raw)
  To: linux-usb, si.yanteng
  Cc: gregkh, seakeel, alexs, dzm91, corbet, skhan, linux-doc, doubled
In-Reply-To: <cover.1778415392.git.baikefan@leap-io-kernel.com>

Translate .../usb/CREDITS into Chinese

Update the translation through commit 7b2328c5a009
("docs: Fix typo in usb/CREDITS")

Reviewed-by: Yanteng Si <siyanteng@cqsoftware.com.cn>
Signed-off-by: Kefan Bai <baikefan@leap-io-kernel.com>
---
 Documentation/translations/zh_CN/usb/CREDITS | 162 +++++++++++++++++++
 1 file changed, 162 insertions(+)
 create mode 100644 Documentation/translations/zh_CN/usb/CREDITS

diff --git a/Documentation/translations/zh_CN/usb/CREDITS b/Documentation/translations/zh_CN/usb/CREDITS
new file mode 100644
index 000000000000..9df5e311d211
--- /dev/null
+++ b/Documentation/translations/zh_CN/usb/CREDITS
@@ -0,0 +1,162 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. include:: ../disclaimer-zh_CN.rst
+
+:Original: Documentation/usb/CREDITS
+:翻译:
+
+ 白钶凡 Kefan Bai <baikefan@leap-io-kernel.com>
+
+:校译:
+
+
+
+简易 Linux USB 驱动的致谢名单:
+
+以下人员都为 Linux USB 驱动代码作出了贡献(按姓氏字母顺序排列)。
+我相信这份名单本应更长一些,但确实不容易维护。
+如需将自己加入名单,请提交补丁。
+
+  Georg Acher <acher@informatik.tu-muenchen.de>
+  David Brownell <dbrownell@users.sourceforge.net>
+  Alan Cox <alan@lxorguk.ukuu.org.uk>
+  Randy Dunlap <randy.dunlap@intel.com>
+  Johannes Erdfelt <johannes@erdfelt.com>
+  Deti Fliegl <deti@fliegl.de>
+  ham <ham@unsuave.com>
+  Bradley M Keryan <keryan@andrew.cmu.edu>
+  Greg Kroah-Hartman <greg@kroah.com>
+  Pavel Machek <pavel@suse.cz>
+  Paul Mackerras <paulus@cs.anu.edu.au>
+  Petko Manlolov <petkan@dce.bg>
+  David E. Nelson <dnelson@jump.net>
+  Vojtech Pavlik <vojtech@suse.cz>
+  Bill Ryder <bryder@sgi.com>
+  Thomas Sailer <sailer@ife.ee.ethz.ch>
+  Gregory P. Smith <greg@electricrain.com>
+  Linus Torvalds <torvalds@linux-foundation.org>
+  Roman Weissgaerber <weissg@vienna.at>
+  <Kazuki.Yasumatsu@fujixerox.co.jp>
+
+特别感谢:
+
+  Inaky Perez Gonzalez <inaky@peloncho.fis.ucm.es>
+  感谢他发起了 Linux USB 驱动开发工作,并编写了体量较大的 uusbd
+  驱动中的大部分代码。我们从那项工作中学到了很多。
+
+  NetBSD 和 FreeBSD 的 USB 开发者们
+  感谢他们加入 Linux USB 邮件列表,提供建议并分享实现经验。
+
+附加感谢:
+  还要感谢以下公司与个人在硬件、支持、时间投入和开发方面提供的捐赠与帮助
+  (摘自 Inaky 驱动原始的 THANKS 文件):
+
+    以下公司曾帮助我们开发 Linux USB / UUSBD:
+
+        - 3Com GmbH 捐赠了一台 ISDN Pro TA,并在技术问题和测试设备方面为我
+          提供支持。没想到能得到这么大的帮助。
+
+        - USAR Systems 向我们提供了他们出色的 USB 评估套件,
+          使我们能够测试 Linux USB 驱动对最新 USB 规范的符合性。
+          USAR Systems 认识到保持开放操作系统与时俱进的重要性,
+          并以硬件支持这个项目。感谢!
+
+        - 感谢英特尔提供的宝贵帮助。
+
+        - 我们与 Cherry 合作,使 Linux 成为首个内置 USB 支持的操作系统。
+          Cherry 是全球最大的键盘制造商之一。
+
+        - CMD Technology, Inc. 慷慨捐赠了一块 CSA-6700 PCI-to-USB
+          控制卡,用于测试 OHCI 实现。
+
+        - 由于他们对我们的支持,Keytronic 可以放心,
+          他们的键盘能卖给至少 300 万 Linux 用户中的一部分。
+
+        - ing büro h doran [http://www.ibhdoran.com]!
+          在欧洲,想给主板买一个 PC 背板 USB 连接器几乎是不可能的
+          (我自己做的那个相当糟糕 :))。现在我知道该去哪里买漂亮的 USB
+          配件了!
+
+        - Genius Germany 捐赠了一只 USB 鼠标,用于测试鼠标启动协议;
+          他们还捐赠了 F-23 数字摇杆和 NetMouse Pro。感谢!
+
+        - AVM GmbH Berlin 支持我们开发 Linux 下的 AVM ISDN Controller B1 USB 驱动。
+          AVM 是领先的 ISDN 控制器制造商,其主动式设计对包括 Linux 在内的
+          所有操作系统平台开放。
+
+        - 非常感谢 Y-E Data, Inc 捐赠的 FlashBuster-U USB 软驱,
+          使我们能够测试批量传输代码。
+
+        - 感谢 Logitech 捐赠了一只三轴 USB 鼠标。
+
+          Logitech 负责设计、制造并销售各种人机接口设备,
+          在键盘、鼠标、轨迹球、摄像头、扬声器,以及面向游戏和专业用途的
+          控制设备方面拥有悠久历史和丰富经验。
+
+          作为这些设备广为人知的供应商和销售商,他们捐赠了 USB 鼠标、
+          摇杆和扫描仪,以表明 Linux 的重要性,也让 Logitech 的客户
+          能在自己喜欢的操作系统上获得支持,并让所有 Linux 用户都能使用
+          Logitech 以及其他 USB 硬件。
+
+          Logitech 也是 1999 年 2 月 11 日维也纳 Linux 大会的官方赞助商,
+          我们将在会上展示 Linux USB 工作的最新进展。
+
+        - 感谢 CATC 提供 USB Inspector,帮助我们揭开 UHCI 内部实现中
+          那些不为人知的角落。
+
+        - 感谢 Entrega 为开发工作提供 PCI 转 USB 卡、集线器和转换器产品。
+
+        - 感谢 ConnectTech 提供 WhiteHEAT USB 转串口转换器以及相关文档,
+          让这个驱动得以写成。
+
+        - 感谢 ADMtek 提供 Pegasus 和 Pegasus II 评估板、规格说明,
+          以及驱动开发过程中的宝贵建议。
+
+    另外还要感谢以下个人(嘿,顺序不分先后 :))
+
+        - Oren Tirosh <orenti@hishome.net>,
+          他非常耐心地听我唠叨各种 USB 疑问,还给了很多很酷的想法。
+
+        - Jochen Karrer <karrer@wpfd25.physik.uni-wuerzburg.de>,
+          指出了致命 bug,并给出了宝贵建议。
+
+        - Edmund Humemberger <ed@atnet.at>,他在公共关系与项目管理方面
+          为 Linux-USB 项目付出了巨大的努力。
+
+        - Alberto Menegazzi <flash@flash.iol.it> 正在着手编写 UUSBD 文档,加油!
+
+        - Ric Klaren <ia_ric@cs.utwente.nl> 编写了很好的入门文档,
+          与 Alberto 的作品形成良性竞争:)。
+
+        - Christian Groessler <cpg@aladdin.de>,感谢他在那些棘手细节上的帮助。
+
+        - Paul MacKerras 改进了 OHCI 实现,推动了对 iMac 的支持,
+          并提供了大量的改进意见。
+
+        - Fernando Herrera <fherrera@eurielec.etsit.upm.es>
+          负责撰写、维护并不断补充那份期待已久、独一无二又精彩的
+          UUSBD FAQ!太棒了!
+
+        - Rasca Gmelch <thron@gmx.de> 重新启用了 raw 驱动,
+          指出了一些错误,并启动了 uusbd-utils 软件包。
+
+        - Peter Dettori <dettori@ozy.dec.com>,像疯了一样挖掘 bug,
+          还提出了很多很酷的建议,太棒了!
+
+        - 自由软件与 Linux 社区的所有成员,包括 FSF、GNU 项目、
+          MIT X 联盟、TeX 社区等等,谢谢你们!
+
+        - 特别感谢 Richard Stallman 创造了 Emacs!
+
+        - 感谢 linux-usb 邮件列表的所有成员,读了那么多邮件——不开玩笑了,
+          感谢你们提出的所有建议!
+
+        - 感谢 USB Implementers Forum 成员们的帮助与支持。
+
+        - Nathan Myers <ncm@cantrip.org>,感谢他的建议!
+          (希望你喜欢 Cibeles 的派对。)
+
+        - 感谢 Linus Torvalds 创建、开发并管理 Linux。
+
+        - Mike Smith、Craig Keithley、Thierry Giron 和 Janet Schank
+          感谢他们让我认识到标准 USB 集线器其实也没那么“标准”,
+          这有助于我们在标准集线器驱动中加入厂商特定的特殊处理。
--
2.54.0


^ permalink raw reply related

* [PATCH v6 4/8] docs/zh_CN: Add chipidea.rst translation
From: Kefan Bai @ 2026-05-10 13:53 UTC (permalink / raw)
  To: linux-usb, si.yanteng
  Cc: gregkh, seakeel, alexs, dzm91, corbet, skhan, linux-doc, doubled
In-Reply-To: <cover.1778415392.git.baikefan@leap-io-kernel.com>

Translate .../usb/chipidea.rst into Chinese

Update the translation through commit e4157519ad46
("Documentation: usb: correct spelling")

Reviewed-by: Yanteng Si <siyanteng@cqsoftware.com.cn>
Signed-off-by: Kefan Bai <baikefan@leap-io-kernel.com>
---
 .../translations/zh_CN/usb/chipidea.rst       | 142 ++++++++++++++++++
 .../translations/zh_CN/usb/index.rst          |   2 +-
 2 files changed, 143 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/translations/zh_CN/usb/chipidea.rst

diff --git a/Documentation/translations/zh_CN/usb/chipidea.rst b/Documentation/translations/zh_CN/usb/chipidea.rst
new file mode 100644
index 000000000000..433b3fc411fc
--- /dev/null
+++ b/Documentation/translations/zh_CN/usb/chipidea.rst
@@ -0,0 +1,142 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. include:: ../disclaimer-zh_CN.rst
+
+:Original: Documentation/usb/chipidea.rst
+:翻译:
+
+ 白钶凡 Kefan Bai <baikefan@leap-io-kernel.com>
+
+:校译:
+
+
+
+==============================
+ChipIdea 高速双角色控制器驱动
+==============================
+
+1. 如何测试 OTG FSM(HNP 和 SRP)
+---------------------------------
+
+下面以两块 Freescale i.MX6Q Sabre SD 开发板为例,说明如何通过
+sysfs 输入文件演示 OTG 的 HNP 和 SRP 功能。
+
+1.1 如何使能 OTG FSM
+---------------------
+
+1.1.1 在 ``menuconfig`` 中选择 ``CONFIG_USB_OTG_FSM``,并重新编译内核
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+重新构建内核镜像和模块。如果想查看 OTG FSM 的一些内部变量,可以挂载
+``debugfs``;其中有两个文件可以显示 OTG FSM 变量以及部分控制器寄存器的值::
+
+	cat /sys/kernel/debug/ci_hdrc.0/otg
+	cat /sys/kernel/debug/ci_hdrc.0/registers
+
+1.1.2 在控制器节点对应的 ``dts`` 文件中添加以下条目
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+::
+
+	otg-rev = <0x0200>;
+	adp-disable;
+
+1.2 测试步骤
+-------------
+
+1) 给两块 Freescale i.MX6Q Sabre SD 开发板上电,
+   并加载 gadget 类驱动(例如 ``g_mass_storage``)。
+
+2) 用 USB 线连接两块开发板:一端是 micro A 插头,另一端是 micro B 插头。
+
+   插入 micro A 插头的一端是 A 设备,它应枚举另一端的 B 设备。
+
+3) 角色切换
+
+   在 B 设备上执行::
+
+	echo 1 > /sys/bus/platform/devices/ci_hdrc.0/inputs/b_bus_req
+
+   B 设备应接管主机角色并枚举 A 设备。
+
+4) A 设备切回主机角色
+
+   在 B 设备上执行::
+
+	echo 0 > /sys/bus/platform/devices/ci_hdrc.0/inputs/b_bus_req
+
+   或者,通过引入 HNP 轮询,B 端主机可以知道 A 端外设希望切换为主机角色,
+   因而这次角色切换也可以通过 A 端外设响应 B 端主机的轮询,在 A 侧触发。
+   这可以通过在 A 设备上执行下面的命令来完成::
+
+	echo 1 > /sys/bus/platform/devices/ci_hdrc.0/inputs/a_bus_req
+
+   A 设备应切回主机角色并枚举 B 设备。
+
+5) 拔掉 B 设备(拔掉 micro B 插头),并在 10 秒内重新插入;
+   A 设备应重新枚举 B 设备。
+
+6) 拔掉 B 设备(拔掉 micro B 插头),并在 10 秒后重新插入;
+   A 设备不应重新枚举 B 设备。
+
+   如果 A 设备希望使用总线:
+
+   在 A 设备上执行::
+
+	echo 0 > /sys/bus/platform/devices/ci_hdrc.0/inputs/a_bus_drop
+	echo 1 > /sys/bus/platform/devices/ci_hdrc.0/inputs/a_bus_req
+
+   如果 B 设备希望使用总线:
+
+   在 B 设备上执行::
+
+	echo 1 > /sys/bus/platform/devices/ci_hdrc.0/inputs/b_bus_req
+
+7) A 设备关闭总线供电
+
+   在 A 设备上执行::
+
+	echo 1 > /sys/bus/platform/devices/ci_hdrc.0/inputs/a_bus_drop
+
+   A 设备应断开与 B 设备的连接,并关闭总线供电。
+
+8) B 设备发出 SRP 数据脉冲
+
+   在 B 设备上执行::
+
+	echo 1 > /sys/bus/platform/devices/ci_hdrc.0/inputs/b_bus_req
+
+   A 设备应恢复 USB 总线并枚举 B 设备。
+
+1.3 参考文档
+-------------
+《On-The-Go and Embedded Host Supplement to the USB Revision 2.0 Specification
+July 27, 2012 Revision 2.0 version 1.1a》
+
+2. 如何将 USB 用作系统唤醒源
+----------------------------
+下面是在 i.MX6 平台上把 USB 用作系统唤醒源的示例。
+
+2.1 使能核心控制器的唤醒功能::
+
+	echo enabled > /sys/bus/platform/devices/ci_hdrc.0/power/wakeup
+
+2.2 使能 glue 层的唤醒功能::
+
+	echo enabled > /sys/bus/platform/devices/2184000.usb/power/wakeup
+
+2.3 使能 PHY 的唤醒功能(可选)::
+
+	echo enabled > /sys/bus/platform/devices/20c9000.usbphy/power/wakeup
+
+2.4 使能根集线器的唤醒功能::
+
+	echo enabled > /sys/bus/usb/devices/usb1/power/wakeup
+
+2.5 使能相关设备的唤醒功能::
+
+	echo enabled > /sys/bus/usb/devices/1-1/power/wakeup
+
+如果系统只有一个 USB 端口,而你希望在该端口上启用 USB 唤醒功能,
+可以使用下面的脚本::
+
+	for i in $(find /sys -name wakeup | grep usb);do echo enabled > $i;done;
diff --git a/Documentation/translations/zh_CN/usb/index.rst b/Documentation/translations/zh_CN/usb/index.rst
index a63ece18302d..70fe33fc37d9 100644
--- a/Documentation/translations/zh_CN/usb/index.rst
+++ b/Documentation/translations/zh_CN/usb/index.rst
@@ -19,10 +19,10 @@ USB 支持

     acm
     authorization
+    chipidea

 Todolist:

-* chipidea
 * dwc3
 * ehci
 * usbmon
--
2.54.0


^ permalink raw reply related

* [PATCH v6 5/8] docs/zh_CN: Add dwc3.rst translation
From: Kefan Bai @ 2026-05-10 13:53 UTC (permalink / raw)
  To: linux-usb, si.yanteng
  Cc: gregkh, seakeel, alexs, dzm91, corbet, skhan, linux-doc, doubled
In-Reply-To: <cover.1778415392.git.baikefan@leap-io-kernel.com>

Translate .../usb/dwc3.rst into Chinese

Update the translation through commit ecefae6db042
("docs: usb: rename files to .rst and add them to drivers-api")

Reviewed-by: Yanteng Si <siyanteng@cqsoftware.com.cn>
Signed-off-by: Kefan Bai <baikefan@leap-io-kernel.com>
---
 Documentation/translations/zh_CN/usb/dwc3.rst | 60 +++++++++++++++++++
 .../translations/zh_CN/usb/index.rst          |  2 +-
 2 files changed, 61 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/translations/zh_CN/usb/dwc3.rst

diff --git a/Documentation/translations/zh_CN/usb/dwc3.rst b/Documentation/translations/zh_CN/usb/dwc3.rst
new file mode 100644
index 000000000000..92108ff8cc80
--- /dev/null
+++ b/Documentation/translations/zh_CN/usb/dwc3.rst
@@ -0,0 +1,60 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. include:: ../disclaimer-zh_CN.rst
+
+:Original: Documentation/usb/dwc3.rst
+:翻译:
+
+ 白钶凡 Kefan Bai <baikefan@leap-io-kernel.com>
+
+:校译:
+
+
+
+===========
+DWC3 驱动
+===========
+
+
+待办
+~~~~~~
+
+阅读时如果想顺手认领点任务,可以从下面挑一项 :)
+
+- 将中断处理程序改为每个端点各自使用线程化 IRQ
+
+  事实证明,有些 DWC3 命令大约需要 ``~1 ms`` 才能完成。
+  当前代码会一直自旋等待命令完成,这种设计并不好。
+
+  实现思路:
+
+  - DWC 核心实现了一个按端点对中断进行解复用的 IRQ 控制器。中断号在
+    探测(``probe``)阶段分配,并归属于该设备。如果硬件通过 ``MSI`` 为每个端点
+    提供独立中断,那么这个“虚拟”IRQ 控制器就可以被真实的端点中断取代。
+
+  - 在调用 ``usb_ep_enable()`` 时请求并分配中断资源,
+    在调用 ``usb_ep_disable()`` 时释放中断资源。
+    最坏情况下需要 32 个中断,最少是 ``ep0/1`` 的两个中断。
+  - ``dwc3_send_gadget_ep_cmd()`` 将在 ``wait_for_completion_timeout()``
+    中休眠,直到命令完成。
+  - 中断处理程序分为以下几个部分:
+
+    - 设备级主中断处理程序
+      遍历每个事件,并对其调用 ``generic_handle_irq()``。
+      从 ``generic_handle_irq()`` 返回后,确认事件计数器,使中断最终消失。
+
+    - 设备级线程化处理程序
+      无。
+
+    - 端点中断的主处理程序
+      读取事件并尽量处理它。凡是需要睡眠的操作都交给线程处理。
+      事件保存在每个端点的数据结构中。
+      还要注意,一旦把某项工作交给线程处理,就不要再在主处理程序里处理它,
+      以免出现优先级反转之类的问题。
+
+    - 端点中断的线程化处理程序
+      处理剩余的端点工作,这些工作可能会睡眠,例如等待命令完成。
+
+  延迟:
+
+   不应增加延迟,因为中断线程具有较高优先级,会在普通用户态任务之前运行
+   (除非用户更改了调度优先级)。
diff --git a/Documentation/translations/zh_CN/usb/index.rst b/Documentation/translations/zh_CN/usb/index.rst
index 70fe33fc37d9..6d669c41d1cd 100644
--- a/Documentation/translations/zh_CN/usb/index.rst
+++ b/Documentation/translations/zh_CN/usb/index.rst
@@ -20,10 +20,10 @@ USB 支持
     acm
     authorization
     chipidea
+    dwc3

 Todolist:

-* dwc3
 * ehci
 * usbmon
 * functionfs
--
2.54.0


^ permalink raw reply related

* [PATCH v6 6/8] docs/zh_CN: Add ehci.rst translation
From: Kefan Bai @ 2026-05-10 13:53 UTC (permalink / raw)
  To: linux-usb, si.yanteng
  Cc: gregkh, seakeel, alexs, dzm91, corbet, skhan, linux-doc, doubled
In-Reply-To: <cover.1778415392.git.baikefan@leap-io-kernel.com>

Translate .../usb/ehci.rst into Chinese

Update the translation through commit 570eb861243c
("docs: usb: replace some characters")

Reviewed-by: Yanteng Si <siyanteng@cqsoftware.com.cn>
Signed-off-by: Kefan Bai <baikefan@leap-io-kernel.com>
---
 Documentation/translations/zh_CN/usb/ehci.rst | 230 ++++++++++++++++++
 .../translations/zh_CN/usb/index.rst          |   2 +-
 2 files changed, 231 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/translations/zh_CN/usb/ehci.rst

diff --git a/Documentation/translations/zh_CN/usb/ehci.rst b/Documentation/translations/zh_CN/usb/ehci.rst
new file mode 100644
index 000000000000..ea1d72f52efd
--- /dev/null
+++ b/Documentation/translations/zh_CN/usb/ehci.rst
@@ -0,0 +1,230 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. include:: ../disclaimer-zh_CN.rst
+
+:Original: Documentation/usb/ehci.rst
+:翻译:
+
+ 白钶凡 Kefan Bai <baikefan@leap-io-kernel.com>
+
+:校译:
+
+
+
+=========
+EHCI 驱动
+=========
+
+2002年12月27日
+
+EHCI 驱动用于通过支持 USB 2.0 的主机控制器硬件与高速 USB 2.0 设备通信。
+USB 2.0 兼容 USB 1.1 标准,它定义了三种传输速率:
+
+    - “高速”(High Speed)480 Mbit/sec(60 MByte/sec)
+    - “全速”(Full Speed)12 Mbit/sec(1.5 MByte/sec)
+    - “低速”(Low Speed)1.5 Mbit/sec
+
+USB 1.1 仅支持全速与低速。高速设备可以在 USB 1.1 系统上使用,
+但速度会降到 USB 1.1 的速率。
+
+USB 1.1 设备也可以在 USB 2.0 系统上使用。
+当它们插入 EHCI 控制器时,会被交由 USB 1.1 的伴随(companion)控制器处理,
+该控制器通常是 OHCI 或 UHCI。
+
+当 USB 1.1 设备插入 USB 2.0 集线器时,
+它们通过集线器中的事务转换器(Transaction Translator,TT)与 EHCI 控制器交互,
+该转换器将低速或全速事务转换为高速分割事务,从而避免浪费传输带宽。
+
+截至本文撰写时,该驱动已在以下 EHCI 实现上成功运行(按字母顺序):
+Intel、NEC、Philips 和 VIA。
+其他供应商的 EHCI 实现正在陆续问世;
+预计该驱动在这些实现上也可正常运行。
+
+自 2001 年年中起,usb-storage 设备就已可用
+(在 2.4 版该驱动上速度相当不错),
+集线器则直到 2001 年底才开始可用,而其他类型的高速设备
+似乎要等到更多系统内置 USB 2.0 后才会出现。
+这类新系统从 2002 年初开始上市,并在 2002 年下半年变得更加常见。
+
+注意,USB 2.0 支持并不只是 EHCI 本身。它还需要对 Linux-USB
+核心 API 作出其他修改,包括 hub 驱动;不过这些修改并不需要真正改变
+暴露给 USB 设备驱动的基本 ``usbcore`` API。
+
+- David Brownell
+  <dbrownell@users.sourceforge.net>
+
+
+功能
+====
+
+该驱动会定期在 x86 硬件上进行测试,也已在 PPC 硬件上使用,
+因此大小端问题应当已经解决。
+因此可以认为,它已经处理好了所有必要的 PCI 细节,
+所以即便在 DMA 映射有些特殊的系统上,I/O 也应能正常运行。
+
+传输类型
+--------
+
+截至本文撰写时,该驱动应当已经能够很好地处理所有控制传输、批量传输
+和中断传输,包括通过 USB 2.0 集线器中的事务转换器与 USB 1.1 设备通信;
+但仍可能存在 bug。
+
+高速等时(ISO)传输支持也已可用,但截至本文撰写时,
+还没有 Linux 驱动使用这项支持。
+
+目前尚不支持通过事务转换器实现全速等时传输。
+需要注意,ISO 传输的 split transaction 支持与高速 ISO 传输
+几乎无法共用代码,因为 EHCI 用不同的数据结构表示它们。
+因此,目前大多数 USB 音频和视频设备还不能通过高速总线连接使用。
+
+驱动行为
+--------
+
+所有类型的传输都可以排队。
+这意味着来自一个接口驱动的控制传输(或通过 usbfs 发出的控制传输)
+不会干扰另一个驱动的控制传输,而且中断传输可以使用 1 帧的周期,
+而不必担心中断处理开销导致的数据丢失。
+
+
+EHCI 根集线器代码会将 USB 1.1 设备移交给其伴随控制器。
+该驱动不需要了解那些驱动的任何细节;
+一个原本就能正常工作的 OHCI 或 UHCI 驱动,并不会因为 EHCI 驱动也存在而需要更改。
+
+电源管理方面还有一些问题;当前挂起/恢复的行为还不完全正确。
+
+此外,在调度周期性事务(中断和等时传输)时还采取了一些简化处理。
+这些简化会限制可调度的周期性事务数量,
+并且无法使用小于一帧的轮询间隔。
+
+使用方式
+=========
+
+假设有一个 EHCI 控制器(位于 PCI 卡或主板上),并且已将此驱动编译为模块,
+可这样加载::
+
+    # modprobe ehci-hcd
+
+卸载方式::
+
+    # rmmod ehci-hcd
+
+还应加载一个伴随控制器驱动,例如 ``ohci-hcd`` 或 ``uhci-hcd``。
+如果 EHCI 驱动出现任何问题,只需卸载它的模块,
+随后该伴随控制器驱动就会接手此前由 EHCI 驱动处理的所有设备
+(但速度会降低)。
+
+模块参数(传给 ``modprobe``)包括:
+
+    log2_irq_thresh(默认值 0):
+        默认中断延迟的 log2 值,单位是微帧。默认值 0 表示 1 个微帧
+        (125 微秒)。最大值 6 表示 2^6 = 64 个微帧。
+        该值控制 EHCI 控制器发出中断的频率。
+
+如果在 2.5 内核上使用此驱动,并且启用了 USB 调试支持,
+则会在任一 EHCI 控制器的 ``sysfs`` 目录中看到三个文件:
+
+    ``async``
+        转储异步调度,用于控制传输和批量传输。它会显示每个活动的 ``qh``
+        以及待处理的 ``qtd``,通常每个 ``urb`` 对应一个 ``qtd``。
+        (可以在 ``usb-storage`` 做磁盘 I/O 时看它;顺便观察请求队列!)
+
+    ``periodic``
+        转储周期性调度,用于中断传输和等时传输。不显示 ``qtd``。
+
+    ``registers``
+        显示控制器寄存器状态。
+
+这些文件的内容有助于定位驱动问题。
+
+
+设备驱动通常不需要关心自己是否运行在 EHCI 之上,
+但它们可能想检查 ``usb_device->speed == USB_SPEED_HIGH``。
+高速设备能做到全速(或低速)设备做不到的事,
+例如高带宽的周期性传输(中断或 ISO 传输)。
+另外,设备描述符中的某些值
+(例如周期性传输的轮询间隔)在高速模式下使用不同的编码方式。
+
+不过,一定要让设备驱动经过 USB 2.0 集线器的测试。
+当使用事务转换器时,这些集线器报告某些故障(例如断开连接)的方式会不同;
+已经见过一些驱动在遇到与 OHCI 或 UHCI 所报告的不同故障时表现不佳。
+
+性能
+====
+
+USB 2.0 吞吐量主要受两个因素制约:主机控制器处理请求的速度,
+以及设备响应这些请求的速度。480 Mbit/sec 的“原始传输率”
+对所有设备都成立,但总吞吐量还会受到诸如单个高速包之间的延迟、
+驱动是否足够聪明,以及系统整体负载等因素的影响。
+延迟也是性能考量因素。
+
+批量传输最常用于关注吞吐量的场景。
+需要记住的是,批量传输总是以 512 字节包为单位,
+而一个 USB 2.0 微帧中最多只能容纳 13 个这样的包。
+8 个 USB 2.0 微帧构成一个 USB 1.1 帧;
+一个微帧的时长是 1 毫秒 / 8 = 125 微秒。
+
+因此,只要硬件和设备驱动软件都允许,
+批量传输可提供超过 50 MByte/sec 的带宽。
+周期性传输模式(等时和中断)允许使用更大的包大小,
+从而可以逼近所宣称的 480 Mbit/sec 传输率。
+
+硬件性能
+--------
+
+截至本文撰写时,单个 USB 2.0 设备的最大传输速率通常约为 20 MByte/sec。
+这当然会随着时间改变:一些设备现在更快,一些更慢。
+
+第一代 NEC EHCI 实现似乎存在大约 28 MByte/sec 的硬件瓶颈。
+虽然这对单个 20 MByte/sec 的设备显然已经够用,
+但把三个这样的设备挂到同一总线上,并不能得到 60 MByte/sec。
+问题似乎在于控制器硬件无法并发进行 USB 与 PCI 访问,
+因此它每个微帧只会尝试 6 次(也许是 7 次)USB 事务,而不是 13 次。
+(对一个比其他产品早上市一年的芯片来说,这是个合理的妥协!)
+
+
+预计较新的实现会在这方面做得更好,
+通过投入更多芯片面积来解决这个问题,
+使新的主板芯片组更接近 60 MByte/sec 的目标。
+这既包括 NEC 的更新实现,也包括其他厂商的芯片。
+
+
+主机从 EHCI 控制器收到“请求已完成”中断的最小延迟为一个微帧
+(125 微秒)。该延迟可以调节;驱动提供了一个模块选项。
+默认情况下,``ehci-hcd`` 使用最小延迟,
+这意味着当发出一个控制或批量请求时,
+通常可以在不到 250 微秒内得知它已完成
+(具体取决于传输大小)。
+
+软件性能
+--------
+
+即便只是要达到 20 MByte/sec 的传输速率,Linux-USB 设备驱动
+也必须让 EHCI 队列始终保持满载。
+这意味着要发出较大的请求,或者在需要发出一连串小请求时使用批量请求排队。
+如果驱动未做到这一点,那么会直接从性能结果上表现出来。
+
+
+在典型情况下,使用 ``usb_bulk_msg()`` 以 4 KB 块循环写出,
+会浪费超过一半的 USB 2.0 带宽。
+I/O 完成与驱动发出下一次请求之间的延迟,通常会比一次 I/O 本身耗时更长。
+如果同样的循环改用 16 KB 块,会好一些;若使用一连串 128 KB 块,则浪费会少得多。
+
+
+但与其依赖这么大的 I/O 缓冲区来让同步 I/O 高效,
+不如直接向主机控制器排入多个(批量)请求,然后等待它们全部完成
+(或在出错时取消)。
+这种 URB 排队方式对所有 USB 1.1 主机控制器驱动也同样适用。
+
+
+在 Linux 2.5 内核中,定义了新的 ``usb_sg_*()`` API;
+它们会把 scatterlist 中的所有缓冲区都排入队列。
+它们还使用 scatterlist 的 DMA 映射(其中可能应用 IOMMU)并减少中断次数,
+这些都有助于让高速传输尽可能快地运行。
+
+待办:
+   中断传输和等时(ISO)传输的性能问题。
+   这些周期性传输都是完全调度的,因此,主要问题可能在于如何触发高带宽模式。
+
+待办:
+   通过 ``sysfs`` 中的 ``uframe_periodic_max`` 参数,
+   可以分配超过标准 80% 的周期性带宽。
+   后续将对此进行说明。
diff --git a/Documentation/translations/zh_CN/usb/index.rst b/Documentation/translations/zh_CN/usb/index.rst
index 6d669c41d1cd..6c8e75d8cfc9 100644
--- a/Documentation/translations/zh_CN/usb/index.rst
+++ b/Documentation/translations/zh_CN/usb/index.rst
@@ -21,10 +21,10 @@ USB 支持
     authorization
     chipidea
     dwc3
+    ehci

 Todolist:

-* ehci
 * usbmon
 * functionfs
 * functionfs-desc
--
2.54.0


^ permalink raw reply related

* [PATCH v6 0/8] Add Chinese translation for USB subsystem
From: Kefan Bai @ 2026-05-10 13:53 UTC (permalink / raw)
  To: linux-usb, si.yanteng
  Cc: gregkh, seakeel, alexs, dzm91, corbet, skhan, linux-doc, doubled

This patch set adds Chinese translations for the USB documentation.

Apologies for the long delay in revisiting this series. I have now
  rebased it onto the latest docs-next tree, rechecked and polished the
  translations, retested it, and resent it.

Changes in v6:
  - Rebased the series onto the latest docs-next branch in Jon's tree
    (git://git.lwn.net/linux.git), as suggested by Alex Shi.
  - Added the USB maintainers to the Cc list.
  - Rechecked and polished the Chinese translations throughout the series.

Changes in v5:
  - Moved the index.rst entries for acm, authorization, chipidea, dwc3,
    ehci, and usbmon into the corresponding patches so the series builds
    cleanly when applied patch by patch.
  - Removed extra spaces in chipidea.rst.
  - Sent the series to linux-usb@vger.kernel.org for review by
    Chinese-speaking developers, as suggested by Alex Shi and Yanteng Si.
  - Link to v5: https://lore.kernel.org/linux-usb/cover.1765180570.git.baikefan@leap-io-kernel.com/

Changes in v4:
  - Shortened overlong title underline and overline markers.
  - Removed the CREDITS entry from index.rst.
  - Link to v4: https://lore.kernel.org/all/cover.1764674650.git.baikefan@leap-io-kernel.com/

Changes in v3:
  - Updated my sign-off to use my full legal name, as requested by
    Jonathan Corbet.
  - Reviewed and fixed the RST syntax issues noted by Alex Shi.
  - Kept the number of translated files to eight to make submission and
    review more manageable.
  - Link to v3: https://lore.kernel.org/all/cover.1763984424.git.baikefan@leap-io-kernel.com/

Changes in v2:
  - Updated [PATCH 01/25] docs/zh_CN: Add index.rst translation to include
    the corresponding changes to
    Documentation/translations/zh_CN/subsystem-apis.rst.
  - Link to v2: https://lore.kernel.org/all/cover.1763897036.git.baikefan@leap-io-kernel.com/

v1:
  - Link: https://lore.kernel.org/all/20251123074540.34161-1-baikefan@leap-io-kernel.com/

Kefan Bai (8):
  docs/zh_CN: Add index.rst translation
  docs/zh_CN: Add acm.rst translation
  docs/zh_CN: Add authorization.rst translation
  docs/zh_CN: Add chipidea.rst translation
  docs/zh_CN: Add dwc3.rst translation
  docs/zh_CN: Add ehci.rst translation
  docs/zh_CN: Add usbmon.rst translation
  docs/zh_CN: Add CREDITS translation

 .../translations/zh_CN/subsystem-apis.rst     |   2 +-
 Documentation/translations/zh_CN/usb/CREDITS  | 162 ++++++++
 Documentation/translations/zh_CN/usb/acm.rst  | 136 +++++++
 .../translations/zh_CN/usb/authorization.rst  | 132 ++++++
 .../translations/zh_CN/usb/chipidea.rst       | 142 +++++++
 Documentation/translations/zh_CN/usb/dwc3.rst |  60 +++
 Documentation/translations/zh_CN/usb/ehci.rst | 230 +++++++++++
 .../translations/zh_CN/usb/index.rst          |  54 +++
 .../translations/zh_CN/usb/usbmon.rst         | 384 ++++++++++++++++++
 9 files changed, 1301 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/translations/zh_CN/usb/CREDITS
 create mode 100644 Documentation/translations/zh_CN/usb/acm.rst
 create mode 100644 Documentation/translations/zh_CN/usb/authorization.rst
 create mode 100644 Documentation/translations/zh_CN/usb/chipidea.rst
 create mode 100644 Documentation/translations/zh_CN/usb/dwc3.rst
 create mode 100644 Documentation/translations/zh_CN/usb/ehci.rst
 create mode 100644 Documentation/translations/zh_CN/usb/index.rst
 create mode 100644 Documentation/translations/zh_CN/usb/usbmon.rst

--
2.54.0


^ permalink raw reply

* [PATCH v6 3/8] docs/zh_CN: Add authorization.rst translation
From: Kefan Bai @ 2026-05-10 13:53 UTC (permalink / raw)
  To: linux-usb, si.yanteng
  Cc: gregkh, seakeel, alexs, dzm91, corbet, skhan, linux-doc, doubled
In-Reply-To: <cover.1778415392.git.baikefan@leap-io-kernel.com>

Translate .../usb/authorization.rst into Chinese

Update the translation through commit f176638af476
("USB: Remove Wireless USB and UWB documentation")

Reviewed-by: Yanteng Si <siyanteng@cqsoftware.com.cn>
Signed-off-by: Kefan Bai <baikefan@leap-io-kernel.com>
---
 .../translations/zh_CN/usb/authorization.rst  | 132 ++++++++++++++++++
 .../translations/zh_CN/usb/index.rst          |   2 +-
 2 files changed, 133 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/translations/zh_CN/usb/authorization.rst

diff --git a/Documentation/translations/zh_CN/usb/authorization.rst b/Documentation/translations/zh_CN/usb/authorization.rst
new file mode 100644
index 000000000000..71153cded526
--- /dev/null
+++ b/Documentation/translations/zh_CN/usb/authorization.rst
@@ -0,0 +1,132 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. include:: ../disclaimer-zh_CN.rst
+
+:Original: Documentation/usb/authorization.rst
+:翻译:
+
+ 白钶凡 Kefan Bai <baikefan@leap-io-kernel.com>
+
+:校译:
+
+
+=============================
+授权或禁止 USB 设备连接到系统
+=============================
+
+版权 (C) 2007 Inaky Perez-Gonzalez <inaky@linux.intel.com> 英特尔公司
+
+此功能允许你控制 USB 设备是否可以在系统中使用。
+借助它,你可以完全通过用户空间实现对 USB 设备的锁定。
+
+目前,当插入一个 USB 设备时,系统会对其进行配置,其接口会立即向用户开放。
+有了这项改动,只有在 root 授权设备完成配置后,设备才可被使用。
+
+
+用法
+====
+
+授权设备接入::
+
+	$ echo 1 > /sys/bus/usb/devices/DEVICE/authorized
+
+取消对设备的授权::
+
+	$ echo 0 > /sys/bus/usb/devices/DEVICE/authorized
+
+将新连接到 ``hostX`` 的设备默认设为未授权(即锁定)::
+
+	$ echo 0 > /sys/bus/usb/devices/usbX/authorized_default
+
+解除锁定::
+
+	$ echo 1 > /sys/bus/usb/devices/usbX/authorized_default
+
+默认情况下,所有 USB 设备都是授权的。
+向 ``authorized_default`` 属性写入 ``2`` 会使内核默认只授权连接到内部
+USB 端口的设备。
+
+系统锁定示例(比较粗糙)
+------------------------
+
+假设你想实现一个锁定功能,只允许类型为 XYZ 的设备接入
+(例如某台带有外露 USB 端口的自助服务终端)::
+
+  启动系统
+  rc.local ->
+
+   for host in /sys/bus/usb/devices/usb*
+   do
+      echo 0 > $host/authorized_default
+   done
+
+给 udev 挂一个脚本,用于处理新插入的 USB 设备::
+
+ if device_is_my_type $DEV
+ then
+   echo 1 > $device_path/authorized
+ done
+
+
+``device_is_my_type()`` 才是锁定方案真正见功夫的地方。
+仅仅检查 class、type 和 protocol 是否匹配某个值,
+是你能做出的最糟糕的安全验证之一;对想绕过它的人来说,
+这反而是最容易利用的方案。如果你需要真正安全的办法,
+那就该使用加密、证书认证之类的机制。把 USB 存储设备当作
+“钥匙”的一个简单例子可以是::
+
+ function device_is_my_type()
+ {
+   echo 1 > authorized		# 暂时授权它
+                                # FIXME: 确保没人能挂载它
+   mount DEVICENODE /mntpoint
+   sum=$(md5sum /mntpoint/.signature)
+   if [ $sum = $(cat /etc/lockdown/keysum) ]
+   then
+        echo "We are good, connected"
+        umount /mntpoint
+        # 再做一些额外处理,让其他人也能使用它
+   else
+        echo 0 > authorized
+   fi
+ }
+
+
+当然,这个例子很粗糙;真正要做的话,你会想用基于 PKI 的证书校验,
+这样就不必依赖共享密钥之类的东西。不过你应该已经明白意思了。
+任何拿到设备仿真工具包的人都能伪造描述符和设备信息。
+别信这个。
+
+接口授权
+--------
+
+也有类似的方法用于允许或拒绝特定 USB 接口。
+这使得你可以只阻止某个 USB 设备中的部分接口。
+
+授权接口::
+
+	$ echo 1 > /sys/bus/usb/devices/INTERFACE/authorized
+
+取消接口授权::
+
+	$ echo 0 > /sys/bus/usb/devices/INTERFACE/authorized
+
+也可以更改特定 USB 总线上新接口的默认授权值。
+
+默认允许接口::
+
+	$ echo 1 > /sys/bus/usb/devices/usbX/interface_authorized_default
+
+默认拒绝接口::
+
+	$ echo 0 > /sys/bus/usb/devices/usbX/interface_authorized_default
+
+默认情况下,``interface_authorized_default`` 位为 ``1``,
+因此所有接口默认都处于已授权状态。
+
+注意:
+  如果把一个先前未授权的接口改为已授权,
+  则必须通过将 ``INTERFACE`` 写入 ``/sys/bus/usb/drivers_probe``
+  来手动触发驱动探测。
+
+对于需要多个接口的驱动程序,应先授权所有必需接口,
+然后再触发驱动探测。这样做可以避免副作用。
diff --git a/Documentation/translations/zh_CN/usb/index.rst b/Documentation/translations/zh_CN/usb/index.rst
index 449e8ac2dff0..a63ece18302d 100644
--- a/Documentation/translations/zh_CN/usb/index.rst
+++ b/Documentation/translations/zh_CN/usb/index.rst
@@ -18,10 +18,10 @@ USB 支持
     :maxdepth: 1

     acm
+    authorization

 Todolist:

-* authorization
 * chipidea
 * dwc3
 * ehci
--
2.54.0


^ permalink raw reply related

* [PATCH v6 7/8] docs/zh_CN: Add usbmon.rst translation
From: Kefan Bai @ 2026-05-10 13:53 UTC (permalink / raw)
  To: linux-usb, si.yanteng
  Cc: gregkh, seakeel, alexs, dzm91, corbet, skhan, linux-doc, doubled
In-Reply-To: <cover.1778415392.git.baikefan@leap-io-kernel.com>

Translate .../usb/usbmon.rst into Chinese

Update the translation through commit 788183a6e8b0
("docs: usb: fix literal block marker in usbmon verification example")

Reviewed-by: Yanteng Si <siyanteng@cqsoftware.com.cn>
Signed-off-by: Kefan Bai <baikefan@leap-io-kernel.com>
---
 .../translations/zh_CN/usb/index.rst          |   2 +-
 .../translations/zh_CN/usb/usbmon.rst         | 384 ++++++++++++++++++
 2 files changed, 385 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/translations/zh_CN/usb/usbmon.rst

diff --git a/Documentation/translations/zh_CN/usb/index.rst b/Documentation/translations/zh_CN/usb/index.rst
index 6c8e75d8cfc9..9df11bd4721c 100644
--- a/Documentation/translations/zh_CN/usb/index.rst
+++ b/Documentation/translations/zh_CN/usb/index.rst
@@ -22,10 +22,10 @@ USB 支持
     chipidea
     dwc3
     ehci
+    usbmon

 Todolist:

-* usbmon
 * functionfs
 * functionfs-desc
 * gadget_configfs
diff --git a/Documentation/translations/zh_CN/usb/usbmon.rst b/Documentation/translations/zh_CN/usb/usbmon.rst
new file mode 100644
index 000000000000..8142e00e353e
--- /dev/null
+++ b/Documentation/translations/zh_CN/usb/usbmon.rst
@@ -0,0 +1,384 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. include:: ../disclaimer-zh_CN.rst
+
+:Original: Documentation/usb/usbmon.rst
+:翻译:
+
+ 白钶凡 Kefan Bai <baikefan@leap-io-kernel.com>
+
+:校译:
+
+
+
+======
+usbmon
+======
+
+简介
+====
+小写形式的 ``usbmon`` 指的是内核中的一项功能,用于收集 USB 总线上的
+I/O 跟踪信息。它类似于网络监控工具 ``tcpdump(1)`` 或 Ethereal 所使用的
+数据包套接字。类似地,人们希望使用 usbdump 或 USBMon
+(首字母大写)之类的工具来检查 usbmon 生成的原始跟踪数据。
+
+usbmon 报告的是各个外设驱动向主机控制器驱动(HCD)发出的请求。
+因此,如果 HCD 本身有 bug,那么 usbmon 报告的跟踪信息可能无法精确对应
+实际的总线事务。这和 tcpdump 的情况是一样的。
+
+目前实现了两种 API: ``text`` 和 ``binary``。二进制 API 通过 ``/dev``
+命名空间中的字符设备提供,并且属于 ABI。文本 API 自内核 2.6.35 起
+已废弃,但为了方便仍然可用。
+
+如何使用 usbmon 收集原始文本跟踪信息
+====================================
+
+与数据包套接字不同,usbmon 提供了一种接口,可以输出文本格式的跟踪信息。
+这样做有两个目的:
+第一,在更完善的格式最终确定之前,它作为工具间通用的跟踪交换格式;
+第二,在不使用工具的情况下,人们也可以直接阅读这些信息。
+
+要收集原始文本跟踪信息,请按以下步骤进行操作。
+
+1. 准备
+--------
+
+挂载 debugfs(内核配置中必须启用它),并加载 usbmon 模块
+(如果它是作为模块构建的)。如果 usbmon 已经编入内核,
+那么第二步可以省略。
+
+命令示例::
+
+    # mount -t debugfs none_debugs /sys/kernel/debug
+    # modprobe usbmon
+    #
+
+确认总线套接字是否存在::
+
+    # ls /sys/kernel/debug/usb/usbmon
+    0s  0u  1s  1t  1u  2s  2t  2u  3s  3t  3u  4s  4t  4u
+    #
+
+现在,你可以选择使用 ``0u`` 捕获所有总线上的数据包,并跳到第 3 步;
+也可以先按第 2 步找到目标设备所在的总线。
+这样可以过滤掉那些持续输出数据的烦人设备。
+
+2. 查找目标设备连接的是哪条总线
+-------------------------------
+
+运行 ``cat /sys/kernel/debug/usb/devices``,找到对应设备的 T 行。
+通常可以通过厂商字符串来查找。如果有许多类似设备,
+可以拔掉其中一个,再比较前后两次 ``/sys/kernel/debug/usb/devices``
+的输出。T 行里会包含总线编号。
+
+示例::
+
+  T:  Bus=03 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12  MxCh= 0
+  D:  Ver= 1.10 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
+  P:  Vendor=0557 ProdID=2004 Rev= 1.00
+  S:  Manufacturer=ATEN
+  S:  Product=UC100KM V2.00
+
+``Bus=03`` 表示它位于 3 号总线上。或者,也可以查看 ``lsusb`` 的输出,
+并从对应行得到总线编号。
+
+示例如下::
+
+  Bus 003 Device 002: ID 0557:2004 ATEN UC100KM V2.00
+
+
+3. 启动 cat 命令
+--------------------
+
+如果只监听单条总线,可执行::
+
+    # cat /sys/kernel/debug/usb/usbmon/3u > /tmp/1.mon.out
+
+否则,如果要监听所有总线,则执行::
+
+    # cat /sys/kernel/debug/usb/usbmon/0u > /tmp/1.mon.out
+
+此进程会一直读取,直到被终止。
+由于输出通常会很长,因此更推荐将输出重定向到某个位置。
+
+
+4. 在 USB 总线上执行期望的操作
+------------------------------
+
+此处需要执行一些会产生 USB 流量的动作,比如插入 U 盘、拷贝文件、操作摄像头等。
+
+
+5. 停止 cat
+-----------
+
+这一步通常通过键盘中断(Control-C)完成。
+
+此时输出文件(本例中为 ``/tmp/1.mon.out``)可以保存、通过电子邮件发送,
+或使用文本编辑器查看。
+如果使用最后一种方式,请确保文件不会大到编辑器无法打开。
+
+
+原始文本数据格式
+================
+
+目前支持两种格式:原始格式,也就是 ``1t`` 格式,以及 ``1u`` 格式。
+``1t`` 格式在内核 2.6.21 中已被废弃。``1u`` 格式增加了一些字段,
+例如 ISO 帧描述符、``interval`` 等。它生成的行会稍长一些,
+但在其他方面是 ``1t`` 格式的完整超集。
+
+如果程序需要区分上述两种格式,可以查看 ``address`` 字段(见下文)。
+如果其中有两个冒号,就是 ``1t`` 格式;否则是 ``1u`` 格式。
+
+任何文本格式的数据由一系列事件组成,如 URB 提交、URB 回调、提交错误等。
+每个事件对应单独的一行文本,由使用空白符间隔的若干字段组成。
+字段的数量与位置可能取决于事件类型,但以下字段对所有类型都通用:
+
+下面按从左到右的顺序列出这些共有字段:
+
+- URB Tag。用于标识 URB,通常是 URB 结构体在内核中的地址(以十六进制表示),
+  但也可能是序号或其他合理的唯一字符串。
+
+- 时间戳(微秒),十进制数字。时间戳的精度取决于可用时钟,因此可能远差于
+  1 微秒(例如实现使用的是 jiffies)。
+
+- 事件类型。它表示的是事件的格式,而不是 URB 的类型。
+  可用值为:``S`` 表示提交,``C`` 表示回调,``E`` 表示提交错误。
+
+- ``Address`` 字段(以前称作 ``pipe``)。它包含四个由冒号分隔的字段:
+  URB 类型及方向、总线号、设备地址和端点号。类型与方向的编码如下:
+
+    == ==   ==========================
+    Ci Co   控制输入和输出
+    Zi Zo   等时输入和输出
+    Ii Io   中断输入和输出
+    Bi Bo   批量输入和输出
+    == ==   ==========================
+
+  总线号、设备地址和端点号使用十进制,但可能有前导零。
+
+- URB 状态字段。这个字段要么是一个字母,要么是几个由冒号分隔的数字:
+  URB 状态、``interval``、``start frame`` 和 ``error count``。
+  与 ``address`` 字段不同,除了状态外,其余字段都是可选的。
+  ``interval`` 只会为中断和等时 URB 打印;``start frame`` 只会为
+  等时 URB 打印;错误计数只会在等时回调事件中打印。
+
+  状态字段是一个十进制数字,有时为负数,对应 URB 的 ``status`` 字段。
+  对于提交事件,这个字段本身没有实际意义,但为了便于脚本解析,它仍然存在。
+  当发生错误时,该字段包含错误码。
+
+  在提交控制包时,这个字段包含的是 ``Setup Tag``,而不是一组数字。
+  判断 ``Setup Tag`` 是否存在很容易,因为它从来不是数字。
+  因此,如果脚本在这个字段里发现的是一组数字,
+  就会继续读取数据长度(等时 URB 除外)。
+  如果发现的是其他内容,比如一个字母,
+  那么脚本会先读取 ``Setup`` 包,再读取数据长度或等时描述符。
+
+- ``Setup`` 包由 5 个字段组成:``bmRequestType``、``bRequest``、``wValue``、
+  ``wIndex`` 和 ``wLength``。这些字段由 USB 2.0 规范定义。
+  如果 ``Setup Tag`` 为 ``s``,就可以安全地解码这些字段。
+  否则,说明 Setup 包虽然存在,但并未被捕获,此时各字段中会填入占位内容。
+
+- 等时传输帧描述符的数量及其内容:
+  如果一个等时传输事件带有一组描述符,首先打印该 URB 中描述符的总数,
+  然后为每个描述符打印一个字段,最多打印 5 个字段。
+  每个字段由三个用冒号分隔的十进制数字组成,
+  分别表示状态(status)、偏移(offset)和长度(length)。
+  对于提交(submission),报告的是初始长度;
+  对于回调(callback),报告的是实际长度。
+
+- 数据长度:
+  对于提交,表示请求的长度;对于回调,表示实际传输的长度。
+
+- 数据标签:
+  即使数据长度非零,usbmon 也不一定会捕获数据。仅当标签为 ``=`` 时,才会有数据字段。
+
+- 数据字段:
+  以大端十六进制格式显示。注意,这些并不是真正的机器字,
+  而只是把字节流拆成若干“字”以便阅读。因此最后一个字可能只包含
+  1 到 4 个字节。
+  收集的数据长度是有限的,可能小于数据长度字段中报告的值。
+  因为数据长度字段只统计实际接收到的字节,而数据字段包含整个传输缓冲区,
+  所以,在等时输入(Zi)完成且缓冲区中接收到的数据稀疏的情况下,
+  收集的数据长度可能大于数据长度字段的值。
+
+
+
+示例:
+
+获取端口状态的输入控制传输::
+
+    d5ea89a0 3575914555 S Ci:1:001:0 s a3 00 0000 0003 0004 4 <
+    d5ea89a0 3575914560 C Ci:1:001:0 0 4 = 01050000
+
+向地址为 5 的存储设备发送 31 字节 Bulk 包装的 SCSI 命令 ``0x28``
+(``READ_10``)的输出批量传输::
+
+    dd65f0e8 4128379752 S Bo:1:005:2 -115 31 = 55534243 ad000000 00800000 80010a28 20000000 20000040 00000000 000000
+    dd65f0e8 4128379808 C Bo:1:005:2 0 31 >
+
+原始二进制格式与 API
+=====================
+API 的整体架构与前文大体相同,只是事件以二进制格式传递。
+每个事件都通过下面的结构发送(这个名字是为了叙述方便而虚构的)::
+
+
+  struct usbmon_packet {
+	u64 id;			/*  0: URB ID - 从提交到回调 */
+	unsigned char type;	/*  8: 与文本相同;可扩展 */
+	unsigned char xfer_type; /*    ISO (0)、中断、控制、批量 (3) */
+	unsigned char epnum;	/*     端点号和传输方向 */
+	unsigned char devnum;	/*     设备地址 */
+	u16 busnum;		/* 12: 总线号 */
+	char flag_setup;	/* 14: 与文本相同 */
+	char flag_data;		/* 15: 与文本相同;二进制零也可 */
+	s64 ts_sec;		/* 16: gettimeofday */
+	s32 ts_usec;		/* 24: gettimeofday */
+	int status;		/* 28: */
+	unsigned int length;	/* 32: 数据长度(提交或实际) */
+	unsigned int len_cap;	/* 36: 已捕获的数据长度 */
+	union {			/* 40: */
+		unsigned char setup[SETUP_LEN];	/* 仅用于控制类 S 事件 */
+		struct iso_rec {		/* 仅用于 ISO */
+			int error_count;
+			int numdesc;
+		} iso;
+	} s;
+	int interval;		/* 48: 仅用于中断和 ISO */
+	int start_frame;	/* 52: 仅用于 ISO */
+	unsigned int xfer_flags; /* 56: URB 的 transfer_flags 副本 */
+	unsigned int ndesc;	/* 60: 实际 ISO 描述符数量 */
+  };				/* 64 总长度 */
+
+可以用 ``read(2)``、``ioctl(2)``,或者通过 ``mmap`` 访问缓冲区,
+从字符设备接收这些事件。不过,出于兼容性原因,``read(2)``
+只返回前 48 个字节。
+
+字符设备通常命名为 ``/dev/usbmonN``,其中 ``N`` 是 USB 总线号。
+编号为零的设备(``/dev/usbmon0``)比较特殊,表示“所有总线”。
+请注意,具体命名策略由 Linux 发行版决定。
+
+如果你手动创建 ``/dev/usbmon0``,请确保它归 root 所有,并且权限为 ``0600``。
+否则,非特权用户将能够窃听键盘流量。
+
+以下 ``MON_IOC_MAGIC`` 为 ``0x92`` 的 ioctl 调用可用:
+
+``MON_IOCQ_URB_LEN``,定义为 ``_IO(MON_IOC_MAGIC, 1)``
+
+该调用返回下一个事件的数据长度。注意大多数事件不包含数据,
+因此如果该调用返回零,并不意味着没有事件。
+
+``MON_IOCG_STATS``,定义为
+``_IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)``
+
+参数是指向以下结构的指针::
+
+  struct mon_bin_stats {
+	u32 queued;
+	u32 dropped;
+  };
+
+成员 ``queued`` 表示当前缓冲区中已经排队的事件数量,
+而不是自上次重置以来处理过的事件数量。
+
+成员 ``dropped`` 表示自上次调用 ``MON_IOCG_STATS`` 以来丢失的事件数量。
+
+``MON_IOCT_RING_SIZE``,定义为 ``_IO(MON_IOC_MAGIC, 4)``
+
+此调用设置缓冲区大小。参数为以字节为单位的缓冲区大小。
+大小可能会向下取整到下一个块(或页)。
+如果请求的大小超出该内核的 [未指定] 范围,则调用会失败并返回 ``-EINVAL``。
+
+``MON_IOCQ_RING_SIZE``,定义为 ``_IO(MON_IOC_MAGIC, 5)``
+
+该调用返回缓冲区当前大小(以字节为单位)。
+
+``MON_IOCX_GET``,定义为 ``_IOW(MON_IOC_MAGIC, 6, struct mon_get_arg)``
+``MON_IOCX_GETX``,定义为 ``_IOW(MON_IOC_MAGIC, 10, struct mon_get_arg)``
+
+如果内核缓冲区中没有事件,这些调用就会一直等待,直到有事件到达,
+然后返回第一个事件。
+参数是指向以下结构的指针::
+
+  struct mon_get_arg {
+	struct usbmon_packet *hdr;
+	void *data;
+	size_t alloc;		/* 数据长度可以为零 */
+  };
+
+
+调用前,应填好 ``hdr``、``data`` 和 ``alloc``。
+调用返回后,``hdr`` 指向的区域中包含下一个事件的结构;
+如果存在数据,那么数据缓冲区中也会包含相应数据。
+该事件会从内核缓冲区中移除。
+
+``MON_IOCX_GET`` 会将 48 字节的数据复制到 ``hdr`` 区域,
+``MON_IOCX_GETX`` 会复制 64 字节。
+
+``MON_IOCX_MFETCH``,定义为
+``_IOWR(MON_IOC_MAGIC, 7, struct mon_mfetch_arg)``
+
+当应用程序通过 ``mmap(2)`` 访问缓冲区时,主要使用这个 ioctl。
+其参数是指向以下结构的指针::
+
+  struct mon_mfetch_arg {
+	uint32_t *offvec;	/* 获取的事件偏移向量 */
+	uint32_t nfetch;	/* 要获取的事件数量(输出:已获取) */
+	uint32_t nflush;	/* 要刷新的事件数量 */
+  };
+
+
+该 ioctl 的操作分为三个阶段:
+
+首先,从内核缓冲区移除并丢弃最多 ``nflush`` 个事件。
+实际丢弃的事件数量会写回 ``nflush``。
+
+其次,除非伪设备以 ``O_NONBLOCK`` 打开,否则会一直等待,
+直到缓冲区中出现事件。
+
+第三,将最多 ``nfetch`` 个偏移量提取到 mmap 缓冲区,并存入
+``offvec`` 中。实际提取到的事件偏移数量会存回 ``nfetch``。
+
+``MON_IOCH_MFLUSH``,定义为 ``_IO(MON_IOC_MAGIC, 8)``
+
+此调用从内核缓冲区移除若干事件。其参数为要移除的事件数量。
+如果缓冲区中的事件少于请求数量,则移除所有事件,且不报告错误。
+当没有事件时也可使用。
+
+``FIONBIO``
+
+如果有需要,将来可能会实现 ``FIONBIO`` ioctl。
+
+除了 ``ioctl(2)`` 和 ``read(2)`` 之外,
+二进制 API 的特殊文件也可以用 ``select(2)`` 和 ``poll(2)`` 轮询。
+但 ``lseek(2)`` 不起作用。
+
+* 二进制 API 的内核缓冲区内存映射访问
+
+基本思想很简单:
+
+准备时,先获取当前大小,再用 ``mmap(2)`` 映射缓冲区。
+然后执行类似下面伪代码的循环::
+
+   struct mon_mfetch_arg fetch;
+   struct usbmon_packet *hdr;
+   int nflush = 0;
+   for (;;) {
+      fetch.offvec = vec; // 有 N 个 32 位字
+      fetch.nfetch = N;   // 或者少于 N
+      fetch.nflush = nflush;
+      ioctl(fd, MON_IOCX_MFETCH, &fetch);   // 同时处理错误
+      nflush = fetch.nfetch;       // 完成后要刷新这么多包
+      for (i = 0; i < nflush; i++) {
+         hdr = (struct ubsmon_packet *) &mmap_area[vec[i]];
+         if (hdr->type == '@')     // 填充包
+            continue;
+         caddr_t data = &mmap_area[vec[i]] + 64;
+         process_packet(hdr, data);
+      }
+   }
+
+
+
+因此,主要思想是每 N 个事件只执行一次 ioctl。
+
+虽然缓冲区是环形的,但返回的头和数据不会跨越缓冲区末端,
+因此上面的伪代码无需任何合并操作。
--
2.54.0


^ permalink raw reply related

* [PATCH v6 1/8] docs/zh_CN: Add index.rst translation
From: Kefan Bai @ 2026-05-10 13:53 UTC (permalink / raw)
  To: linux-usb, si.yanteng
  Cc: gregkh, seakeel, alexs, dzm91, corbet, skhan, linux-doc, doubled
In-Reply-To: <cover.1778415392.git.baikefan@leap-io-kernel.com>

Translate .../usb/index.rst into Chinese and update subsystem-apis.rst

Update the translation through commit a592a36e4937
("Documentation: use a source-read extension for the index link boilerplate")

Reviewed-by: Yanteng Si <siyanteng@cqsoftware.com.cn>
Signed-off-by: Kefan Bai <baikefan@leap-io-kernel.com>
---
 .../translations/zh_CN/subsystem-apis.rst     |  2 +-
 .../translations/zh_CN/usb/index.rst          | 54 +++++++++++++++++++
 2 files changed, 55 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/translations/zh_CN/usb/index.rst

diff --git a/Documentation/translations/zh_CN/subsystem-apis.rst b/Documentation/translations/zh_CN/subsystem-apis.rst
index 830217140fb6..b52e1feb0167 100644
--- a/Documentation/translations/zh_CN/subsystem-apis.rst
+++ b/Documentation/translations/zh_CN/subsystem-apis.rst
@@ -90,6 +90,7 @@ TODOList:
    security/index
    PCI/index
    peci/index
+   usb/index

 TODOList:

@@ -104,6 +105,5 @@ TODOList:
 * accel/index
 * crypto/index
 * bpf/index
-* usb/index
 * misc-devices/index
 * wmi/index
diff --git a/Documentation/translations/zh_CN/usb/index.rst b/Documentation/translations/zh_CN/usb/index.rst
new file mode 100644
index 000000000000..7cfe99a4dc0a
--- /dev/null
+++ b/Documentation/translations/zh_CN/usb/index.rst
@@ -0,0 +1,54 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. include:: ../disclaimer-zh_CN.rst
+
+:Original: Documentation/usb/index.rst
+:翻译:
+
+ 白钶凡 Kefan Bai <baikefan@leap-io-kernel.com>
+
+:校译:
+
+
+
+===========
+USB 支持
+===========
+
+.. toctree::
+    :maxdepth: 1
+
+
+Todolist:
+
+* acm
+* authorization
+* chipidea
+* dwc3
+* ehci
+* usbmon
+* functionfs
+* functionfs-desc
+* gadget_configfs
+* gadget_hid
+* gadget_multi
+* gadget_printer
+* gadget_serial
+* gadget_uvc
+* gadget-testing
+* iuu_phoenix
+* mass-storage
+* misc_usbsevseg
+* mtouchusb
+* ohci
+* raw-gadget
+* usbip_protocol
+* usb-serial
+* usb-help
+* text_files
+
+.. only::  subproject and html
+
+   索引
+   =======
+
+   * :ref:`genindex`
--
2.54.0


^ permalink raw reply related

* Re: [PATCH RFC v5 10/53] KVM: guest_memfd: Add basic support for KVM_SET_MEMORY_ATTRIBUTES2
From: Liam R. Howlett @ 2026-05-10 13:43 UTC (permalink / raw)
  To: Ackerley Tng
  Cc: aik, andrew.jones, binbin.wu, brauner, chao.p.peng, david,
	ira.weiny, jmattson, jthoughton, michael.roth, oupton,
	pankaj.gupta, qperret, rick.p.edgecombe, rientjes, shivankg,
	steven.price, tabba, willy, wyihan, yan.y.zhao, forkloop,
	pratyush, suzuki.poulose, aneesh.kumar, Paolo Bonzini,
	Sean Christopherson, Thomas Gleixner, Ingo Molnar,
	Borislav Petkov, Dave Hansen, x86, H. Peter Anvin, Steven Rostedt,
	Masami Hiramatsu, Mathieu Desnoyers, Jonathan Corbet, Shuah Khan,
	Shuah Khan, Vishal Annapurve, Andrew Morton, Chris Li,
	Kairui Song, Kemeng Shi, Nhat Pham, Baoquan He, Barry Song,
	Axel Rasmussen, Yuanchu Xie, Wei Xu, Youngjun Park, Qi Zheng,
	Shakeel Butt, Kiryl Shutsemau, Jason Gunthorpe, Vlastimil Babka,
	kvm, linux-kernel, linux-trace-kernel, linux-doc, linux-kselftest,
	linux-mm, linux-coco
In-Reply-To: <CAEvNRgF9+Gr7UVEq-E2SQEb_XOQQMOXy9F_A2tA=DbNV_fJ0EQ@mail.gmail.com>

On 7 May 2026 12:56:11 GMT-04:00, Ackerley Tng <ackerleytng@google.com> wrote:
>"Liam R. Howlett" <liam@infradead.org> writes:
>
>> On 26/04/28 04:25PM, Ackerley Tng via B4 Relay wrote:
>>>
>>> [...snip...]
>>>
>>> +/*
>>> + * Preallocate memory for attributes to be stored on a maple tree, pointed to
>>> + * by mas.  Adjacent ranges with attributes identical to the new attributes
>>> + * will be merged.  Also sets mas's bounds up for storing attributes.
>>> + *
>>> + * This maintains the invariant that ranges with the same attributes will
>>> + * always be merged.
>>> + */
>>> +static int kvm_gmem_mas_preallocate(struct ma_state *mas, u64 attributes,
>>> +				    pgoff_t start, size_t nr_pages)
>>> +{
>>> +	pgoff_t end = start + nr_pages;
>>> +	pgoff_t last = end - 1;
>>> +	void *entry;
>>> +
>>> +	/* Try extending range. entry is NULL on overflow/wrap-around. */
>>> +	mas_set_range(mas, end, end);
>>> +	entry = mas_find(mas, end);
>
>Thank you for your reviews!
>
>>
>> Please read the documentation as I believe you have a bug here.  What
>> happens if there is another range stored higher than end + 1?
>>
>
>The invariant in this maple tree is that contiguous ranges with the same
>attribute are stored as a single range.
>
>The goal of this first part is to get the entry at the index just after
>the requested range, and see what the attribute there is. If that
>attribute is what we're about to set, extend the requested range for
>storing to the end of that range.
>
>If there is another range higher than end + 1, with the invariant
>maintained, that attribute has to be different than the attribute stored
>at end. Hence, we only want to extend this requested range up till end.
>

mas_find() will look for an entry at the given address for the first search, and if it is not found it will continue to search upwards.  Since you limit the search to end, it will work as you want and there isn't a bug as I was thinking in my sleep deprived state.

Since you are searching for exactly one address (end), it might serve you better to walk there.  Maybe walking is a better API for what you are doing here?


>> Do you have testing of these functions somewhere?
>>
>
>GMEM_CONVERSION_MULTIPAGE_TEST_INIT_SHARED(indexing, 4) tests setting
>attributes in ranges. If test_page is 2,
>
>1. [0, 4) starts off shared (4 is the number of pages in the guest_memfd)
>2. [2, 3) is converted to private
>    => so the ranges should now be [0, 2), [2, 3), [3, 4)
>3. [2, 3) is converted back to shared
>    => so the ranges should now be [0, 4)
>
>I verified this by inserting some trace_printk()s and inspecting manually.
>

Thanks.  I find the exclusive ranges a bit odd to think about in the maple tree context, but this test case makes sense.  This is especially odd to look at a single index entry, at least for me.

I generally have a set of test cases and append any bug reproduces to that list so they are unlikely to reoccur.  My testing is certainly different from what you'll be doing, but this method has done well with the quality of code improving over time, and limited (if any) regressions.

I actually insist that any fix has a test before I accept them.  There are two reasons for this: 1. Avoiding the regression. 2. People really understand the bug if they can create a reproducer.

I hope this helps.


>>> +	if (entry && xa_to_value(entry) == attributes)
>>> +		last = mas->last;
>>> +
>>> +	if (start > 0) {
>>> +		mas_set_range(mas, start - 1, start - 1);
>>> +		entry = mas_find(mas, start - 1);
>>> +		if (entry && xa_to_value(entry) == attributes)
>>> +			start = mas->index;
>>> +	}
>>> +
>>> +	mas_set_range(mas, start, last);
>>> +	return mas_preallocate(mas, xa_mk_value(attributes), GFP_KERNEL);
>>> +}
>>> +
>>>
>>> [...snip...]
>>>


^ permalink raw reply

* [PATCH v12 11/11] Documentation: ABI: testing: add common ABI file for iio/frequency
From: Rodrigo Alencar via B4 Relay @ 2026-05-10 12:42 UTC (permalink / raw)
  To: linux-kernel, linux-iio, devicetree, linux-doc
  Cc: Jonathan Cameron, David Lechner, Andy Shevchenko,
	Lars-Peter Clausen, Michael Hennerich, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Jonathan Corbet, Andrew Morton,
	Petr Mladek, Steven Rostedt, Andy Shevchenko, Rasmus Villemoes,
	Sergey Senozhatsky, Shuah Khan, Rodrigo Alencar
In-Reply-To: <20260510-adf41513-iio-driver-v12-0-34af2ed2779f@analog.com>

From: Rodrigo Alencar <rodrigo.alencar@analog.com>

Add ABI documentation file for PLL/DDS devices with frequency_resolution
sysfs entry attribute used by both ADF4350 and ADF41513.

Signed-off-by: Rodrigo Alencar <rodrigo.alencar@analog.com>
---
 Documentation/ABI/testing/sysfs-bus-iio-frequency         | 11 +++++++++++
 Documentation/ABI/testing/sysfs-bus-iio-frequency-adf4350 | 10 ----------
 2 files changed, 11 insertions(+), 10 deletions(-)

diff --git a/Documentation/ABI/testing/sysfs-bus-iio-frequency b/Documentation/ABI/testing/sysfs-bus-iio-frequency
new file mode 100644
index 000000000000..1ce8ae578fd6
--- /dev/null
+++ b/Documentation/ABI/testing/sysfs-bus-iio-frequency
@@ -0,0 +1,11 @@
+What:		/sys/bus/iio/devices/iio:deviceX/out_altvoltageY_frequency_resolution
+KernelVersion:	6.20
+Contact:	linux-iio@vger.kernel.org
+Description:
+		Stores channel Y frequency resolution/channel spacing in Hz for PLL
+		devices. The given value directly influences the operating mode when
+		fractional-N synthesis is required, as it derives values for
+		configurable modulus parameters used in the calculation of the output
+		frequency. It is assumed that the algorithm that is used to compute
+		the various dividers, is able to generate proper values for multiples
+		of channel spacing.
diff --git a/Documentation/ABI/testing/sysfs-bus-iio-frequency-adf4350 b/Documentation/ABI/testing/sysfs-bus-iio-frequency-adf4350
index 1254457a726e..76987a119feb 100644
--- a/Documentation/ABI/testing/sysfs-bus-iio-frequency-adf4350
+++ b/Documentation/ABI/testing/sysfs-bus-iio-frequency-adf4350
@@ -1,13 +1,3 @@
-What:		/sys/bus/iio/devices/iio:deviceX/out_altvoltageY_frequency_resolution
-KernelVersion:	3.4.0
-Contact:	linux-iio@vger.kernel.org
-Description:
-		Stores channel Y frequency resolution/channel spacing in Hz.
-		The value given directly influences the MODULUS used by
-		the fractional-N PLL. It is assumed that the algorithm
-		that is used to compute the various dividers, is able to
-		generate proper values for multiples of channel spacing.
-
 What:		/sys/bus/iio/devices/iio:deviceX/out_altvoltageY_refin_frequency
 KernelVersion:	3.4.0
 Contact:	linux-iio@vger.kernel.org

-- 
2.43.0



^ permalink raw reply related

* [PATCH v12 09/11] iio: frequency: adf41513: features on frequency change
From: Rodrigo Alencar via B4 Relay @ 2026-05-10 12:42 UTC (permalink / raw)
  To: linux-kernel, linux-iio, devicetree, linux-doc
  Cc: Jonathan Cameron, David Lechner, Andy Shevchenko,
	Lars-Peter Clausen, Michael Hennerich, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Jonathan Corbet, Andrew Morton,
	Petr Mladek, Steven Rostedt, Andy Shevchenko, Rasmus Villemoes,
	Sergey Senozhatsky, Shuah Khan, Rodrigo Alencar
In-Reply-To: <20260510-adf41513-iio-driver-v12-0-34af2ed2779f@analog.com>

From: Rodrigo Alencar <rodrigo.alencar@analog.com>

Set Bleed current when PFD frequency changes (bleed enabled when in
fractional mode). Set lock detector window size, handling bias and
precision. Add phase resync support, setting clock dividers when
PFD frequency changes.

Signed-off-by: Rodrigo Alencar <rodrigo.alencar@analog.com>
---
 drivers/iio/frequency/adf41513.c | 105 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 105 insertions(+)

diff --git a/drivers/iio/frequency/adf41513.c b/drivers/iio/frequency/adf41513.c
index 397e859170cc..2014fd1892d9 100644
--- a/drivers/iio/frequency/adf41513.c
+++ b/drivers/iio/frequency/adf41513.c
@@ -20,6 +20,7 @@
 #include <linux/property.h>
 #include <linux/regulator/consumer.h>
 #include <linux/spi/spi.h>
+#include <linux/time64.h>
 #include <linux/types.h>
 #include <linux/units.h>
 
@@ -144,6 +145,10 @@
 #define ADF41513_PRESCALER_8_9			1
 #define ADF41513_PRESCALER_AUTO			2
 
+/* CLK Divider mode */
+#define ADF41513_CLK_DIV_MODE_OFF		0
+#define ADF41513_CLK_DIV_MODE_PHASE_RESYNC	2
+
 /* Specifications */
 #define ADF41510_MAX_RF_FREQ_HZ			(10ULL * HZ_PER_GHZ)
 #define ADF41513_MIN_RF_FREQ_HZ			(1ULL * HZ_PER_GHZ)
@@ -209,6 +214,7 @@ struct adf41513_chip_info {
 struct adf41513_data {
 	u64 power_up_frequency_hz;
 	u64 freq_resolution_uhz;
+	u32 phase_resync_period_ns;
 	u32 charge_pump_voltage_mv;
 	u32 lock_detect_count;
 
@@ -268,6 +274,16 @@ struct adf41513_state {
 	bool powerdown;
 };
 
+static const u16 adf41513_ld_window_x10_ns[] = {
+	9, 12, 16, 17, 21, 28, 29, 35,			/* 0 - 7 */
+	43, 47, 49, 52, 70, 79, 115,			/* 8 - 14 */
+};
+
+static const u8 adf41513_ldp_bias[] = {
+	0xC, 0xD, 0xE, 0x8, 0x9, 0x4, 0xA, 0x5,		/* 0 - 7 */
+	0x0, 0x6, 0xB, 0x1, 0x2, 0x7, 0x3,		/* 8 - 14 */
+};
+
 static const char * const adf41513_power_supplies[] = {
 	"avdd1", "avdd2", "avdd3", "avdd4", "avdd5", "vp",
 };
@@ -578,9 +594,83 @@ static int adf41513_calc_pll_settings(struct adf41513_state *st,
 	return 0;
 }
 
+static void adf41513_set_bleed_val(struct adf41513_state *st)
+{
+	u32 bleed_value, cp_index;
+
+	if (st->data.phase_detector_polarity)
+		bleed_value = 90;
+	else
+		bleed_value = 144;
+
+	cp_index = 1 + FIELD_GET(ADF41513_REG5_CP_CURRENT_MSK,
+				 st->regs[ADF41513_REG5]);
+	bleed_value = div64_u64(st->settings.pfd_frequency_uhz * cp_index * bleed_value,
+				1600ULL * MEGA * MICROHZ_PER_HZ);
+
+	FIELD_MODIFY(ADF41513_REG6_BLEED_CURRENT_MSK, &st->regs[ADF41513_REG6],
+		     bleed_value);
+}
+
+static void adf41513_set_ld_window(struct adf41513_state *st)
+{
+	/*
+	 * The ideal lock detector window size is halfway between the max
+	 * window, set by the phase comparison period t_PFD = (1 / f_PFD),
+	 * and the minimum is set by (I_BLEED/I_CP) × t_PFD
+	 */
+	u16 ld_window_10x_ns = div64_u64(10ULL * NSEC_PER_SEC * MICROHZ_PER_HZ,
+					 st->settings.pfd_frequency_uhz << 1);
+	u8 ld_idx, ldp, ld_bias;
+
+	if (st->settings.mode != ADF41513_MODE_INTEGER_N) {
+		/* account for bleed current (deduced from eq.6 and eq.7) */
+		if (st->data.phase_detector_polarity)
+			ld_window_10x_ns += 4;
+		else
+			ld_window_10x_ns += 6;
+	}
+
+	ld_idx = find_closest(ld_window_10x_ns, adf41513_ld_window_x10_ns,
+			      ARRAY_SIZE(adf41513_ld_window_x10_ns));
+	ldp = (adf41513_ldp_bias[ld_idx] >> 2) & 0x3;
+	ld_bias = adf41513_ldp_bias[ld_idx] & 0x3;
+
+	FIELD_MODIFY(ADF41513_REG6_LDP_MSK, &st->regs[ADF41513_REG6], ldp);
+	FIELD_MODIFY(ADF41513_REG9_LD_BIAS_MSK, &st->regs[ADF41513_REG9], ld_bias);
+}
+
+static void adf41513_set_phase_resync(struct adf41513_state *st)
+{
+	u32 total_div, clk1_div, clk2_div;
+
+	if (!st->data.phase_resync_period_ns)
+		return;
+
+	/* assuming both clock dividers hold similar values */
+	total_div = mul_u64_u64_div_u64(st->settings.pfd_frequency_uhz,
+					st->data.phase_resync_period_ns,
+					1ULL * MICROHZ_PER_HZ * NSEC_PER_SEC);
+	clk1_div = clamp(int_sqrt(total_div), 1,
+			 ADF41513_MAX_CLK_DIVIDER);
+	clk2_div = clamp(DIV_ROUND_CLOSEST(total_div, clk1_div), 1,
+			 ADF41513_MAX_CLK_DIVIDER);
+
+	FIELD_MODIFY(ADF41513_REG5_CLK1_DIV_MSK, &st->regs[ADF41513_REG5],
+		     clk1_div);
+	FIELD_MODIFY(ADF41513_REG7_CLK2_DIV_MSK, &st->regs[ADF41513_REG7],
+		     clk2_div);
+
+	/* enable phase resync */
+	FIELD_MODIFY(ADF41513_REG7_CLK_DIV_MODE_MSK, &st->regs[ADF41513_REG7],
+		     ADF41513_CLK_DIV_MODE_PHASE_RESYNC);
+}
+
 static int adf41513_set_frequency(struct adf41513_state *st, u64 freq_uhz, u16 sync_mask)
 {
 	struct adf41513_pll_settings result;
+	bool pfd_change = false;
+	bool mode_change = false;
 	int ret;
 
 	ret = adf41513_calc_pll_settings(st, &result, freq_uhz);
@@ -588,6 +678,8 @@ static int adf41513_set_frequency(struct adf41513_state *st, u64 freq_uhz, u16 s
 		return ret;
 
 	/* apply computed results to pll settings */
+	pfd_change = st->settings.pfd_frequency_uhz != result.pfd_frequency_uhz;
+	mode_change = st->settings.mode != result.mode;
 	st->settings = result;
 
 	dev_dbg(&st->spi->dev,
@@ -629,6 +721,14 @@ static int adf41513_set_frequency(struct adf41513_state *st, u64 freq_uhz, u16 s
 		st->regs[ADF41513_REG6] |= ADF41513_REG6_BLEED_ENABLE_MSK;
 	}
 
+	if (pfd_change) {
+		adf41513_set_bleed_val(st);
+		adf41513_set_phase_resync(st);
+	}
+
+	if (pfd_change || mode_change)
+		adf41513_set_ld_window(st);
+
 	return adf41513_sync_config(st, sync_mask | ADF41513_SYNC_REG0);
 }
 
@@ -908,6 +1008,11 @@ static int adf41513_parse_fw(struct adf41513_state *st)
 	st->data.phase_detector_polarity =
 		device_property_read_bool(dev, "adi,phase-detector-polarity-positive-enable");
 
+	st->data.phase_resync_period_ns = 0;
+	ret = device_property_read_u32(dev, "adi,phase-resync-period-ns", &tmp);
+	if (!ret)
+		st->data.phase_resync_period_ns = tmp;
+
 	st->data.logic_lvl_1v8_en = device_property_read_bool(dev, "adi,logic-level-1v8-enable");
 
 	tmp = ADF41513_LD_COUNT_MIN;

-- 
2.43.0



^ permalink raw reply related

* [PATCH v12 10/11] docs: iio: add documentation for adf41513 driver
From: Rodrigo Alencar via B4 Relay @ 2026-05-10 12:42 UTC (permalink / raw)
  To: linux-kernel, linux-iio, devicetree, linux-doc
  Cc: Jonathan Cameron, David Lechner, Andy Shevchenko,
	Lars-Peter Clausen, Michael Hennerich, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Jonathan Corbet, Andrew Morton,
	Petr Mladek, Steven Rostedt, Andy Shevchenko, Rasmus Villemoes,
	Sergey Senozhatsky, Shuah Khan, Rodrigo Alencar
In-Reply-To: <20260510-adf41513-iio-driver-v12-0-34af2ed2779f@analog.com>

From: Rodrigo Alencar <rodrigo.alencar@analog.com>

Add documentation for ADF41513 driver, which describes the device
driver files and shows how userspace may consume the ABI for various
tasks.

Signed-off-by: Rodrigo Alencar <rodrigo.alencar@analog.com>
---
 Documentation/iio/adf41513.rst | 199 +++++++++++++++++++++++++++++++++++++++++
 Documentation/iio/index.rst    |   1 +
 MAINTAINERS                    |   1 +
 3 files changed, 201 insertions(+)

diff --git a/Documentation/iio/adf41513.rst b/Documentation/iio/adf41513.rst
new file mode 100644
index 000000000000..244453cce6f6
--- /dev/null
+++ b/Documentation/iio/adf41513.rst
@@ -0,0 +1,199 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===============
+ADF41513 driver
+===============
+
+This driver supports Analog Devices' ADF41513 and similar SPI PLL frequency
+synthesizers.
+
+1. Supported devices
+====================
+
+* `ADF41510 <https://www.analog.com/ADF41510>`_
+* `ADF41513 <https://www.analog.com/ADF41513>`_
+
+The ADF41513 is an ultralow noise frequency synthesizer that can be used to
+implement local oscillators (LOs) as high as 26.5 GHz in the upconversion and
+downconversion sections of wireless receivers and transmitters. The ADF41510
+is a similar device that supports frequencies up to 10 GHz.
+
+Both devices support integer-N and fractional-N operation modes, providing
+excellent phase noise performance and flexible frequency generation
+capabilities.
+
+Key Features:
+
+- **ADF41510**: 1 GHz to 10 GHz frequency range
+- **ADF41513**: 1 GHz to 26.5 GHz frequency range
+- Integer-N and fractional-N operation modes
+- Ultra-low phase noise (-235 dBc/Hz integer-N, -231 dBc/Hz fractional-N)
+- High maximum PFD frequency (250 MHz integer-N, 125 MHz fractional-N)
+- 25-bit fixed modulus or 49-bit variable modulus fractional modes
+- Programmable charge pump currents with 16x range
+- Digital lock detect functionality
+- Phase resync capability for consistent output phase
+
+2. Device attributes
+====================
+
+The ADF41513 driver provides the following IIO extended attributes for
+frequency control and monitoring:
+
+Each IIO device has a device folder under ``/sys/bus/iio/devices/iio:deviceX``,
+where X is the IIO index of the device. Under these folders reside a set of
+device files that provide access to the synthesizer's functionality.
+
+The following table shows the ADF41513 related device files:
+
++--------------------------------------+-------------------------------------------------------+
+| Device file                          | Description                                           |
++======================================+=======================================================+
+| out_altvoltage0_frequency            | RF output frequency control and readback (Hz)         |
++--------------------------------------+-------------------------------------------------------+
+| out_altvoltage0_frequency_resolution | Target frequency resolution control (Hz)              |
++--------------------------------------+-------------------------------------------------------+
+| out_altvoltage0_powerdown            | Power management control (0=active, 1=power down)     |
++--------------------------------------+-------------------------------------------------------+
+| out_altvoltage0_phase                | RF output phase adjustment and readback (radians)     |
++--------------------------------------+-------------------------------------------------------+
+
+2.1 Frequency Control
+----------------------
+
+The ``out_altvoltage0_frequency`` attribute controls the RF output frequency
+with sub-Hz precision. The driver automatically selects between integer-N and
+fractional-N modes to achieve the requested frequency with the best possible
+phase noise performance.
+
+**Supported ranges:**
+
+- **ADF41510**: 1,000,000,000 Hz to 10,000,000,000 Hz (1 GHz to 10 GHz)
+- **ADF41513**: 1,000,000,000 Hz to 26,500,000,000 Hz (1 GHz to 26.5 GHz)
+
+The frequency is specified in Hz, for sub-Hz precision use decimal notation.
+For example, 12.102 GHz would be written as "12102000000.000000".
+
+2.2 Frequency Resolution Control
+--------------------------------
+
+The ``out_altvoltage0_frequency_resolution`` attribute controls the target
+frequency resolution that the driver attempts to achieve. This affects the
+choice between integer-N and fractional-N modes, including fixed modulus
+(25-bit) and variable modulus (49-bit) fractional-N modes:
+
+- **Integer-N**: Resolution = :math:`f_{PFD}` (same as PFD frequency)
+- **Fixed modulus**: Resolution = :math:`f_{PFD} / 2^{25}` (~3 Hz with 100 MHz PFD)
+- **Variable modulus**: Resolution = :math:`f_{PFD} / 2^{49}` (µHz resolution possible)
+
+Default resolution is 1 Hz (1,000,000 µHz).
+
+2.3 Phase adjustment
+--------------------
+
+The ``out_altvoltage0_phase`` attribute allows adjustment of the output phase
+in radians. Setting this attribute enables phase adjustment. It can be set
+from 0 to :math:`2\pi` radians. Reading this attribute returns the current
+phase offset of the output signal. To create a consistent phase relationship
+with the reference signal, the phase resync feature needs to be enabled by
+setting a non-zero value to the ``adi,phase-resync-period-ns`` device property,
+which triggers a phase resynchronization after locking is achieved.
+
+3. Operating modes
+==================
+
+3.1 Integer-N Mode
+------------------
+
+When the requested frequency can be achieved as an integer multiple of the PFD
+frequency (within the specified resolution tolerance), the driver automatically
+selects integer-N mode for optimal phase noise performance.
+
+In integer-N mode:
+
+- Phase noise: -235 dBc/Hz normalized floor
+- Frequency resolution: :math:`f_{PFD}` (same as PFD frequency)
+- Maximum PFD frequency: 250 MHz
+- Bleed current: Disabled
+
+3.2 Fractional-N Mode
+---------------------
+
+When sub-integer frequency steps are required, the driver automatically selects
+fractional-N mode using either fixed or variable modulus.
+
+**Fixed Modulus (25-bit)**:
+
+- Used when variable modulus is not required
+- Resolution: :math:`f_{PFD} / 2^{25}`
+- Simpler implementation, faster settling
+
+**Variable Modulus (49-bit)**:
+
+- Used for maximum resolution requirements
+- Resolution: :math:`f_{PFD} / 2^{49}` (theoretical)
+- Exact frequency synthesis capability
+
+In fractional-N mode:
+
+- Phase noise: -231 dBc/Hz normalized floor
+- Maximum PFD frequency: 125 MHz
+- Bleed current: Automatically enabled and optimized
+- Dithering: Enabled to reduce fractional spurs
+
+3.3 Automatic Mode Selection
+----------------------------
+
+The driver automatically selects the optimal operating mode based on:
+
+1. **Frequency accuracy requirements**: Determined by ``frequency_resolution`` setting
+2. **Phase noise optimization**: Integer-N preferred when possible
+3. **PFD frequency constraints**: Different limits for integer vs fractional modes
+4. **Prescaler selection**: Automatic 4/5 vs 8/9 prescaler selection based on frequency
+
+4. Usage examples
+=================
+
+4.1 Basic Frequency Setting
+----------------------------
+
+Set output frequency to 12.102 GHz:
+
+.. code-block:: bash
+
+    root:/sys/bus/iio/devices/iio:device0> echo 12102000000 > out_altvoltage0_frequency
+
+Read current frequency:
+
+.. code-block:: bash
+
+    root:/sys/bus/iio/devices/iio:device0> cat out_altvoltage0_frequency
+    12101999999.582767
+
+4.2 High Resolution Frequency Control
+-------------------------------------
+
+Configure for sub-Hz resolution and set a precise frequency:
+
+.. code-block:: bash
+
+    # Set resolution to 0.1 Hz (100,000 µHz)
+    root:/sys/bus/iio/devices/iio:device0> echo 0.1 > out_altvoltage0_frequency_resolution
+
+    # Set frequency to 12.102 GHz (1 µHz precision)
+    root:/sys/bus/iio/devices/iio:device0> echo 12102000000 > out_altvoltage0_frequency
+    root:/sys/bus/iio/devices/iio:device0> cat out_altvoltage0_frequency
+    12101999999.980131
+
+4.3 Monitor Lock Status
+-----------------------
+
+When lock detect GPIO is configured, check if PLL is locked:
+
+.. code-block:: bash
+
+    # Read frequency - will return error if not locked
+    root:/sys/bus/iio/devices/iio:device0> cat out_altvoltage0_frequency
+
+If the PLL is not locked, the frequency read will return ``-EBUSY`` (Device or
+resource busy).
diff --git a/Documentation/iio/index.rst b/Documentation/iio/index.rst
index 007e0a1fcc5a..b02b879b053a 100644
--- a/Documentation/iio/index.rst
+++ b/Documentation/iio/index.rst
@@ -31,6 +31,7 @@ Industrial I/O Kernel Drivers
    ad7625
    ad7944
    ade9000
+   adf41513
    adis16475
    adis16480
    adis16550
diff --git a/MAINTAINERS b/MAINTAINERS
index b5bf5f7de9c9..4c326244d496 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -1668,6 +1668,7 @@ L:	linux-iio@vger.kernel.org
 S:	Supported
 W:	https://ez.analog.com/linux-software-drivers
 F:	Documentation/devicetree/bindings/iio/frequency/adi,adf41513.yaml
+F:	Documentation/iio/adf41513.rst
 F:	drivers/iio/frequency/adf41513.c
 
 ANALOG DEVICES INC ADF4377 DRIVER

-- 
2.43.0



^ permalink raw reply related

* [PATCH v12 08/11] iio: frequency: adf41513: handle LE synchronization feature
From: Rodrigo Alencar via B4 Relay @ 2026-05-10 12:42 UTC (permalink / raw)
  To: linux-kernel, linux-iio, devicetree, linux-doc
  Cc: Jonathan Cameron, David Lechner, Andy Shevchenko,
	Lars-Peter Clausen, Michael Hennerich, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Jonathan Corbet, Andrew Morton,
	Petr Mladek, Steven Rostedt, Andy Shevchenko, Rasmus Villemoes,
	Sergey Senozhatsky, Shuah Khan, Rodrigo Alencar
In-Reply-To: <20260510-adf41513-iio-driver-v12-0-34af2ed2779f@analog.com>

From: Rodrigo Alencar <rodrigo.alencar@analog.com>

When LE sync is enabled, it must be set after powering up and it must be
disabled when powering down. It is recommended when using the PLL as
a frequency synthesizer, where reference signal will always be present
while the device is being configured.

Signed-off-by: Rodrigo Alencar <rodrigo.alencar@analog.com>
---
 drivers/iio/frequency/adf41513.c | 32 ++++++++++++++++++++++++++++++--
 1 file changed, 30 insertions(+), 2 deletions(-)

diff --git a/drivers/iio/frequency/adf41513.c b/drivers/iio/frequency/adf41513.c
index b8a8b9fb81d9..397e859170cc 100644
--- a/drivers/iio/frequency/adf41513.c
+++ b/drivers/iio/frequency/adf41513.c
@@ -218,6 +218,7 @@ struct adf41513_data {
 	bool phase_detector_polarity;
 
 	bool logic_lvl_1v8_en;
+	bool le_sync_en;
 };
 
 struct adf41513_pll_settings {
@@ -634,13 +635,27 @@ static int adf41513_set_frequency(struct adf41513_state *st, u64 freq_uhz, u16 s
 static int adf41513_suspend(struct adf41513_state *st)
 {
 	st->regs[ADF41513_REG6] |= FIELD_PREP(ADF41513_REG6_POWER_DOWN_MSK, 1);
+	st->regs[ADF41513_REG12] &= ~ADF41513_REG12_LE_SELECT_MSK;
 	return adf41513_sync_config(st, ADF41513_SYNC_DIFF);
 }
 
 static int adf41513_resume(struct adf41513_state *st)
 {
+	int ret;
+
 	st->regs[ADF41513_REG6] &= ~ADF41513_REG6_POWER_DOWN_MSK;
-	return adf41513_sync_config(st, ADF41513_SYNC_ALL);
+	ret = adf41513_sync_config(st, ADF41513_SYNC_ALL);
+	if (ret)
+		return ret;
+
+	if (st->data.le_sync_en) {
+		st->regs[ADF41513_REG12] |= ADF41513_REG12_LE_SELECT_MSK;
+		ret = adf41513_sync_config(st, ADF41513_SYNC_DIFF);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
 }
 
 static ssize_t adf41513_read_resolution(struct iio_dev *indio_dev,
@@ -903,6 +918,8 @@ static int adf41513_parse_fw(struct adf41513_state *st)
 				     "invalid lock detect count: %u\n", tmp);
 	st->data.lock_detect_count = tmp;
 
+	/* load enable sync */
+	st->data.le_sync_en = device_property_read_bool(dev, "adi,le-sync-enable");
 	st->data.freq_resolution_uhz = MICROHZ_PER_HZ;
 
 	return 0;
@@ -959,7 +976,18 @@ static int adf41513_setup(struct device *dev, struct adf41513_state *st)
 	if (ret)
 		return ret;
 
-	return devm_add_action_or_reset(dev, adf41513_close, st);
+	ret = devm_add_action_or_reset(dev, adf41513_close, st);
+	if (ret)
+		return ret;
+
+	if (st->data.le_sync_en) {
+		st->regs[ADF41513_REG12] |= ADF41513_REG12_LE_SELECT_MSK;
+		ret = adf41513_sync_config(st, ADF41513_SYNC_DIFF);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
 }
 
 static int adf41513_pm_suspend(struct device *dev)

-- 
2.43.0



^ permalink raw reply related

* [PATCH v12 07/11] iio: frequency: adf41513: driver implementation
From: Rodrigo Alencar via B4 Relay @ 2026-05-10 12:42 UTC (permalink / raw)
  To: linux-kernel, linux-iio, devicetree, linux-doc
  Cc: Jonathan Cameron, David Lechner, Andy Shevchenko,
	Lars-Peter Clausen, Michael Hennerich, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Jonathan Corbet, Andrew Morton,
	Petr Mladek, Steven Rostedt, Andy Shevchenko, Rasmus Villemoes,
	Sergey Senozhatsky, Shuah Khan, Rodrigo Alencar
In-Reply-To: <20260510-adf41513-iio-driver-v12-0-34af2ed2779f@analog.com>

From: Rodrigo Alencar <rodrigo.alencar@analog.com>

The driver is based on existing PLL drivers in the IIO subsystem and
implements the following key features:

- Integer-N and fractional-N (fixed/variable modulus) synthesis modes;
- High-resolution frequency calculations using microhertz (µHz) precision
  to handle sub-Hz resolution across multi-GHz frequency ranges;
- IIO debugfs interface for direct register access;
- FW property parsing from devicetree including charge pump settings and
  reference path configuration;
- Power management support with suspend/resume callbacks;
- Lock detect GPIO monitoring.

Signed-off-by: Rodrigo Alencar <rodrigo.alencar@analog.com>
---
 MAINTAINERS                      |    1 +
 drivers/iio/frequency/Kconfig    |   10 +
 drivers/iio/frequency/Makefile   |    1 +
 drivers/iio/frequency/adf41513.c | 1098 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 1110 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index 69646ebe5762..b5bf5f7de9c9 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -1668,6 +1668,7 @@ L:	linux-iio@vger.kernel.org
 S:	Supported
 W:	https://ez.analog.com/linux-software-drivers
 F:	Documentation/devicetree/bindings/iio/frequency/adi,adf41513.yaml
+F:	drivers/iio/frequency/adf41513.c
 
 ANALOG DEVICES INC ADF4377 DRIVER
 M:	Antoniu Miclaus <antoniu.miclaus@analog.com>
diff --git a/drivers/iio/frequency/Kconfig b/drivers/iio/frequency/Kconfig
index 583cbdf4e8cd..90c6304c4bcd 100644
--- a/drivers/iio/frequency/Kconfig
+++ b/drivers/iio/frequency/Kconfig
@@ -29,6 +29,16 @@ endmenu
 
 menu "Phase-Locked Loop (PLL) frequency synthesizers"
 
+config ADF41513
+	tristate "Analog Devices ADF41513 PLL Frequency Synthesizer"
+	depends on SPI
+	help
+	  Say yes here to build support for Analog Devices ADF41513
+	  26.5 GHz Integer-N/Fractional-N PLL Frequency Synthesizer.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called adf41513.
+
 config ADF4350
 	tristate "Analog Devices ADF4350/ADF4351 Wideband Synthesizers"
 	depends on SPI
diff --git a/drivers/iio/frequency/Makefile b/drivers/iio/frequency/Makefile
index 70d0e0b70e80..53b4d01414d8 100644
--- a/drivers/iio/frequency/Makefile
+++ b/drivers/iio/frequency/Makefile
@@ -5,6 +5,7 @@
 
 # When adding new entries keep the list in alphabetical order
 obj-$(CONFIG_AD9523) += ad9523.o
+obj-$(CONFIG_ADF41513) += adf41513.o
 obj-$(CONFIG_ADF4350) += adf4350.o
 obj-$(CONFIG_ADF4371) += adf4371.o
 obj-$(CONFIG_ADF4377) += adf4377.o
diff --git a/drivers/iio/frequency/adf41513.c b/drivers/iio/frequency/adf41513.c
new file mode 100644
index 000000000000..b8a8b9fb81d9
--- /dev/null
+++ b/drivers/iio/frequency/adf41513.c
@@ -0,0 +1,1098 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * ADF41513 SPI PLL Frequency Synthesizer driver
+ *
+ * Copyright 2026 Analog Devices Inc.
+ */
+
+#include <linux/bitfield.h>
+#include <linux/bits.h>
+#include <linux/clk.h>
+#include <linux/device.h>
+#include <linux/err.h>
+#include <linux/gpio/consumer.h>
+#include <linux/iio/iio.h>
+#include <linux/iio/sysfs.h>
+#include <linux/log2.h>
+#include <linux/math64.h>
+#include <linux/mod_devicetable.h>
+#include <linux/module.h>
+#include <linux/property.h>
+#include <linux/regulator/consumer.h>
+#include <linux/spi/spi.h>
+#include <linux/types.h>
+#include <linux/units.h>
+
+/* Registers */
+#define ADF41513_REG0		0
+#define ADF41513_REG1		1
+#define ADF41513_REG2		2
+#define ADF41513_REG3		3
+#define ADF41513_REG4		4
+#define ADF41513_REG5		5
+#define ADF41513_REG6		6
+#define ADF41513_REG7		7
+#define ADF41513_REG8		8
+#define ADF41513_REG9		9
+#define ADF41513_REG10		10
+#define ADF41513_REG11		11
+#define ADF41513_REG12		12
+#define ADF41513_REG13		13
+#define ADF41513_REG_NUM	14
+
+#define ADF41513_SYNC_REG0	BIT(ADF41513_REG0)
+#define ADF41513_SYNC_REG1	BIT(ADF41513_REG1)
+#define ADF41513_SYNC_REG2	BIT(ADF41513_REG2)
+#define ADF41513_SYNC_REG3	BIT(ADF41513_REG3)
+#define ADF41513_SYNC_REG4	BIT(ADF41513_REG4)
+#define ADF41513_SYNC_REG5	BIT(ADF41513_REG5)
+#define ADF41513_SYNC_REG6	BIT(ADF41513_REG6)
+#define ADF41513_SYNC_REG7	BIT(ADF41513_REG7)
+#define ADF41513_SYNC_REG9	BIT(ADF41513_REG9)
+#define ADF41513_SYNC_REG11	BIT(ADF41513_REG11)
+#define ADF41513_SYNC_REG12	BIT(ADF41513_REG12)
+#define ADF41513_SYNC_REG13	BIT(ADF41513_REG13)
+#define ADF41513_SYNC_DIFF	0
+#define ADF41513_SYNC_ALL	GENMASK(ADF41513_REG13, ADF41513_REG0)
+
+/* REG0 Bit Definitions */
+#define ADF41513_REG0_CTRL_BITS_MSK		GENMASK(3, 0)
+#define ADF41513_REG0_INT_MSK			GENMASK(19, 4)
+#define ADF41513_REG0_VAR_MOD_MSK		BIT(28)
+
+/* REG1 Bit Definitions */
+#define ADF41513_REG1_FRAC1_MSK			GENMASK(28, 4)
+#define ADF41513_REG1_DITHER2_MSK		BIT(31)
+
+/* REG2 Bit Definitions */
+#define ADF41513_REG2_PHASE_VAL_MSK		GENMASK(15, 4)
+#define ADF41513_REG2_PHASE_ADJ_MSK		BIT(31)
+
+/* REG3 Bit Definitions */
+#define ADF41513_REG3_FRAC2_MSK			GENMASK(27, 4)
+
+/* REG4 Bit Definitions */
+#define ADF41513_REG4_MOD2_MSK			GENMASK(27, 4)
+
+/* REG5 Bit Definitions */
+#define ADF41513_REG5_CLK1_DIV_MSK		GENMASK(15, 4)
+#define ADF41513_REG5_R_CNT_MSK			GENMASK(20, 16)
+#define ADF41513_REG5_REF_DOUBLER_MSK		BIT(21)
+#define ADF41513_REG5_RDIV2_MSK			BIT(22)
+#define ADF41513_REG5_PRESCALER_MSK		BIT(23)
+#define ADF41513_REG5_LSB_P1_MSK		BIT(24)
+#define ADF41513_REG5_CP_CURRENT_MSK		GENMASK(28, 25)
+#define ADF41513_REG5_DLD_MODES_MSK		GENMASK(31, 30)
+
+/* REG6 Bit Definitions */
+#define ADF41513_REG6_COUNTER_RESET_MSK		BIT(4)
+#define ADF41513_REG6_CP_TRISTATE_MSK		BIT(5)
+#define ADF41513_REG6_POWER_DOWN_MSK		BIT(6)
+#define ADF41513_REG6_PD_POLARITY_MSK		BIT(7)
+#define ADF41513_REG6_LDP_MSK			GENMASK(9, 8)
+#define ADF41513_REG6_CP_TRISTATE_PD_ON_MSK	BIT(16)
+#define ADF41513_REG6_SD_RESET_MSK		BIT(17)
+#define ADF41513_REG6_LOL_ENABLE_MSK		BIT(18)
+#define ADF41513_REG6_ABP_MSK			BIT(19)
+#define ADF41513_REG6_INT_MODE_MSK		BIT(20)
+#define ADF41513_REG6_BLEED_ENABLE_MSK		BIT(22)
+#define ADF41513_REG6_BLEED_POLARITY_MSK	BIT(23)
+#define ADF41513_REG6_BLEED_CURRENT_MSK		GENMASK(31, 24)
+
+/* REG7 Bit Definitions */
+#define ADF41513_REG7_CLK2_DIV_MSK		GENMASK(17, 6)
+#define ADF41513_REG7_CLK_DIV_MODE_MSK		GENMASK(19, 18)
+#define ADF41513_REG7_PS_BIAS_MSK		GENMASK(21, 20)
+#define ADF41513_REG7_N_DELAY_MSK		GENMASK(23, 22)
+#define ADF41513_REG7_LD_CLK_SEL_MSK		BIT(26)
+#define ADF41513_REG7_LD_COUNT_MSK		GENMASK(29, 27)
+
+/* REG9 Bit Definitions */
+#define ADF41513_REG9_LD_BIAS_MSK		GENMASK(31, 30)
+
+/* REG11 Bit Definitions */
+#define ADF41513_REG11_POWER_DOWN_SEL_MSK	BIT(31)
+
+/* REG12 Bit Definitions */
+#define ADF41513_REG12_READBACK_SEL_MSK		GENMASK(19, 14)
+#define ADF41513_REG12_LE_SELECT_MSK		BIT(20)
+#define ADF41513_REG12_MASTER_RESET_MSK		BIT(22)
+#define ADF41513_REG12_LOGIC_LEVEL_MSK		BIT(27)
+#define ADF41513_REG12_MUXOUT_MSK		GENMASK(31, 28)
+
+/* MUXOUT Selection */
+#define ADF41513_MUXOUT_TRISTATE		0x0
+#define ADF41513_MUXOUT_DVDD			0x1
+#define ADF41513_MUXOUT_DGND			0x2
+#define ADF41513_MUXOUT_R_DIV			0x3
+#define ADF41513_MUXOUT_N_DIV			0x4
+#define ADF41513_MUXOUT_DIG_LD			0x6
+#define ADF41513_MUXOUT_SDO			0x7
+#define ADF41513_MUXOUT_READBACK		0x8
+#define ADF41513_MUXOUT_CLK1_DIV		0xA
+#define ADF41513_MUXOUT_R_DIV2			0xD
+#define ADF41513_MUXOUT_N_DIV2			0xE
+
+/* DLD Mode Selection */
+#define ADF41513_DLD_TRISTATE			0x0
+#define ADF41513_DLD_DIG_LD			0x1
+#define ADF41513_DLD_LOW			0x2
+#define ADF41513_DLD_HIGH			0x3
+
+/* Prescaler Selection */
+#define ADF41513_PRESCALER_4_5			0
+#define ADF41513_PRESCALER_8_9			1
+#define ADF41513_PRESCALER_AUTO			2
+
+/* Specifications */
+#define ADF41510_MAX_RF_FREQ_HZ			(10ULL * HZ_PER_GHZ)
+#define ADF41513_MIN_RF_FREQ_HZ			(1ULL * HZ_PER_GHZ)
+#define ADF41513_MAX_RF_FREQ_HZ			(26500ULL * HZ_PER_MHZ)
+
+#define ADF41513_MIN_REF_FREQ_HZ		(10 * HZ_PER_MHZ)
+#define ADF41513_MAX_REF_FREQ_HZ		(800 * HZ_PER_MHZ)
+#define ADF41513_MAX_REF_FREQ_DOUBLER_HZ	(225 * HZ_PER_MHZ)
+
+#define ADF41513_MAX_PFD_FREQ_INT_N_UHZ		(250ULL * MEGA * MICROHZ_PER_HZ)
+#define ADF41513_MAX_PFD_FREQ_FRAC_N_UHZ	(125ULL * MEGA * MICROHZ_PER_HZ)
+#define ADF41513_MAX_FREQ_RESOLUTION_UHZ	(100ULL * KILO * MICROHZ_PER_HZ)
+
+#define ADF41513_MIN_INT_4_5			20
+#define ADF41513_MAX_INT_4_5			511
+#define ADF41513_MIN_INT_8_9			64
+#define ADF41513_MAX_INT_8_9			1023
+
+#define ADF41513_MIN_INT_FRAC_4_5		23
+#define ADF41513_MIN_INT_FRAC_8_9		75
+
+#define ADF41513_MIN_R_CNT			1
+#define ADF41513_MAX_R_CNT			32
+
+#define ADF41513_MIN_R_SET			1800
+#define ADF41513_DEFAULT_R_SET			2700
+#define ADF41513_MAX_R_SET			10000
+
+#define ADF41513_MIN_CP_VOLTAGE_mV		810
+#define ADF41513_DEFAULT_CP_VOLTAGE_mV		6480
+#define ADF41513_MAX_CP_VOLTAGE_mV		12960
+
+#define ADF41513_MIN_CP_CURRENT_uA		81
+#define ADF41513_MAX_CP_CURRENT_uA		7200
+
+#define ADF41513_LD_COUNT_FAST_MIN		2
+#define ADF41513_LD_COUNT_FAST_LIMIT		64
+#define ADF41513_LD_COUNT_MIN			64
+#define ADF41513_LD_COUNT_MAX			8192
+
+#define ADF41513_FIXED_MODULUS			BIT(25)
+#define ADF41513_MAX_MOD2			(BIT(24) - 1)
+#define ADF41513_MAX_PHASE_VAL			(BIT(12) - 1)
+#define ADF41513_MAX_CLK_DIVIDER		(BIT(12) - 1)
+
+#define ADF41513_HZ_DECIMAL_SCALE		6
+#define ADF41513_PS_BIAS_INIT			0x2
+#define ADF41513_MAX_PHASE_MICRORAD		((2 * 314159265UL) / 100)
+
+enum adf41513_pll_mode {
+	ADF41513_MODE_INVALID,
+	ADF41513_MODE_INTEGER_N,
+	ADF41513_MODE_FIXED_MODULUS,
+	ADF41513_MODE_VARIABLE_MODULUS,
+};
+
+struct adf41513_chip_info {
+	const char *name;
+	u64 max_rf_freq_hz;
+	bool has_prescaler_8_9;
+};
+
+struct adf41513_data {
+	u64 power_up_frequency_hz;
+	u64 freq_resolution_uhz;
+	u32 charge_pump_voltage_mv;
+	u32 lock_detect_count;
+
+	u8 ref_div_factor;
+	bool ref_doubler_en;
+	bool ref_div2_en;
+	bool phase_detector_polarity;
+
+	bool logic_lvl_1v8_en;
+};
+
+struct adf41513_pll_settings {
+	enum adf41513_pll_mode mode;
+
+	/* reference path parameters */
+	u8 r_counter;
+	u8 ref_doubler;
+	u8 ref_div2;
+	u8 prescaler;
+
+	/* frequency parameters */
+	u64 target_frequency_uhz;
+	u64 actual_frequency_uhz;
+	u64 pfd_frequency_uhz;
+
+	/* pll parameters */
+	u32 frac1;
+	u32 frac2;
+	u32 mod2;
+	u16 int_val;
+};
+
+struct adf41513_state {
+	const struct adf41513_chip_info *chip_info;
+	struct spi_device *spi;
+	struct gpio_desc *lock_detect;
+	struct clk *ref_clk;
+	u32 ref_freq_hz;
+
+	/*
+	 * Lock for accessing device registers. Some operations require
+	 * multiple consecutive R/W operations, during which the device
+	 * shouldn't be interrupted. The buffers are also shared across
+	 * all operations so need to be protected on stand alone reads and
+	 * writes.
+	 */
+	struct mutex lock;
+
+	/* Cached register values */
+	u32 regs[ADF41513_REG_NUM];
+	u32 regs_hw[ADF41513_REG_NUM];
+
+	struct adf41513_data data;
+	struct adf41513_pll_settings settings;
+
+	bool powerdown;
+};
+
+static const char * const adf41513_power_supplies[] = {
+	"avdd1", "avdd2", "avdd3", "avdd4", "avdd5", "vp",
+};
+
+static int adf41513_sync_config(struct adf41513_state *st, u16 sync_mask)
+{
+	__be32 d32;
+	int ret;
+
+	/* write registers in reverse order (R13 to R0)*/
+	for (int i = ADF41513_REG13; i >= ADF41513_REG0; i--) {
+		if (st->regs_hw[i] == st->regs[i] && !(sync_mask & BIT(i)))
+			continue;
+
+		d32 = cpu_to_be32(st->regs[i] | i);
+		ret = spi_write_then_read(st->spi, &d32, sizeof(d32), NULL, 0);
+		if (ret < 0)
+			return ret;
+		st->regs_hw[i] = st->regs[i];
+		dev_dbg(&st->spi->dev, "REG%d <= 0x%08X\n", i, st->regs[i] | i);
+	}
+
+	return 0;
+}
+
+static u64 adf41513_pll_get_rate(struct adf41513_state *st)
+{
+	struct adf41513_pll_settings *cfg = &st->settings;
+
+	if (cfg->mode != ADF41513_MODE_INVALID)
+		return cfg->actual_frequency_uhz;
+
+	/* get pll settings from regs_hw */
+	cfg->int_val = FIELD_GET(ADF41513_REG0_INT_MSK, st->regs_hw[ADF41513_REG0]);
+	cfg->frac1 = FIELD_GET(ADF41513_REG1_FRAC1_MSK, st->regs_hw[ADF41513_REG1]);
+	cfg->frac2 = FIELD_GET(ADF41513_REG3_FRAC2_MSK, st->regs_hw[ADF41513_REG3]);
+	cfg->mod2 = FIELD_GET(ADF41513_REG4_MOD2_MSK, st->regs_hw[ADF41513_REG4]);
+	cfg->r_counter = FIELD_GET(ADF41513_REG5_R_CNT_MSK, st->regs_hw[ADF41513_REG5]);
+	cfg->ref_doubler = FIELD_GET(ADF41513_REG5_REF_DOUBLER_MSK, st->regs_hw[ADF41513_REG5]);
+	cfg->ref_div2 = FIELD_GET(ADF41513_REG5_RDIV2_MSK, st->regs_hw[ADF41513_REG5]);
+	cfg->prescaler = FIELD_GET(ADF41513_REG5_PRESCALER_MSK, st->regs_hw[ADF41513_REG5]);
+
+	if (!cfg->mod2)
+		cfg->mod2 = 1;
+	if (!cfg->r_counter)
+		cfg->r_counter = ADF41513_MAX_R_CNT;
+
+	/* calculate pfd frequency */
+	cfg->pfd_frequency_uhz = (u64)st->ref_freq_hz * MICRO;
+	if (cfg->ref_doubler)
+		cfg->pfd_frequency_uhz <<= 1;
+	if (cfg->ref_div2)
+		cfg->pfd_frequency_uhz >>= 1;
+	cfg->pfd_frequency_uhz = div_u64(cfg->pfd_frequency_uhz, cfg->r_counter);
+	cfg->actual_frequency_uhz = (u64)cfg->int_val * cfg->pfd_frequency_uhz;
+
+	/* check if int mode is selected */
+	if (FIELD_GET(ADF41513_REG6_INT_MODE_MSK, st->regs_hw[ADF41513_REG6])) {
+		cfg->mode = ADF41513_MODE_INTEGER_N;
+	} else {
+		cfg->actual_frequency_uhz += mul_u64_u32_div(cfg->pfd_frequency_uhz,
+							     cfg->frac1,
+							     ADF41513_FIXED_MODULUS);
+
+		/* check if variable modulus is selected */
+		if (FIELD_GET(ADF41513_REG0_VAR_MOD_MSK, st->regs_hw[ADF41513_REG0])) {
+			cfg->actual_frequency_uhz +=
+				mul_u64_u64_div_u64(cfg->frac2,
+						    cfg->pfd_frequency_uhz,
+						    (u64)cfg->mod2 * ADF41513_FIXED_MODULUS);
+
+			cfg->mode = ADF41513_MODE_VARIABLE_MODULUS;
+		} else {
+			/* LSB_P1 offset */
+			if (!FIELD_GET(ADF41513_REG5_LSB_P1_MSK, st->regs_hw[ADF41513_REG5]))
+				cfg->actual_frequency_uhz +=
+					div_u64(cfg->pfd_frequency_uhz,
+						2 * ADF41513_FIXED_MODULUS);
+			cfg->mode = ADF41513_MODE_FIXED_MODULUS;
+		}
+	}
+
+	cfg->target_frequency_uhz = cfg->actual_frequency_uhz;
+
+	return cfg->actual_frequency_uhz;
+}
+
+static int adf41513_calc_pfd_frequency(struct adf41513_state *st,
+				       struct adf41513_pll_settings *result,
+				       u64 fpfd_limit_uhz)
+{
+	result->ref_div2 = st->data.ref_div2_en;
+	result->ref_doubler = st->data.ref_doubler_en;
+
+	if (st->data.ref_doubler_en &&
+	    st->ref_freq_hz > ADF41513_MAX_REF_FREQ_DOUBLER_HZ) {
+		result->ref_doubler = 0;
+		dev_warn(&st->spi->dev, "Disabling ref doubler due to high reference frequency\n");
+	}
+
+	result->r_counter = st->data.ref_div_factor - 1;
+	do {
+		result->r_counter++;
+		/* f_PFD = REF_IN × ((1 + D)/(R × (1 + T))) */
+		result->pfd_frequency_uhz = (u64)st->ref_freq_hz * MICRO;
+		if (result->ref_doubler)
+			result->pfd_frequency_uhz <<= 1;
+		if (result->ref_div2)
+			result->pfd_frequency_uhz >>= 1;
+		result->pfd_frequency_uhz = div_u64(result->pfd_frequency_uhz,
+						    result->r_counter);
+	} while (result->pfd_frequency_uhz > fpfd_limit_uhz);
+
+	if (result->r_counter > ADF41513_MAX_R_CNT) {
+		dev_err(&st->spi->dev, "Cannot optimize PFD frequency\n");
+		return -ERANGE;
+	}
+
+	return 0;
+}
+
+static int adf41513_calc_integer_n(struct adf41513_state *st,
+				   struct adf41513_pll_settings *result)
+{
+	u32 max_int = st->chip_info->has_prescaler_8_9 ?
+		      ADF41513_MAX_INT_8_9 : ADF41513_MAX_INT_4_5;
+	u64 freq_error_uhz;
+	u32 int_val = div64_u64_rem(result->target_frequency_uhz, result->pfd_frequency_uhz,
+				    &freq_error_uhz);
+
+	/* check if freq error is within a tolerance of 1/2 resolution */
+	if (freq_error_uhz > (result->pfd_frequency_uhz >> 1) && int_val < max_int) {
+		int_val++;
+		freq_error_uhz = result->pfd_frequency_uhz - freq_error_uhz;
+	}
+
+	if (freq_error_uhz > st->data.freq_resolution_uhz)
+		return -ERANGE;
+
+	/* set prescaler */
+	if (st->chip_info->has_prescaler_8_9 && int_val >= ADF41513_MIN_INT_8_9 &&
+	    int_val <= ADF41513_MAX_INT_8_9)
+		result->prescaler = 1;
+	else if (int_val >= ADF41513_MIN_INT_4_5 && int_val <= ADF41513_MAX_INT_4_5)
+		result->prescaler = 0;
+	else
+		return -ERANGE;
+
+	result->actual_frequency_uhz = (u64)int_val * result->pfd_frequency_uhz;
+	result->mode = ADF41513_MODE_INTEGER_N;
+	result->int_val = int_val;
+	result->frac1 = 0;
+	result->frac2 = 0;
+	result->mod2 = 0;
+
+	return 0;
+}
+
+static int adf41513_calc_fixed_mod(struct adf41513_state *st,
+				   struct adf41513_pll_settings *result)
+{
+	u64 resolution_uhz = div_u64(result->pfd_frequency_uhz, ADF41513_FIXED_MODULUS);
+	u64 target_frequency_uhz = result->target_frequency_uhz;
+	u64 freq_error_uhz;
+	u32 int_val, frac1;
+	bool lsb_p1_offset = !FIELD_GET(ADF41513_REG5_LSB_P1_MSK, st->regs_hw[ADF41513_REG5]);
+
+	/* LSB_P1 adds a frequency offset of f_pfd/2^26 */
+	if (lsb_p1_offset)
+		target_frequency_uhz -= resolution_uhz >> 1;
+
+	int_val = div64_u64_rem(target_frequency_uhz, result->pfd_frequency_uhz,
+				&freq_error_uhz);
+
+	if (st->chip_info->has_prescaler_8_9 && int_val >= ADF41513_MIN_INT_FRAC_8_9 &&
+	    int_val <= ADF41513_MAX_INT_8_9)
+		result->prescaler = 1;
+	else if (int_val >= ADF41513_MIN_INT_FRAC_4_5 && int_val <= ADF41513_MAX_INT_4_5)
+		result->prescaler = 0;
+	else
+		return -ERANGE;
+
+	/* compute frac1 and fixed modulus error */
+	frac1 = mul_u64_u64_div_u64(freq_error_uhz, ADF41513_FIXED_MODULUS,
+				    result->pfd_frequency_uhz);
+	freq_error_uhz -= mul_u64_u32_div(result->pfd_frequency_uhz, frac1,
+					  ADF41513_FIXED_MODULUS);
+
+	/* check if freq error is within a tolerance of 1/2 resolution */
+	if (freq_error_uhz > (resolution_uhz >> 1) && frac1 < (ADF41513_FIXED_MODULUS - 1)) {
+		frac1++;
+		freq_error_uhz = resolution_uhz - freq_error_uhz;
+	}
+
+	if (freq_error_uhz > st->data.freq_resolution_uhz)
+		return -ERANGE;
+
+	/* integer part */
+	result->actual_frequency_uhz = (u64)int_val * result->pfd_frequency_uhz;
+	/* fractional part */
+	if (lsb_p1_offset)
+		result->actual_frequency_uhz +=	(resolution_uhz >> 1);
+	result->actual_frequency_uhz += mul_u64_u32_div(result->pfd_frequency_uhz, frac1,
+							ADF41513_FIXED_MODULUS);
+	result->mode = ADF41513_MODE_FIXED_MODULUS;
+	result->int_val = int_val;
+	result->frac1 = frac1;
+	result->frac2 = 0;
+	result->mod2 = 0;
+
+	return 0;
+}
+
+static int adf41513_calc_variable_mod(struct adf41513_state *st,
+				      struct adf41513_pll_settings *result)
+{
+	u64 freq_error_uhz, mod2;
+	u32 frac1, frac2;
+	u32 int_val = div64_u64_rem(result->target_frequency_uhz,
+				    result->pfd_frequency_uhz, &freq_error_uhz);
+
+	if (st->chip_info->has_prescaler_8_9 && int_val >= ADF41513_MIN_INT_FRAC_8_9 &&
+	    int_val <= ADF41513_MAX_INT_8_9)
+		result->prescaler = 1;
+	else if (int_val >= ADF41513_MIN_INT_FRAC_4_5 && int_val <= ADF41513_MAX_INT_4_5)
+		result->prescaler = 0;
+	else
+		return -ERANGE;
+
+	/* calculate required mod2 based on target resolution / 2 */
+	mod2 = DIV64_U64_ROUND_CLOSEST(result->pfd_frequency_uhz << 1,
+				       st->data.freq_resolution_uhz * ADF41513_FIXED_MODULUS);
+	/* ensure mod2 is at least 2 for meaningful operation */
+	mod2 = clamp(mod2, 2, ADF41513_MAX_MOD2);
+
+	/* calculate frac1 and frac2 */
+	frac1 = mul_u64_u64_div_u64(freq_error_uhz, ADF41513_FIXED_MODULUS,
+				    result->pfd_frequency_uhz);
+	freq_error_uhz -= mul_u64_u32_div(result->pfd_frequency_uhz, frac1,
+					  ADF41513_FIXED_MODULUS);
+	frac2 = mul_u64_u64_div_u64(freq_error_uhz, mod2 * ADF41513_FIXED_MODULUS,
+				    result->pfd_frequency_uhz);
+
+	/* integer part */
+	result->actual_frequency_uhz = (u64)int_val * result->pfd_frequency_uhz;
+	/* fractional part */
+	result->actual_frequency_uhz += mul_u64_u64_div_u64(mod2 * frac1 + frac2,
+							    result->pfd_frequency_uhz,
+							    mod2 * ADF41513_FIXED_MODULUS);
+	result->mode = ADF41513_MODE_VARIABLE_MODULUS;
+	result->int_val = int_val;
+	result->frac1 = frac1;
+	result->frac2 = frac2;
+	result->mod2 = mod2;
+
+	return 0;
+}
+
+static int adf41513_calc_pll_settings(struct adf41513_state *st,
+				      struct adf41513_pll_settings *result,
+				      u64 rf_out_uhz)
+{
+	u64 max_rf_freq_uhz = st->chip_info->max_rf_freq_hz * MICRO;
+	u64 min_rf_freq_uhz = ADF41513_MIN_RF_FREQ_HZ * MICRO;
+	u64 pfd_freq_limit_uhz;
+	int ret;
+
+	if (rf_out_uhz < min_rf_freq_uhz || rf_out_uhz > max_rf_freq_uhz) {
+		dev_err(&st->spi->dev, "RF frequency %llu uHz out of range [%llu, %llu] uHz\n",
+			rf_out_uhz, min_rf_freq_uhz, max_rf_freq_uhz);
+		return -EINVAL;
+	}
+
+	result->target_frequency_uhz = rf_out_uhz;
+
+	/* try integer-N first (best phase noise performance) */
+	pfd_freq_limit_uhz = min(div_u64(rf_out_uhz, ADF41513_MIN_INT_4_5),
+				 ADF41513_MAX_PFD_FREQ_INT_N_UHZ);
+	ret = adf41513_calc_pfd_frequency(st, result, pfd_freq_limit_uhz);
+	if (ret)
+		return ret;
+
+	if (adf41513_calc_integer_n(st, result) == 0)
+		return 0;
+
+	/* try fractional-N: recompute pfd frequency if necessary */
+	pfd_freq_limit_uhz = min(div_u64(rf_out_uhz, ADF41513_MIN_INT_FRAC_4_5),
+				 ADF41513_MAX_PFD_FREQ_FRAC_N_UHZ);
+	if (pfd_freq_limit_uhz < result->pfd_frequency_uhz) {
+		ret = adf41513_calc_pfd_frequency(st, result, pfd_freq_limit_uhz);
+		if (ret)
+			return ret;
+	}
+
+	/* fixed-modulus attempt */
+	if (adf41513_calc_fixed_mod(st, result) == 0)
+		return 0;
+
+	/* variable-modulus attempt */
+	ret = adf41513_calc_variable_mod(st, result);
+	if (ret) {
+		dev_err(&st->spi->dev,
+			"no valid PLL configuration found for %llu uHz\n",
+			rf_out_uhz);
+		return ret;
+	}
+
+	return 0;
+}
+
+static int adf41513_set_frequency(struct adf41513_state *st, u64 freq_uhz, u16 sync_mask)
+{
+	struct adf41513_pll_settings result;
+	int ret;
+
+	ret = adf41513_calc_pll_settings(st, &result, freq_uhz);
+	if (ret < 0)
+		return ret;
+
+	/* apply computed results to pll settings */
+	st->settings = result;
+
+	dev_dbg(&st->spi->dev,
+		"%s mode: int=%u, frac1=%u, frac2=%u, mod2=%u, fpdf=%llu Hz, prescaler=%s\n",
+		(result.mode == ADF41513_MODE_INTEGER_N) ? "integer-n" :
+		(result.mode == ADF41513_MODE_FIXED_MODULUS) ? "fixed-modulus" : "variable-modulus",
+		result.int_val, result.frac1, result.frac2, result.mod2,
+		div64_u64(result.pfd_frequency_uhz, MICRO),
+		result.prescaler ? "8/9" : "4/5");
+
+	st->regs[ADF41513_REG0] = FIELD_PREP(ADF41513_REG0_INT_MSK,
+					     st->settings.int_val);
+	if (st->settings.mode == ADF41513_MODE_VARIABLE_MODULUS)
+		st->regs[ADF41513_REG0] |= ADF41513_REG0_VAR_MOD_MSK;
+
+	st->regs[ADF41513_REG1] = FIELD_PREP(ADF41513_REG1_FRAC1_MSK,
+					     st->settings.frac1);
+	if (st->settings.mode != ADF41513_MODE_INTEGER_N)
+		st->regs[ADF41513_REG1] |= ADF41513_REG1_DITHER2_MSK;
+
+	st->regs[ADF41513_REG3] = FIELD_PREP(ADF41513_REG3_FRAC2_MSK,
+					     st->settings.frac2);
+	FIELD_MODIFY(ADF41513_REG4_MOD2_MSK, &st->regs[ADF41513_REG4],
+		     st->settings.mod2);
+	FIELD_MODIFY(ADF41513_REG5_R_CNT_MSK, &st->regs[ADF41513_REG5],
+		     st->settings.r_counter % ADF41513_MAX_R_CNT);
+	FIELD_MODIFY(ADF41513_REG5_REF_DOUBLER_MSK, &st->regs[ADF41513_REG5],
+		     st->settings.ref_doubler);
+	FIELD_MODIFY(ADF41513_REG5_RDIV2_MSK, &st->regs[ADF41513_REG5],
+		     st->settings.ref_div2);
+	FIELD_MODIFY(ADF41513_REG5_PRESCALER_MSK, &st->regs[ADF41513_REG5],
+		     st->settings.prescaler);
+
+	if (st->settings.mode == ADF41513_MODE_INTEGER_N) {
+		st->regs[ADF41513_REG6] |= ADF41513_REG6_INT_MODE_MSK;
+		st->regs[ADF41513_REG6] &= ~ADF41513_REG6_BLEED_ENABLE_MSK;
+	} else {
+		st->regs[ADF41513_REG6] &= ~ADF41513_REG6_INT_MODE_MSK;
+		st->regs[ADF41513_REG6] |= ADF41513_REG6_BLEED_ENABLE_MSK;
+	}
+
+	return adf41513_sync_config(st, sync_mask | ADF41513_SYNC_REG0);
+}
+
+static int adf41513_suspend(struct adf41513_state *st)
+{
+	st->regs[ADF41513_REG6] |= FIELD_PREP(ADF41513_REG6_POWER_DOWN_MSK, 1);
+	return adf41513_sync_config(st, ADF41513_SYNC_DIFF);
+}
+
+static int adf41513_resume(struct adf41513_state *st)
+{
+	st->regs[ADF41513_REG6] &= ~ADF41513_REG6_POWER_DOWN_MSK;
+	return adf41513_sync_config(st, ADF41513_SYNC_ALL);
+}
+
+static ssize_t adf41513_read_resolution(struct iio_dev *indio_dev,
+					uintptr_t private,
+					const struct iio_chan_spec *chan,
+					char *buf)
+{
+	struct adf41513_state *st = iio_priv(indio_dev);
+	int vals[2];
+
+	guard(mutex)(&st->lock);
+
+	iio_val_s64_array_populate(st->data.freq_resolution_uhz, vals);
+	return iio_format_value(buf, IIO_VAL_DECIMAL64_MICRO, ARRAY_SIZE(vals), vals);
+}
+
+static ssize_t adf41513_read_powerdown(struct iio_dev *indio_dev,
+				       uintptr_t private,
+				       const struct iio_chan_spec *chan,
+				       char *buf)
+{
+	struct adf41513_state *st = iio_priv(indio_dev);
+	u32 val;
+
+	guard(mutex)(&st->lock);
+
+	val = FIELD_GET(ADF41513_REG6_POWER_DOWN_MSK, st->regs_hw[ADF41513_REG6]);
+	return sysfs_emit(buf, "%u\n", val);
+}
+
+static ssize_t adf41513_write_resolution(struct iio_dev *indio_dev,
+					 uintptr_t private,
+					 const struct iio_chan_spec *chan,
+					 const char *buf, size_t len)
+{
+	struct adf41513_state *st = iio_priv(indio_dev);
+	u64 freq_uhz;
+	int ret;
+
+	ret = kstrtoudec64(buf, ADF41513_HZ_DECIMAL_SCALE, &freq_uhz);
+	if (ret)
+		return ret;
+
+	if (freq_uhz == 0 || freq_uhz > ADF41513_MAX_FREQ_RESOLUTION_UHZ)
+		return -EINVAL;
+
+	guard(mutex)(&st->lock);
+
+	st->data.freq_resolution_uhz = freq_uhz;
+	return len;
+}
+
+static ssize_t adf41513_write_powerdown(struct iio_dev *indio_dev,
+					uintptr_t private,
+					const struct iio_chan_spec *chan,
+					const char *buf, size_t len)
+{
+	struct adf41513_state *st = iio_priv(indio_dev);
+	bool val;
+	int ret;
+
+	ret = kstrtobool(buf, &val);
+	if (ret)
+		return ret;
+
+	guard(mutex)(&st->lock);
+
+	if (val)
+		ret = adf41513_suspend(st);
+	else
+		ret = adf41513_resume(st);
+	if (ret)
+		return ret;
+
+	st->powerdown = val;
+	return len;
+}
+
+static const struct iio_chan_spec_ext_info adf41513_ext_info[] = {
+	{
+		.name = "frequency_resolution",
+		.read = adf41513_read_resolution,
+		.write = adf41513_write_resolution,
+		.shared = IIO_SEPARATE,
+	},
+	{
+		.name = "powerdown",
+		.read = adf41513_read_powerdown,
+		.write = adf41513_write_powerdown,
+		.shared = IIO_SEPARATE,
+	},
+	{ }
+};
+
+static const struct iio_chan_spec adf41513_chan = {
+	.type = IIO_ALTVOLTAGE,
+	.indexed = 1,
+	.output = 1,
+	.channel = 0,
+	.info_mask_separate = BIT(IIO_CHAN_INFO_FREQUENCY) |
+			      BIT(IIO_CHAN_INFO_PHASE),
+	.ext_info = adf41513_ext_info,
+};
+
+static int adf41513_read_raw(struct iio_dev *indio_dev,
+			     struct iio_chan_spec const *chan,
+			     int *val, int *val2, long info)
+{
+	struct adf41513_state *st = iio_priv(indio_dev);
+	u64 tmp64;
+
+	guard(mutex)(&st->lock);
+
+	switch (info) {
+	case IIO_CHAN_INFO_FREQUENCY:
+		if (st->lock_detect &&
+		    !gpiod_get_value_cansleep(st->lock_detect)) {
+			dev_dbg(&st->spi->dev, "PLL un-locked\n");
+			return -EBUSY;
+		}
+		tmp64 = adf41513_pll_get_rate(st);
+		iio_val_s64_decompose(tmp64, val, val2);
+		return IIO_VAL_DECIMAL64_MICRO;
+	case IIO_CHAN_INFO_PHASE:
+		tmp64 = FIELD_GET(ADF41513_REG2_PHASE_VAL_MSK,
+				  st->regs_hw[ADF41513_REG2]);
+		tmp64 = (tmp64 * ADF41513_MAX_PHASE_MICRORAD) >> 12;
+		iio_val_s64_decompose(tmp64, val, val2);
+		return IIO_VAL_DECIMAL64_MICRO;
+	default:
+		return -EINVAL;
+	}
+}
+
+static int adf41513_write_raw(struct iio_dev *indio_dev,
+			      struct iio_chan_spec const *chan,
+			      int val, int val2, long info)
+{
+	struct adf41513_state *st = iio_priv(indio_dev);
+	u64 tmp64 = iio_val_s64_compose(val, val2);
+	u16 phase_val;
+
+	guard(mutex)(&st->lock);
+
+	switch (info) {
+	case IIO_CHAN_INFO_FREQUENCY:
+		return adf41513_set_frequency(st, tmp64, ADF41513_SYNC_DIFF);
+	case IIO_CHAN_INFO_PHASE:
+		if (tmp64 >= ADF41513_MAX_PHASE_MICRORAD)
+			return -EINVAL;
+
+		phase_val = DIV_U64_ROUND_CLOSEST(tmp64 << 12,
+						  ADF41513_MAX_PHASE_MICRORAD);
+		phase_val = min(phase_val, ADF41513_MAX_PHASE_VAL);
+		st->regs[ADF41513_REG2] |= ADF41513_REG2_PHASE_ADJ_MSK;
+		FIELD_MODIFY(ADF41513_REG2_PHASE_VAL_MSK,
+			     &st->regs[ADF41513_REG2], phase_val);
+		return adf41513_sync_config(st, ADF41513_SYNC_REG0);
+	default:
+		return -EINVAL;
+	}
+}
+
+static int adf41513_write_raw_get_fmt(struct iio_dev *indio_dev,
+				      struct iio_chan_spec const *chan,
+				      long mask)
+{
+	switch (mask) {
+	case IIO_CHAN_INFO_FREQUENCY:
+	case IIO_CHAN_INFO_PHASE:
+		return IIO_VAL_DECIMAL64_MICRO;
+	default:
+		return -EINVAL;
+	}
+}
+
+static int adf41513_reg_access(struct iio_dev *indio_dev, unsigned int reg,
+			       unsigned int writeval, unsigned int *readval)
+{
+	struct adf41513_state *st = iio_priv(indio_dev);
+
+	if (reg > ADF41513_REG13)
+		return -EINVAL;
+
+	guard(mutex)(&st->lock);
+
+	if (!readval) {
+		if (reg <= ADF41513_REG6)
+			st->settings.mode = ADF41513_MODE_INVALID;
+		st->regs[reg] = writeval & ~0xF; /* Clear control bits */
+		return adf41513_sync_config(st, BIT(reg));
+	}
+
+	*readval = st->regs_hw[reg];
+	return 0;
+}
+
+static const struct iio_info adf41513_info = {
+	.read_raw = adf41513_read_raw,
+	.write_raw = adf41513_write_raw,
+	.write_raw_get_fmt = adf41513_write_raw_get_fmt,
+	.debugfs_reg_access = &adf41513_reg_access,
+};
+
+static int adf41513_parse_fw(struct adf41513_state *st)
+{
+	struct device *dev = &st->spi->dev;
+	u32 tmp, cp_resistance, cp_current;
+	int ret;
+
+	tmp = ADF41510_MAX_RF_FREQ_HZ / MEGA;
+	device_property_read_u32(dev, "adi,power-up-frequency-mhz", &tmp);
+	st->data.power_up_frequency_hz = (u64)tmp * MEGA;
+	if (st->data.power_up_frequency_hz < ADF41513_MIN_RF_FREQ_HZ ||
+	    st->data.power_up_frequency_hz > st->chip_info->max_rf_freq_hz)
+		return dev_err_probe(dev, -ERANGE,
+				     "power-up frequency %llu Hz out of range\n",
+				     st->data.power_up_frequency_hz);
+
+	tmp = ADF41513_MIN_R_CNT;
+	device_property_read_u32(dev, "adi,reference-div-factor", &tmp);
+	if (tmp < ADF41513_MIN_R_CNT || tmp > ADF41513_MAX_R_CNT)
+		return dev_err_probe(dev, -ERANGE,
+				     "invalid reference div factor %u\n", tmp);
+	st->data.ref_div_factor = tmp;
+
+	st->data.ref_doubler_en = device_property_read_bool(dev, "adi,reference-doubler-enable");
+	st->data.ref_div2_en = device_property_read_bool(dev, "adi,reference-div2-enable");
+
+	cp_resistance = ADF41513_DEFAULT_R_SET;
+	device_property_read_u32(dev, "adi,charge-pump-resistor-ohms", &cp_resistance);
+	if (cp_resistance < ADF41513_MIN_R_SET || cp_resistance > ADF41513_MAX_R_SET)
+		return dev_err_probe(dev, -ERANGE, "R_SET %u Ohms out of range\n", cp_resistance);
+
+	st->data.charge_pump_voltage_mv = ADF41513_DEFAULT_CP_VOLTAGE_mV;
+	ret = device_property_read_u32(dev, "adi,charge-pump-current-microamp", &cp_current);
+	if (!ret) {
+		if (cp_current < ADF41513_MIN_CP_CURRENT_uA ||
+		    cp_current > ADF41513_MAX_CP_CURRENT_uA)
+			return dev_err_probe(dev, -ERANGE,
+					     "I_CP %u uA out of range\n", cp_current);
+
+		tmp = DIV_ROUND_CLOSEST(cp_current * cp_resistance, MILLI);
+		if (tmp < ADF41513_MIN_CP_VOLTAGE_mV || tmp > ADF41513_MAX_CP_VOLTAGE_mV)
+			return dev_err_probe(dev, -ERANGE, "I_CP %u uA (%u Ohms) out of range\n",
+					     cp_current, cp_resistance);
+		st->data.charge_pump_voltage_mv = tmp;
+	}
+
+	st->data.phase_detector_polarity =
+		device_property_read_bool(dev, "adi,phase-detector-polarity-positive-enable");
+
+	st->data.logic_lvl_1v8_en = device_property_read_bool(dev, "adi,logic-level-1v8-enable");
+
+	tmp = ADF41513_LD_COUNT_MIN;
+	device_property_read_u32(dev, "adi,lock-detector-count", &tmp);
+	if (tmp < ADF41513_LD_COUNT_FAST_MIN || tmp > ADF41513_LD_COUNT_MAX ||
+	    !is_power_of_2(tmp))
+		return dev_err_probe(dev, -ERANGE,
+				     "invalid lock detect count: %u\n", tmp);
+	st->data.lock_detect_count = tmp;
+
+	st->data.freq_resolution_uhz = MICROHZ_PER_HZ;
+
+	return 0;
+}
+
+static void adf41513_chip_disable(void *data)
+{
+	gpiod_set_value_cansleep(data, 0);
+}
+
+static void adf41513_close(void *data)
+{
+	adf41513_suspend(data);
+}
+
+static int adf41513_setup(struct device *dev, struct adf41513_state *st)
+{
+	u32 tmp;
+	int ret;
+
+	memset(st->regs_hw, 0xFF, sizeof(st->regs_hw));
+
+	/* assuming DLD pin is used for lock detection */
+	st->regs[ADF41513_REG5] = FIELD_PREP(ADF41513_REG5_DLD_MODES_MSK,
+					     ADF41513_DLD_DIG_LD);
+
+	tmp = DIV_ROUND_CLOSEST(st->data.charge_pump_voltage_mv, ADF41513_MIN_CP_VOLTAGE_mV);
+	st->regs[ADF41513_REG5] |= FIELD_PREP(ADF41513_REG5_CP_CURRENT_MSK, tmp - 1);
+
+	st->regs[ADF41513_REG6] = ADF41513_REG6_ABP_MSK |
+				  ADF41513_REG6_LOL_ENABLE_MSK |
+				  ADF41513_REG6_SD_RESET_MSK;
+	if (st->data.phase_detector_polarity)
+		st->regs[ADF41513_REG6] |= ADF41513_REG6_PD_POLARITY_MSK;
+
+	st->regs[ADF41513_REG7] = FIELD_PREP(ADF41513_REG7_PS_BIAS_MSK,
+					     ADF41513_PS_BIAS_INIT);
+	tmp = ilog2(st->data.lock_detect_count);
+	if (st->data.lock_detect_count < ADF41513_LD_COUNT_FAST_LIMIT) {
+		tmp -= const_ilog2(ADF41513_LD_COUNT_FAST_MIN);
+		st->regs[ADF41513_REG7] |= ADF41513_REG7_LD_CLK_SEL_MSK;
+	} else {
+		tmp -= const_ilog2(ADF41513_LD_COUNT_MIN);
+	}
+	st->regs[ADF41513_REG7] |= FIELD_PREP(ADF41513_REG7_LD_COUNT_MSK, tmp);
+
+	st->regs[ADF41513_REG11] = ADF41513_REG11_POWER_DOWN_SEL_MSK;
+	st->regs[ADF41513_REG12] = FIELD_PREP(ADF41513_REG12_LOGIC_LEVEL_MSK,
+					      st->data.logic_lvl_1v8_en ? 0 : 1);
+
+	/* perform initialization sequence with power-up frequency */
+	ret = adf41513_set_frequency(st, st->data.power_up_frequency_hz * MICRO,
+				     ADF41513_SYNC_ALL);
+	if (ret)
+		return ret;
+
+	return devm_add_action_or_reset(dev, adf41513_close, st);
+}
+
+static int adf41513_pm_suspend(struct device *dev)
+{
+	struct adf41513_state *st = dev_get_drvdata(dev);
+
+	guard(mutex)(&st->lock);
+	return adf41513_suspend(st);
+}
+
+static int adf41513_pm_resume(struct device *dev)
+{
+	struct adf41513_state *st = dev_get_drvdata(dev);
+
+	guard(mutex)(&st->lock);
+	if (st->powerdown)
+		return 0; /* nothing to do */
+
+	return adf41513_resume(st);
+}
+
+static const struct adf41513_chip_info adf41510_chip_info = {
+	.name = "adf41510",
+	.max_rf_freq_hz = ADF41510_MAX_RF_FREQ_HZ,
+	.has_prescaler_8_9 = false,
+};
+
+static const struct adf41513_chip_info adf41513_chip_info = {
+	.name = "adf41513",
+	.max_rf_freq_hz = ADF41513_MAX_RF_FREQ_HZ,
+	.has_prescaler_8_9 = true,
+};
+
+static int adf41513_probe(struct spi_device *spi)
+{
+	struct device *dev = &spi->dev;
+	struct gpio_desc *chip_enable;
+	struct iio_dev *indio_dev;
+	struct adf41513_state *st;
+	int ret;
+
+	indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
+	if (!indio_dev)
+		return -ENOMEM;
+
+	st = iio_priv(indio_dev);
+	st->spi = spi;
+	st->chip_info = spi_get_device_match_data(spi);
+	if (!st->chip_info)
+		return -EINVAL;
+
+	spi_set_drvdata(spi, st);
+
+	st->ref_clk = devm_clk_get_enabled(dev, NULL);
+	if (IS_ERR(st->ref_clk))
+		return PTR_ERR(st->ref_clk);
+
+	st->ref_freq_hz = clk_get_rate(st->ref_clk);
+	if (st->ref_freq_hz < ADF41513_MIN_REF_FREQ_HZ ||
+	    st->ref_freq_hz > ADF41513_MAX_REF_FREQ_HZ)
+		return dev_err_probe(dev, -ERANGE,
+				     "reference frequency %u Hz out of range\n",
+				     st->ref_freq_hz);
+
+	ret = adf41513_parse_fw(st);
+	if (ret)
+		return ret;
+
+	ret = devm_regulator_bulk_get_enable(dev,
+					     ARRAY_SIZE(adf41513_power_supplies),
+					     adf41513_power_supplies);
+	if (ret)
+		return dev_err_probe(dev, ret,
+				     "failed to get and enable regulators\n");
+
+	st->lock_detect = devm_gpiod_get_optional(dev, "lock-detect", GPIOD_IN);
+	if (IS_ERR(st->lock_detect))
+		return dev_err_probe(dev, PTR_ERR(st->lock_detect),
+				     "fail to request lock detect GPIO\n");
+
+	chip_enable = devm_gpiod_get_optional(dev, "enable", GPIOD_OUT_HIGH);
+	if (IS_ERR(chip_enable))
+		return dev_err_probe(dev, PTR_ERR(chip_enable),
+				     "fail to request chip enable GPIO\n");
+
+	ret = devm_add_action_or_reset(dev, adf41513_chip_disable, chip_enable);
+	if (ret)
+		return dev_err_probe(dev, ret, "Failed to add disable action\n");
+
+	ret = devm_mutex_init(dev, &st->lock);
+	if (ret)
+		return ret;
+
+	indio_dev->name = st->chip_info->name;
+	indio_dev->info = &adf41513_info;
+	indio_dev->modes = INDIO_DIRECT_MODE;
+	indio_dev->channels = &adf41513_chan;
+	indio_dev->num_channels = 1;
+
+	ret = adf41513_setup(dev, st);
+	if (ret < 0)
+		return dev_err_probe(dev, ret, "failed to setup device\n");
+
+	return devm_iio_device_register(dev, indio_dev);
+}
+
+static const struct spi_device_id adf41513_id[] = {
+	{"adf41510", (kernel_ulong_t)&adf41510_chip_info},
+	{"adf41513", (kernel_ulong_t)&adf41513_chip_info},
+	{ }
+};
+MODULE_DEVICE_TABLE(spi, adf41513_id);
+
+static const struct of_device_id adf41513_of_match[] = {
+	{ .compatible = "adi,adf41510", .data = &adf41510_chip_info },
+	{ .compatible = "adi,adf41513", .data = &adf41513_chip_info },
+	{ }
+};
+MODULE_DEVICE_TABLE(of, adf41513_of_match);
+
+static DEFINE_SIMPLE_DEV_PM_OPS(adf41513_pm_ops, adf41513_pm_suspend, adf41513_pm_resume);
+
+static struct spi_driver adf41513_driver = {
+	.driver = {
+		.name = "adf41513",
+		.pm = pm_ptr(&adf41513_pm_ops),
+		.of_match_table = adf41513_of_match,
+	},
+	.probe = adf41513_probe,
+	.id_table = adf41513_id,
+};
+module_spi_driver(adf41513_driver);
+
+MODULE_AUTHOR("Rodrigo Alencar <rodrigo.alencar@analog.com>");
+MODULE_DESCRIPTION("Analog Devices ADF41513 PLL Frequency Synthesizer");
+MODULE_LICENSE("GPL");

-- 
2.43.0



^ permalink raw reply related

* [PATCH v12 06/11] iio: test: iio-test-format: add test case for decimal format
From: Rodrigo Alencar via B4 Relay @ 2026-05-10 12:42 UTC (permalink / raw)
  To: linux-kernel, linux-iio, devicetree, linux-doc
  Cc: Jonathan Cameron, David Lechner, Andy Shevchenko,
	Lars-Peter Clausen, Michael Hennerich, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Jonathan Corbet, Andrew Morton,
	Petr Mladek, Steven Rostedt, Andy Shevchenko, Rasmus Villemoes,
	Sergey Senozhatsky, Shuah Khan, Rodrigo Alencar
In-Reply-To: <20260510-adf41513-iio-driver-v12-0-34af2ed2779f@analog.com>

From: Rodrigo Alencar <rodrigo.alencar@analog.com>

Add iio_test_iio_format_value_decimal_64() kunit test case for decimal
value formatting, exploring different scales types. Also, the same
iio_val_s64_array_populate() macro used to populate local array is used in
iio_test_iio_format_value_integer_64().

Signed-off-by: Rodrigo Alencar <rodrigo.alencar@analog.com>
---
 drivers/iio/test/iio-test-format.c | 97 +++++++++++++++++++++++++++++---------
 1 file changed, 75 insertions(+), 22 deletions(-)

diff --git a/drivers/iio/test/iio-test-format.c b/drivers/iio/test/iio-test-format.c
index 872dd8582003..a2a9b4360c92 100644
--- a/drivers/iio/test/iio-test-format.c
+++ b/drivers/iio/test/iio-test-format.c
@@ -200,56 +200,108 @@ static void iio_test_iio_format_value_multiple(struct kunit *test)
 static void iio_test_iio_format_value_integer_64(struct kunit *test)
 {
 	int values[2];
-	s64 value;
 	char *buf;
 	int ret;
 
 	buf = kunit_kmalloc(test, PAGE_SIZE, GFP_KERNEL);
 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf);
 
-	value = 24;
-	values[0] = lower_32_bits(value);
-	values[1] = upper_32_bits(value);
+	iio_val_s64_array_populate(24, values);
 	ret = iio_format_value(buf, IIO_VAL_INT_64, ARRAY_SIZE(values), values);
 	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "24\n");
 
-	value = -24;
-	values[0] = lower_32_bits(value);
-	values[1] = upper_32_bits(value);
+	iio_val_s64_array_populate(-24, values);
 	ret = iio_format_value(buf, IIO_VAL_INT_64, ARRAY_SIZE(values), values);
 	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "-24\n");
 
-	value = 0;
-	values[0] = lower_32_bits(value);
-	values[1] = upper_32_bits(value);
+	iio_val_s64_array_populate(0, values);
 	ret = iio_format_value(buf, IIO_VAL_INT_64, ARRAY_SIZE(values), values);
 	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "0\n");
 
-	value = UINT_MAX;
-	values[0] = lower_32_bits(value);
-	values[1] = upper_32_bits(value);
+	iio_val_s64_array_populate(UINT_MAX, values);
 	ret = iio_format_value(buf, IIO_VAL_INT_64, ARRAY_SIZE(values), values);
 	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "4294967295\n");
 
-	value = -((s64)UINT_MAX);
-	values[0] = lower_32_bits(value);
-	values[1] = upper_32_bits(value);
+	iio_val_s64_array_populate(-((s64)UINT_MAX), values);
 	ret = iio_format_value(buf, IIO_VAL_INT_64, ARRAY_SIZE(values), values);
 	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "-4294967295\n");
 
-	value = LLONG_MAX;
-	values[0] = lower_32_bits(value);
-	values[1] = upper_32_bits(value);
+	iio_val_s64_array_populate(LLONG_MAX, values);
 	ret = iio_format_value(buf, IIO_VAL_INT_64, ARRAY_SIZE(values), values);
 	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "9223372036854775807\n");
 
-	value = LLONG_MIN;
-	values[0] = lower_32_bits(value);
-	values[1] = upper_32_bits(value);
+	iio_val_s64_array_populate(LLONG_MIN, values);
 	ret = iio_format_value(buf, IIO_VAL_INT_64, ARRAY_SIZE(values), values);
 	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "-9223372036854775808\n");
 }
 
+static void iio_test_iio_format_value_decimal_64(struct kunit *test)
+{
+	int values[2];
+	char *buf;
+	int ret;
+
+	buf = kunit_kmalloc(test, PAGE_SIZE, GFP_KERNEL);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf);
+
+	/* DECIMAL64_MILLI: positive >= 1, value 1.234 */
+	iio_val_s64_array_populate(1234, values);
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_MILLI, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "1.234\n");
+
+	/* DECIMAL64_MICRO: positive >= 1, value 3.141592 */
+	iio_val_s64_array_populate(3141592, values);
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_MICRO, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "3.141592\n");
+
+	/* DECIMAL64_MILLI: positive < 1, value 0.042 */
+	iio_val_s64_array_populate(42, values);
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_MILLI, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "0.042\n");
+
+	/* DECIMAL64_MILLI: negative <= -1, value -1.234 */
+	iio_val_s64_array_populate(-1234, values);
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_MILLI, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "-1.234\n");
+
+	/* DECIMAL64_MILLI: negative > -1, value -0.123 */
+	iio_val_s64_array_populate(-123, values);
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_MILLI, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "-0.123\n");
+
+	/* DECIMAL64_MILLI: zero */
+	iio_val_s64_array_populate(0, values);
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_MILLI, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "0.000\n");
+
+	/* DECIMAL64_NANO: value 1.000000001 */
+	iio_val_s64_array_populate(1000000001, values);
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_NANO, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "1.000000001\n");
+
+	/* DECIMAL64_MICRO: large value using upper 32 bits */
+	iio_val_s64_array_populate(5000000000000042LL, values);
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_MICRO, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "5000000000.000042\n");
+
+	/* limits */
+	iio_val_s64_array_populate(LLONG_MAX, values);
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_PICO, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "9223372.036854775807\n");
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_NANO, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "9223372036.854775807\n");
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_MICRO, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "9223372036854.775807\n");
+
+	iio_val_s64_array_populate(LLONG_MIN, values);
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_PICO, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "-9223372.036854775808\n");
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_NANO, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "-9223372036.854775808\n");
+	ret = iio_format_value(buf, IIO_VAL_DECIMAL64_MICRO, ARRAY_SIZE(values), values);
+	IIO_TEST_FORMAT_EXPECT_EQ(test, buf, ret, "-9223372036854.775808\n");
+}
+
 static struct kunit_case iio_format_test_cases[] = {
 		KUNIT_CASE(iio_test_iio_format_value_integer),
 		KUNIT_CASE(iio_test_iio_format_value_fixedpoint),
@@ -257,6 +309,7 @@ static struct kunit_case iio_format_test_cases[] = {
 		KUNIT_CASE(iio_test_iio_format_value_fractional_log2),
 		KUNIT_CASE(iio_test_iio_format_value_multiple),
 		KUNIT_CASE(iio_test_iio_format_value_integer_64),
+		KUNIT_CASE(iio_test_iio_format_value_decimal_64),
 		{ }
 };
 

-- 
2.43.0



^ permalink raw reply related

* [PATCH v12 05/11] iio: core: add decimal value formatting into 64-bit value
From: Rodrigo Alencar via B4 Relay @ 2026-05-10 12:42 UTC (permalink / raw)
  To: linux-kernel, linux-iio, devicetree, linux-doc
  Cc: Jonathan Cameron, David Lechner, Andy Shevchenko,
	Lars-Peter Clausen, Michael Hennerich, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Jonathan Corbet, Andrew Morton,
	Petr Mladek, Steven Rostedt, Andy Shevchenko, Rasmus Villemoes,
	Sergey Senozhatsky, Shuah Khan, Rodrigo Alencar
In-Reply-To: <20260510-adf41513-iio-driver-v12-0-34af2ed2779f@analog.com>

From: Rodrigo Alencar <rodrigo.alencar@analog.com>

Create new format types for iio values (IIO_VAL_DECIMAL64_*), which
defines the representation of fixed decimal point values into a single
64-bit number. This new format increases the range of represented values,
allowing for integer parts greater than 2^32, as bits are not "wasted"
in the fractional part, which can be seen in IIO_VAL_INT_PLUS_MICRO and
IIO_VAL_INT_PLUS_NANO. Helpers are created to compose and decompose 64-bit
decimals into integer values used in IIO formatting interfaces, which
creates consistency and avoid error-prone manual assignments when using
wordpart macros. When doing the parsing, kstrtodec64() is used with the
scale defined by the specific decimal format type.

Signed-off-by: Rodrigo Alencar <rodrigo.alencar@analog.com>
---
 drivers/iio/industrialio-core.c | 46 +++++++++++++++++++++++++++++++++--------
 include/linux/iio/types.h       | 28 +++++++++++++++++++++++++
 2 files changed, 65 insertions(+), 9 deletions(-)

diff --git a/drivers/iio/industrialio-core.c b/drivers/iio/industrialio-core.c
index bd6f4f9f4533..24bc1577fdac 100644
--- a/drivers/iio/industrialio-core.c
+++ b/drivers/iio/industrialio-core.c
@@ -19,6 +19,7 @@
 #include <linux/idr.h>
 #include <linux/kdev_t.h>
 #include <linux/kernel.h>
+#include <linux/math64.h>
 #include <linux/module.h>
 #include <linux/mutex.h>
 #include <linux/poll.h>
@@ -26,7 +27,6 @@
 #include <linux/sched.h>
 #include <linux/slab.h>
 #include <linux/wait.h>
-#include <linux/wordpart.h>
 
 #include <linux/iio/buffer.h>
 #include <linux/iio/buffer_impl.h>
@@ -707,8 +707,25 @@ static ssize_t __iio_format_value(char *buf, size_t offset, unsigned int type,
 	case IIO_VAL_CHAR:
 		return sysfs_emit_at(buf, offset, "%c", (char)vals[0]);
 	case IIO_VAL_INT_64:
-		tmp2 = (s64)((((u64)vals[1]) << 32) | (u32)vals[0]);
+		tmp2 = iio_val_s64_from_array(vals);
 		return sysfs_emit_at(buf, offset, "%lld", tmp2);
+	case IIO_VAL_DECIMAL64_MILLI:
+	case IIO_VAL_DECIMAL64_MICRO:
+	case IIO_VAL_DECIMAL64_NANO:
+	case IIO_VAL_DECIMAL64_PICO:
+	{
+		s64 frac;
+		unsigned int scale = type - IIO_VAL_DECIMAL64_BASE;
+
+		tmp2 = div64_s64_rem(iio_val_s64_from_array(vals),
+				     int_pow(10, scale), &frac);
+		if (tmp2 == 0 && frac < 0)
+			return sysfs_emit_at(buf, offset, "-0.%0*lld", scale,
+					     abs(frac));
+		else
+			return sysfs_emit_at(buf, offset, "%lld.%0*lld", tmp2,
+					     scale, abs(frac));
+	}
 	default:
 		return 0;
 	}
@@ -977,7 +994,7 @@ static ssize_t iio_write_channel_info(struct device *dev,
 {
 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
-	int ret, fract_mult = 100000;
+	int type, ret, fract_mult = 100000, dec_scale = 0;
 	int integer, fract = 0;
 	long long integer64;
 	bool is_char = false;
@@ -988,9 +1005,11 @@ static ssize_t iio_write_channel_info(struct device *dev,
 	if (!indio_dev->info->write_raw)
 		return -EINVAL;
 
-	if (indio_dev->info->write_raw_get_fmt)
-		switch (indio_dev->info->write_raw_get_fmt(indio_dev,
-			this_attr->c, this_attr->address)) {
+	if (indio_dev->info->write_raw_get_fmt) {
+		type = indio_dev->info->write_raw_get_fmt(indio_dev,
+							  this_attr->c,
+							  this_attr->address);
+		switch (type) {
 		case IIO_VAL_INT:
 			fract_mult = 0;
 			break;
@@ -1006,12 +1025,19 @@ static ssize_t iio_write_channel_info(struct device *dev,
 		case IIO_VAL_CHAR:
 			is_char = true;
 			break;
+		case IIO_VAL_DECIMAL64_MILLI:
+		case IIO_VAL_DECIMAL64_MICRO:
+		case IIO_VAL_DECIMAL64_NANO:
+		case IIO_VAL_DECIMAL64_PICO:
+			dec_scale = type - IIO_VAL_DECIMAL64_BASE;
+			fallthrough;
 		case IIO_VAL_INT_64:
 			is_64bit = true;
 			break;
 		default:
 			return -EINVAL;
 		}
+	}
 
 	if (is_char) {
 		char ch;
@@ -1020,12 +1046,14 @@ static ssize_t iio_write_channel_info(struct device *dev,
 			return -EINVAL;
 		integer = ch;
 	} else if (is_64bit) {
-		ret = kstrtoll(buf, 0, &integer64);
+		if (dec_scale)
+			ret = kstrtodec64(buf, dec_scale, &integer64);
+		else
+			ret = kstrtoll(buf, 0, &integer64);
 		if (ret)
 			return ret;
 
-		fract = upper_32_bits(integer64);
-		integer = lower_32_bits(integer64);
+		iio_val_s64_decompose(integer64, &integer, &fract);
 	} else {
 		ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
 					    scale_db);
diff --git a/include/linux/iio/types.h b/include/linux/iio/types.h
index 4e3099defc1d..bc0e6f66bd9c 100644
--- a/include/linux/iio/types.h
+++ b/include/linux/iio/types.h
@@ -7,6 +7,7 @@
 #ifndef _IIO_TYPES_H_
 #define _IIO_TYPES_H_
 
+#include <linux/wordpart.h>
 #include <uapi/linux/iio/types.h>
 
 enum iio_event_info {
@@ -34,6 +35,33 @@ enum iio_event_info {
 #define IIO_VAL_FRACTIONAL_LOG2 11
 #define IIO_VAL_CHAR 12
 
+#define IIO_VAL_DECIMAL64_BASE		100
+#define IIO_VAL_DECIMAL64_MILLI		(IIO_VAL_DECIMAL64_BASE + 3)
+#define IIO_VAL_DECIMAL64_MICRO		(IIO_VAL_DECIMAL64_BASE + 6)
+#define IIO_VAL_DECIMAL64_NANO		(IIO_VAL_DECIMAL64_BASE + 9)
+#define IIO_VAL_DECIMAL64_PICO		(IIO_VAL_DECIMAL64_BASE + 12)
+
+static inline s64 iio_val_s64_compose(int val0, int val1)
+{
+	return (s64)(((u64)val1 << 32) | (u32)val0);
+}
+
+static inline s64 iio_val_s64_from_array(const int *vals)
+{
+	return iio_val_s64_compose(vals[0], vals[1]);
+}
+
+static inline void iio_val_s64_decompose(s64 dec64, int *val0, int *val1)
+{
+	*val0 = lower_32_bits(dec64);
+	*val1 = upper_32_bits(dec64);
+}
+
+static inline void iio_val_s64_array_populate(s64 dec64, int *vals)
+{
+	iio_val_s64_decompose(dec64, &vals[0], &vals[1]);
+}
+
 enum iio_available_type {
 	IIO_AVAIL_LIST,
 	IIO_AVAIL_RANGE,

-- 
2.43.0



^ permalink raw reply related

* [PATCH v12 04/11] lib: math: div64: add div64_s64_rem()
From: Rodrigo Alencar via B4 Relay @ 2026-05-10 12:42 UTC (permalink / raw)
  To: linux-kernel, linux-iio, devicetree, linux-doc
  Cc: Jonathan Cameron, David Lechner, Andy Shevchenko,
	Lars-Peter Clausen, Michael Hennerich, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Jonathan Corbet, Andrew Morton,
	Petr Mladek, Steven Rostedt, Andy Shevchenko, Rasmus Villemoes,
	Sergey Senozhatsky, Shuah Khan, Rodrigo Alencar
In-Reply-To: <20260510-adf41513-iio-driver-v12-0-34af2ed2779f@analog.com>

From: Rodrigo Alencar <rodrigo.alencar@analog.com>

Add div64_s64_rem() function, with 32-bit implementation that uses
div64_u64_rem() and a branchless approach to resolve the sign of the
remainder and quotient (negation in two's complement).

Signed-off-by: Rodrigo Alencar <rodrigo.alencar@analog.com>
---
 include/linux/math64.h | 18 ++++++++++++++++++
 lib/math/div64.c       | 15 +++++++++++++++
 2 files changed, 33 insertions(+)

diff --git a/include/linux/math64.h b/include/linux/math64.h
index cc305206d89f..99189410d4bb 100644
--- a/include/linux/math64.h
+++ b/include/linux/math64.h
@@ -57,6 +57,20 @@ static inline u64 div64_u64_rem(u64 dividend, u64 divisor, u64 *remainder)
 	return dividend / divisor;
 }
 
+/**
+ * div64_s64_rem - signed 64bit divide with 64bit divisor and remainder
+ * @dividend: signed 64bit dividend
+ * @divisor: signed 64bit divisor
+ * @remainder: pointer to signed 64bit remainder
+ *
+ * Return: sets ``*remainder``, then returns dividend / divisor
+ */
+static inline s64 div64_s64_rem(s64 dividend, s64 divisor, s64 *remainder)
+{
+	*remainder = dividend % divisor;
+	return dividend / divisor;
+}
+
 /**
  * div64_u64 - unsigned 64bit divide with 64bit divisor
  * @dividend: unsigned 64bit dividend
@@ -102,6 +116,10 @@ extern s64 div_s64_rem(s64 dividend, s32 divisor, s32 *remainder);
 extern u64 div64_u64_rem(u64 dividend, u64 divisor, u64 *remainder);
 #endif
 
+#ifndef div64_s64_rem
+extern s64 div64_s64_rem(s64 dividend, s64 divisor, s64 *remainder);
+#endif
+
 #ifndef div64_u64
 extern u64 div64_u64(u64 dividend, u64 divisor);
 #endif
diff --git a/lib/math/div64.c b/lib/math/div64.c
index d1e92ea24fce..0b10ded09a9b 100644
--- a/lib/math/div64.c
+++ b/lib/math/div64.c
@@ -158,6 +158,21 @@ u64 div64_u64(u64 dividend, u64 divisor)
 EXPORT_SYMBOL(div64_u64);
 #endif
 
+#ifndef div64_s64_rem
+s64 div64_s64_rem(s64 dividend, s64 divisor, s64 *remainder)
+{
+	s64 quot, t, rem;
+
+	quot = div64_u64_rem(abs(dividend), abs(divisor), (u64 *)&rem);
+	t = dividend >> 63;
+	*remainder = (rem ^ t) - t;
+	t = (dividend ^ divisor) >> 63;
+
+	return (quot ^ t) - t;
+}
+EXPORT_SYMBOL(div64_s64_rem);
+#endif
+
 #ifndef div64_s64
 s64 div64_s64(s64 dividend, s64 divisor)
 {

-- 
2.43.0



^ permalink raw reply related


This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox