First commit: Publish project as open source.

This commit is contained in:
Keyitdev
2026-07-28 12:52:19 +02:00
commit cc51c61859
27 changed files with 2995 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
# These are supported funding model platforms
ko_fi: keyitdev
+21
View File
@@ -0,0 +1,21 @@
name: build
on:
push:
tags:
- 'v*'
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
cc: [gcc, clang]
steps:
- uses: actions/checkout@v4
- name: Build
run: make CC=${{ matrix.cc }} CFLAGS="-O2 -Wall -Wextra -Werror -std=c11"
- name: Smoke test
run: ./asus-fan-control-ec help
- name: Staged install
run: make install DESTDIR=/tmp/pkg PREFIX=/usr && find /tmp/pkg -type f
+4
View File
@@ -0,0 +1,4 @@
build/
asus-fan-control-ec
*.o
*.d
+138
View File
@@ -0,0 +1,138 @@
## How it works
Some information stated in this document may be incorrect, this document is the result of my reverse engineering.
### Control channel
Fan control is **not** a memory region you can poke. It is a command protocol on a private pair of I/O ports, independent of the ACPI EC (`0x62`/`0x66`) and of the OEM host interface (`0x6C`/`0x68`).
| port | role |
|---|---|
| `0x25C` | data |
| `0x25D` | command and status |
Status bits on `0x25D`: `0x01` OBF (a byte is waiting to be read), `0x02` IBF (input buffer busy, do not write).
A transaction is: drain any stale output, wait for IBF to clear, write the preamble `0xFF` to the command port, write the command, then write each payload byte to the data port, waiting for IBF between bytes. For a read, wait for OBF and take the result from the data port.
Two commands matter:
| command | payload | meaning |
|---|---|---|
| `0xBB` | `50` | table version, one byte returned |
| `0xDD` | `<selector> <register> <value>` | register table access |
In the selector byte, **bit 7 selects the direction**: `0x02` reads from table 2, `0x82` writes to it.
So reading register `0x30` is `DD 02 30 00`, and writing 140 to register `0x35` is `DD 82 35 8C`.
### Registers
All in table 2, all reached with command `0xDD`.
| reg | name | access | range | notes |
|---|---|---|---|---|
| `0x30` | fan count | R | `2` | constant; used as a liveness check before any write |
| `0x31` | fan control mode | R/W | `0` / `1` | `0` = EC's own curve, `1` = manual. **Global** |
| `0x32` | fan select | W | `0``1` | chooses which fan `0x33`/`0x34`/`0x35` refer to |
| `0x33` | tachometer, low byte | R | | |
| `0x34` | tachometer, high byte | R | | `rpm = (0x34 << 8) \| 0x33` |
| `0x35` | PWM duty | R/W | `0``255` | per fan |
Two properties are easy to get wrong:
**`0x31` is global.** It is one bit for the whole controller, not one per fan. Clearing it while fan 1 is selected releases fan 0 as well. Consequently `--fan` does not confine the effect of a write.
**Entering manual mode freezes both fans** wherever the EC's curve last put them. `set X --fan 0` therefore means "freeze both fans, and give fan 0 the value X" - the fan you did not name stops responding to temperature and sits at whatever duty it happened to have.
**While `0x31` is `0`, register `0x35` belongs to the controller.** It writes its own computed duty there and overwrites anything the host puts in. Reading it in that state is useful telemetry: it shows what the EC's curve is currently doing.
### Setting a fan
```
DD 82 32 <index> select the fan
DD 82 31 01 manual mode
DD 82 32 <index> re-assert the selection
DD 82 35 <duty> duty 0-255
```
Order matters. A duty written while `0x31` is still `0` gets overwritten by the EC's curve before manual mode engages - the vendor software writes in the opposite order and has this bug.
The selector is written twice on purpose. Coming out of automatic mode, a duty write has been observed landing on the wrong fan, as if the mode write had cleared the selection. Re-asserting it costs one transaction and removes the failure.
Releasing is the mode register alone, and nothing else:
```
DD 82 31 00 leave the duty untouched
```
### Reading fan speed
Two independent paths:
- **Registers** `0x34` and `0x33` over the ports, three transactions per fan.
- **The aperture**, a read-only mirror of the controller's RAM in host physical memory. Fan speeds sit at `0xFEDD8B7C` and `0xFEDD8B7E` as big-endian 16-bit values, ready to use.
The aperture is the better source for telemetry: two bytes at roughly 1.2 µs each, no transaction, no contention with writes. `fan-info` reads both and compares them - that comparison is the validation test.
### Temperature
Temperature is **never written and never read over the control ports.** It comes entirely from the aperture, one byte per sensor:
| field | address | meaning | confidence |
|---|---|---|---|
| `CTMP` | `0xFEDD8358` | CPU temperature, whole °C | confirmed |
| `CLOT` | `0xFEDD8301` | second sensor, whole °C | name only |
`CTMP` is confirmed by the machine's own ACPI tables. The thermal zone's `_TMP` method reads that exact byte and converts it with `TTMP = CTMP * 10 + 2732`, which is degrees Celsius turned into tenths of a kelvin. That pins down the location, the unit and the fact that the rest of the system trusts the same number.
`CLOT` is declared in the ACPI field but never read by anything, so its meaning rests on the field name alone. Treat it as unverified.
Practical notes:
- **One unsigned byte.** Whole degrees, no fractions, no negatives. Do not expect it to agree with `k10temp` to the decimal - that driver reads the CPU's own registers over a completely different path.
- **The refresh rate belongs to the EC.** Reading a hundred times a second gets you nothing that reading once a second does not.
- **The controller does not measure the CPU.** It receives that number from the SoC and stores it. You are reading the EC's picture of the world.
You cannot set a temperature. What the curve does is map a temperature to a percent, convert that to a duty with `duty = round(percent * 255 / 100)`, and write the duty. `--sensor` chooses which of the two readings drives the mapping: `cpu`, `board`, or `max` (the default, and the safer choice with two sensors on one curve).
---
## The vendor path on Windows
Recorded for comparison, and as the origin of the findings above.
```
HealthyTable_SetFanPwmDuty(duty) AsusWinIO64.dll, RVA 0x28AE0
└─ RwEcCmd(len, cmd, buf, dir, &status) RVA 0x200D0
└─ DeviceIoControl(\\.\AsusSAIO,
0x80102070,
req, 16, req, 16)
└─ IOCTL dispatch AsusSAIO.sys, RVA 0x12A0
└─ handler RVA 0x1AA0
└─ transaction core RVA 0x1828
└─ port write RVA 0x1D70
└─ out dx, al RVA 0x1DCB
```
The 16-byte request structure, same buffer in and out:
| offset | type | field |
|---|---|---|
| `0x00` | u8 | command code, `0xBB` or `0xDD` |
| `0x01` | u8 | payload length, 18 |
| `0x02` | u8[8] | payload |
| `0x0A` | u8 | direction: 1 expects a returned byte, 0 is a write |
| `0x0B` | u8 | byte returned by the EC |
| `0x0C` | u32 | status, `0` = OK, `0x102` = timeout |
The library needs **SYSTEM**, not merely administrator, and the ASUS System Analysis service has to be running.
- **`0x12A0`** is the IOCTL dispatcher. It compares the control code against a list; `cmp eax, 0x80102070` sits at `0x1367` and branches to `0x13F7`.
- **`0x13F7`** rejects the request unless both buffers are at least `0x10` bytes, copies 16 bytes in, calls `0x1AA0`, copies 16 bytes back and sets `Information = 0x10`. This is where the *16 bytes, same buffer both ways* claim comes from.
- **`0x1AA0`** unpacks the structure exactly as tabulated: command from `[buf]`, length from `[buf+1]`, payload pointer `buf+2`, direction from `[buf+0xA]`, status pointer `buf+0xC`; after calling `0x1828` it stores the returned byte at `[buf+0xB]`. The call is bracketed by `KeWaitForSingleObject` and `KeReleaseMutex` - the serialising mutex is real, and any independent implementation needs its own.
- **`0x1828`** is the transaction core and carries the port numbers as literals: `mov edx, 0x25c`, and `mov edx, 0x25d` paired with `mov cl, 0xff` - the preamble byte written to the command port.
- **`0x1734`** is the status-bit wait. It polls at most `0x3E8` = **1000** times and returns `0x102` on expiry. Each iteration calls a helper at `0x1000` that wraps `KeDelayExecutionThread` with a relative interval of `arg × -10` in 100 ns units; the caller passes `0x64` = 100, so **100 µs per poll**. The `POLL_LIMIT` and `POLL_DELAY` constants in this program are the same numbers, arrived at independently.
- **`0x1D70`** is a generic port write that switches on a width byte: 1 → `out dx, al` at `0x1DCB`, 2 → `out dx, ax`, 4 → `out dx, eax`.
Two imports are worth noting. `MmMapIoSpace` / `MmUnmapIoSpace` are the driver's own route to the telemetry aperture - the same physical page this program maps through `/dev/mem`. `IoGetCurrentProcess`, `ZwOpenProcessTokenEx`, `ZwQueryInformationToken` and `RtlEqualSid` are the caller check that makes administrator insufficient: the driver compares the calling token's SID rather than checking for elevation.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+53
View File
@@ -0,0 +1,53 @@
CC ?= cc
CFLAGS ?= -O2 -Wall -Wextra -std=c11
LDFLAGS ?=
PREFIX ?= /usr/local
BINDIR ?= $(PREFIX)/bin
DATADIR ?= $(PREFIX)/share
SYSCONFDIR ?= /etc
BASHCOMPDIR ?= $(DATADIR)/bash-completion/completions
ZSHCOMPDIR ?= $(DATADIR)/zsh/site-functions
BIN := asus-fan-control-ec
SRCDIR := src
OBJDIR := build
SRC := $(wildcard $(SRCDIR)/*.c)
OBJ := $(patsubst $(SRCDIR)/%.c,$(OBJDIR)/%.o,$(SRC))
DEP := $(OBJ:.o=.d)
.PHONY: all clean install uninstall
all: $(BIN)
$(BIN): $(OBJ)
$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
$(OBJDIR)/%.o: $(SRCDIR)/%.c | $(OBJDIR)
$(CC) $(CFLAGS) -MMD -MP -c -o $@ $<
$(OBJDIR):
mkdir -p $(OBJDIR)
clean:
rm -rf $(OBJDIR) $(BIN)
install: $(BIN)
install -Dm755 $(BIN) $(DESTDIR)$(BINDIR)/$(BIN)
[ -f $(DESTDIR)$(SYSCONFDIR)/asus-fan-curve.conf ] || \
install -Dm644 asus-fan-curve.conf \
$(DESTDIR)$(SYSCONFDIR)/asus-fan-curve.conf
install -Dm644 asus-fan-control-ec.service \
$(DESTDIR)$(PREFIX)/lib/systemd/system/asus-fan-control-ec.service
install -Dm644 completions/asus-fan-control-ec.bash \
$(DESTDIR)$(BASHCOMPDIR)/$(BIN)
install -Dm644 completions/_asus-fan-control-ec \
$(DESTDIR)$(ZSHCOMPDIR)/_$(BIN)
uninstall:
rm -f $(DESTDIR)$(BINDIR)/$(BIN)
rm -f $(DESTDIR)$(PREFIX)/lib/systemd/system/asus-fan-control-ec.service
rm -f $(DESTDIR)$(BASHCOMPDIR)/$(BIN)
rm -f $(DESTDIR)$(ZSHCOMPDIR)/_$(BIN)
-include $(DEP)
+356
View File
@@ -0,0 +1,356 @@
# asus-fan-control-ec
asus-fan-control-ec provides fan-control support for ASUS devices, mainly those with AMD processors and systems affected by the `ACPI Error: AE_NOT_FOUND` issue, where the standard ACPI-based interface is unavailable.
[![Build](https://github.com/Keyitdev/asus-fan-control-ec/actions/workflows/build.yml/badge.svg)](https://github.com/Keyitdev/asus-fan-control-ec/actions/workflows/build.yml)
[![Ko-fi](https://img.shields.io/badge/support_me_on_ko--fi-F16061?logo=kofi&logoColor=f5f5f5)](https://ko-fi.com/keyitdev)
**[Quick start](#quick-start) · [Build](#build) · [Usage](#usage) · [Tested devices](#tested-devices) · [How it works](HOW-IT-WORKS.md) · [Support](#support)**
---
## Why this exists
On some ASUS laptops, the fans cannot be set the standard way. There is no hwmon interface for them, no `EmbeddedControl` region for the kernel's EC driver to attach to, and no ACPI method that reaches the fan registers at all.
Existing tools such as [asus-fan-control](https://github.com/dominiksalvet/asus-fan-control) work around this as ACPI clients: through the `acpi_call` module they invoke a firmware method the vendor already provides, which rewrites the temperature thresholds of the controller's built-in curve. That depends on an ACPI EC object that these laptops do not expose, and even where it works it only shifts when the controller changes gear - it cannot set a duty.
This project takes the other route and implements the protocol itself, talking to the **embedded controller directly**. It drives a private pair of I/O ports - 0x25C for data and 0x25D for command and status, independent of the ACPI EC at 0x62/0x66 - carrying the controller's own register-table command, and it reads temperatures and tachometers out of a read-only window onto the controller's RAM mapped through /dev/mem. No kernel module, no firmware method, nothing between the program and the hardware.
## Quick start
Build first, then check whether your machine is compatible - **before writing anything to it**.
```sh
make
sudo ./asus-fan-control-ec fan-info
```
> [!IMPORTANT]
> `fan-info` is the compatibility check, and it is the only command which is almost safe to run blind:
it writes no duty and no control mode, so it cannot change how the machine is cooled.
What it does is read each fan's speed twice over two independent paths - once through
the I/O ports, once out of the telemetry aperture - and compare them. Agreement proves
the ports, the command encoding and the register numbers are all correct on your device.
Look at the last line. If it reads
```
Result: VALIDATED against the MMIO aperture.
```
you are compatible and can carry on. Anything else - a `MISMATCH` verdict, an error,
a non-zero exit status - means the program is not talking to your embedded controller
correctly. **Stop there. Do not run `set` or `setp`**. Let me know - open issue.
Only once validated:
```sh
sudo ./asus-fan-control-ec setp 90
sudo ./asus-fan-control-ec setp -1
```
`setp 90` pins both fans at 90%. `setp -1` hands the fans back to the embedded
controller, and is the only correct way to undo the previous line.
## Requirements
Root. The program needs `ioperm` (or `/dev/port`) for the control channel and `/dev/mem` for telemetry.
If your kernel was built with `CONFIG_STRICT_DEVMEM=y` - most distribution kernels are - `/dev/mem` access to the aperture may be refused. Boot with `iomem=relaxed` if telemetry fails while the ports still work.
## Build
No dependencies beyond libc and a C11 compiler.
```sh
make
```
Produces `./asus-fan-control-ec`. Object files land in `build/`.
```sh
make clean # remove build/ and the binary
sudo make install # installs globally - see below
sudo make uninstall # removes everything install put on the system
```
**`make install` installs globally.** It copies files out of the source tree and
into system directories: the binary onto your `PATH`, plus the example config,
the systemd unit and the bash and zsh completion scripts. That is why it needs
root. If you only want to try the program out, do not run it - build and use
`./asus-fan-control-ec` in place. `sudo make uninstall` reverses the install.
An existing `/etc/asus-fan-curve.conf` is never overwritten by `install`.
## Usage
```
asus-fan-control-ec [global options] <command> [options]
```
### Setting fan speed
#### `set DUTY`
Sets the PWM duty on every fan, or on one fan with `--fan`.
```sh
sudo asus-fan-control-ec set 140 # duty 0-255
sudo asus-fan-control-ec set -1 # hand control back to the EC
```
```
Fan count: 2, speeds before: 3575/3673 rpm.
Attempt 1/3, fans 0 1, duty 140.
fan 0:
Set: OK
PWM duty: 138 (54%) (0x35=138)
fan 1:
Set: OK
PWM duty: 138 (54%) (0x35=138)
Fan count: 2, speeds after: 3796/3789 rpm.
```
Reading back `138` after writing `140` is normal (duty quantisation).
`speeds after` is sampled immediately, so it shows the fans mid-spin-up, not at their final speed.
| option | meaning |
|---|---|
| `--fan N` | act on one fan only (see the warning below) |
| `--retries N` | write attempts before giving up, default 3 |
| `--no-verify` | write and exit without reading back |
| `--order mode-first\|duty-first` | order of the manual-mode and duty writes, default `mode-first` |
#### `setp PERCENT`
Same as `set`, in percent. `-1` releases, exactly like `set -1`.
```sh
sudo asus-fan-control-ec setp 55
```
#### `curve`
Runs a fan curve from a config file until stopped.
```sh
sudo asus-fan-control-ec curve
sudo asus-fan-control-ec curve --once --dry-run # show what it would do
```
```
Curve loaded from /etc/asus-fan-curve.conf.
below 77 C -> 0%
77-86 C -> 15%
86-89 C -> 20%
89-92 C -> 40%
92-95 C -> 60%
95 C and above -> 80%
sensor=max interval=3.0s hysteresis=3C panic=96C
00:21:28 temp=50C target= 0% manual applied fan0= 2173 fan1= 2186
00:21:31 temp=50C target= 0% manual hold fan0= 0 fan1= 0
00:21:34 temp=50C target= 0% manual hold fan0= 0 fan1= 0
00:21:37 temp=88C target= 20% manual applied fan0= 890 fan1= 740
00:21:41 temp=92C target= 60% manual applied fan0= 3024 fan1= 2366
^CHanded fan control back to the EC.
```
The mode column reflects the **actual** state, derived from the last successful operation, not from what was requested.
| status | meaning |
|---|---|
| `applied` | took on the first try |
| `retried` | took after one or more retries |
| `hold` | no change needed |
| `FAILED` | did not take; the target is not recorded, so the next tick tries again |
| option | default | meaning |
|---|---|---|
| `--config PATH` | `/etc/asus-fan-curve.conf` | curve file |
| `--interval S` | 3.0 | seconds between ticks |
| `--hysteresis C` | 3 | degrees of resistance to stepping down |
| `--panic-temp C` | 96 | force 100% at or above this |
| `--sensor cpu\|board\|max` | `max` | which temperature drives the curve |
| `--retries N` | 3 | write attempts per change |
| `--once` | | one tick, then exit without releasing |
| `--dry-run` | | print the parsed curve and exit |
| `--silent` | | suppress the periodic line; retries and failures still print |
#### Config file format
One band per line, `percent,temperature`. Blank lines and `#` comments are ignored. Order does not matter; bands are sorted by temperature.
```
# percent,temperature
-1,0
20,60
40,75
80,90
```
Reads as: below 60 °C let the EC do its thing, from 60 °C hold 20%, from 75 °C hold 40%, from 90 °C hold 80%.
A percent of **`-1` hands that band back to the embedded controller**, which is useful for staying out of the way while idle and only taking over when things get warm.
Hysteresis works on band indexes, not on percentages: the curve steps up immediately, and steps down only once `temperature + hysteresis` also falls into the lower band.
#### Running as a service
```sh
sudo systemctl enable --now asus-fan-control-ec
```
The unit runs `curve --silent`. The daemon handles `SIGTERM`, `SIGINT` and `SIGHUP` and releases the fans back to the EC on exit; `ExecStopPost` repeats the release as a safety net.
### Reading measurements
#### `fan-speed`
```
Fan control: Manual (0x31=1)
fan 0: 3963 rpm
fan 1: 4091 rpm
```
#### `fan-info`
Full state plus a validation of the control channel against the telemetry aperture. **Run this first on a new machine.**
```
Fan count: 2 (0x30=2)
Fan control: Manual (0x31=1)
fan0:
PWM duty: 138 (54%) (0x35=138)
Fan speed reg: 3949 rpm (0x34/0x33 = 0F 6D)
Fan speed mmio: 3949 rpm (0xFEDD8B7C)
Verdict: MATCH
fan1:
PWM duty: 138 (54%) (0x35=138)
Fan speed reg: 4083 rpm (0x34/0x33 = 0F F3)
Fan speed mmio: 4083 rpm (0xFEDD8B7E)
Verdict: MATCH
Result: VALIDATED against the MMIO aperture.
```
`MATCH` means the fan speed read over the I/O ports agrees with the same speed read out of mapped memory, within 64 rpm. Two independent paths reaching the same number proves the handshake, the command encoding, the register identification and the fan selector are all correct. Exit status is 0 only when everything matches.
The only register this command writes is the fan selector `0x32`, which it has to write in order to read anything per fan. **It never touches the duty `0x35` or the control mode `0x31`**, so it cannot change how the machine is cooled. On an untested model that distinction matters: if `0x32` turns out to mean something else there, this command has still written to it.
It does *not* prove the speed itself is accurate. Both paths originate from the same counter inside the controller.
#### `temps-info`
```
CPU: 44 C (0xFEDD8358 = 2C, ERAM+0x58 CTMP)
Board: 39 C (0xFEDD8301 = 27, ERAM+0x01 CLOT)
Max: 44 C (higher of the two)
```
#### `version`
```
Laptop model: ASUSTeK COMPUTER INC. ASUS TUF Gaming A15 FA507NV_FA507NV (DMI)
Embedded controller version: 3.18 (0xFEDD83E4 = 03 12)
Healthy table version: 17 (0xBB 50)
```
### Global options
`--cmd-port N`, `--data-port N`, `--gap SECONDS`, `--verbose`.
`--verbose` traces every byte written to the ports. `--gap` is the delay after each write, 20 ms by default; the hardware handshake alone is not enough for the controller to keep up.
## Tested devices
| Name | Model | CPU | Embedded Controller version | Support Status |
|-|-|-|-|-|
|ASUS TUF Gaming A15|FA507NV_FA507NV|AMD|3.18|Fully supported|
|ASUS TUF Gaming A15|FA506IU_FA506IU|AMD|3.19|Fully supported|
Other models in the family may work, but the ports, addresses and register numbers were confirmed on these machines only.
If your device is not supported, you may want to check out other amazing projects, such as [asus-fan-control](https://github.com/dominiksalvet/asus-fan-control).
## Reporting problems
**Start with the [Tested devices](#tested-devices) table.** Which half of it you land in
decides what a useful report looks like.
### Your device is in the table
Then the ports, addresses and register numbers are known to be correct for it, and what
you are seeing is a bug rather than an unsupported machine. Reproduce it before writing
the report:
1. Run `sudo asus-fan-control-ec version` and `sudo asus-fan-control-ec fan-info`.
2. Re-run the command that misbehaved with `--verbose`, which traces every byte written
to the ports.
3. Write down what you expected and what happened instead.
[Open an issue](../../issues/new) with those three things, plus your distribution and
the output of `uname -r`. If you changed `--cmd-port`, `--data-port` or `--gap`, say so -
otherwise the trace is being read against the wrong assumptions.
### Your device is not in the table
Report it anyway, and keep it short. Run `fan-info` first, because its last line answers
the only question that matters:
- **`Result: VALIDATED against the MMIO aperture.`** - the protocol works on your model.
Open an issue with the full output of `version` and `fan-info` and the device can be
added to the table.
- **Anything else** - a `MISMATCH` verdict, an error, a non-zero exit status. Stop there,
do not run `set` or `setp`, and open an issue with the same two outputs and whatever
error you saw. Two sentences describing the machine are enough.
Paste output as text rather than a screenshot; register values are the whole point of
the report and they need to be searchable.
## Safety
Trademarks and ownership. ASUS, ASUSTeK, TUF and TUF Gaming are trademarks of ASUSTeK Computer Inc. They appear here descriptively, to identify the hardware this program was written for, and nothing more. This project is independent: not affiliated with, authorised by, endorsed by, or sponsored by ASUSTeK Computer Inc., and the author claims no rights in the company's trademarks, firmware, drivers or hardware designs. No vendor code is included.
> [!WARNING]
> **No warranty.** This program writes to undocumented registers of an embedded controller. Used carelessly it can stop the fans, overheat the machine, or leave the cooling system in a state the firmware does not expect - and the register family it uses reaches further than fans, into battery state and non-volatile manufacturing data. It is distributed with absolutely no warranty. You run it as root on your own hardware, at your own risk; the author accepts no liability for damage to devices, loss of data, voided warranties, or anything else that follows from its use. Read the [Safety](#safety) section before the first write, and run fan-info before trusting any of it on a model that is not in the tested table.
> [!WARNING]
> **Duty `0` stops the fans and does not give control back.** The controller accepts zero as a valid setting and holds it indefinitely, regardless of temperature. The only correct way to return control is writing `0x31 = 0` **without touching the duty** - that is what `set -1` does.
>
> **`--fan` does not limit the damage.** Because `0x31` is global and manual mode freezes both fans, a write aimed at one fan changes the state of both. Run `fan-info` afterwards and check the other fan's duty.
>
> **Always release before exiting.** Any process holding a curve needs signal handling that releases the fans. `curve` does this; if you script `set` yourself, you own that responsibility.
> [!CAUTION]
> **Do not guess command codes.** The same `0xDD` command family includes battery state operations and writes to non-volatile memory holding the device's manufacturing data. Experimenting with undocumented registers **risks permanent damage**.
**Recovering a stuck Embedded controller:**
1. Remove all external devices.
2. Turn off the device.
3. Connect the power adapter.
4. Press and hold the power button for 40 seconds.
5. More info: [here](https://www.asus.com/support/faq/1050239/)
## Support
Everything this program does had to be worked out by hand: the port pair, the handshake,
the command encoding and every register number were found by probing an undocumented
controller and checking each guess against a second, independent read path. That is slow
work. If the project saved you from a laptop that runs its fans however it likes, a contribution is welcome
and keeps the work going.
[![Ko-fi](https://img.shields.io/badge/support_me_on_ko--fi-F16061?style=for-the-badge&logo=kofi&logoColor=f5f5f5)](https://ko-fi.com/keyitdev)
[https://ko-fi.com/keyitdev](https://ko-fi.com/keyitdev)
## How it works
If you want to read more:
[How it works](HOW-IT-WORKS.md)
## License
Distributed under the **[GPLv3+](https://www.gnu.org/licenses/gpl-3.0.html) License**.
Copyright (C) 2026 Keyitdev.
+13
View File
@@ -0,0 +1,13 @@
[Unit]
Description=asus-fan-control-ec fan curve daemon
After=multi-user.target
[Service]
Type=simple
ExecStart=/usr/local/bin/asus-fan-control-ec curve --silent
ExecStopPost=-/usr/local/bin/asus-fan-control-ec set -1
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
+5
View File
@@ -0,0 +1,5 @@
# percent,temperature
# percent -1 hands that band back to the embedded controller
20,70
40,80
80,90
+61
View File
@@ -0,0 +1,61 @@
#compdef asus-fan-control-ec
_asus-fan-control-ec() {
local state
local -a commands globals
commands=(
'set:set PWM duty 0-255, or -1 to hand control back to the EC'
'setp:set duty in percent, or -1 for the same release'
'curve:run the fan curve daemon'
'fan-speed:show control mode and fan speeds'
'fan-info:full state plus channel validation'
'temps-info:show both temperatures with their addresses'
'help:show usage'
'version:show model, EC version and project info'
)
globals=(
'--cmd-port[command port]:port:'
'--data-port[data port]:port:'
'--gap[delay after each write, seconds]:seconds:'
'--verbose[trace every port write]'
)
_arguments -C $globals '1: :->command' '*:: :->args'
case $state in
command)
_describe -t commands 'command' commands
;;
args)
case $words[1] in
set|setp)
_arguments $globals \
'--fan[act on one fan only]:index:(0 1)' \
'--retries[write attempts before giving up]:count:' \
'--no-verify[write and exit without reading back]' \
'--order[order of the mode and duty writes]:order:(mode-first duty-first)'
;;
curve)
_arguments $globals \
'--config[curve file]:file:_files' \
'--interval[seconds between ticks]:seconds:' \
'--hysteresis[degrees of resistance to stepping down]:degrees:' \
'--panic-temp[force 100 percent at or above]:degrees:' \
'--sensor[which temperature drives the curve]:sensor:(cpu board max)' \
'--retries[write attempts per change]:count:' \
'--order[order of the mode and duty writes]:order:(mode-first duty-first)' \
'--once[one tick, then exit without releasing]' \
'--dry-run[print the parsed curve and exit]' \
'--silent[suppress the periodic line]'
;;
*)
_arguments $globals
;;
esac
;;
esac
}
_asus-fan-control-ec "$@"
+64
View File
@@ -0,0 +1,64 @@
_asus_fan_control_ec()
{
local cur prev cmd word i skip
local commands="set setp curve fan-speed fan-info temps-info help version"
local globals="--cmd-port --data-port --gap --verbose"
local valued="--cmd-port --data-port --gap --fan --retries --order --config --interval --hysteresis --panic-temp --sensor"
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
case "$prev" in
--order)
COMPREPLY=( $(compgen -W "mode-first duty-first" -- "$cur") )
return ;;
--sensor)
COMPREPLY=( $(compgen -W "cpu board max" -- "$cur") )
return ;;
--config)
COMPREPLY=( $(compgen -f -- "$cur") )
return ;;
--fan)
COMPREPLY=( $(compgen -W "0 1" -- "$cur") )
return ;;
--cmd-port|--data-port|--gap|--retries|--interval|--hysteresis|--panic-temp)
return ;;
esac
cmd=""
skip=0
for (( i=1; i < COMP_CWORD; i++ )); do
word="${COMP_WORDS[i]}"
if [ "$skip" = 1 ]; then
skip=0
continue
fi
case " $valued " in
*" $word "*)
skip=1
continue ;;
esac
case " $commands " in
*" $word "*)
cmd="$word"
break ;;
esac
done
if [ -z "$cmd" ]; then
COMPREPLY=( $(compgen -W "$commands $globals" -- "$cur") )
return
fi
case "$cmd" in
set|setp)
COMPREPLY=( $(compgen -W "--fan --retries --no-verify --order $globals" -- "$cur") ) ;;
curve)
COMPREPLY=( $(compgen -W "--config --interval --hysteresis --panic-temp --sensor --retries --order --once --dry-run --silent $globals" -- "$cur") ) ;;
*)
COMPREPLY=( $(compgen -W "$globals" -- "$cur") ) ;;
esac
}
complete -F _asus_fan_control_ec asus-fan-control-ec
+396
View File
@@ -0,0 +1,396 @@
#define _GNU_SOURCE
#include "commands.h"
#include "common.h"
#include "ec.h"
#include "fan.h"
#include "healthy.h"
#include "mmio.h"
#include "util.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static void print_model(void)
{
char vendor[128], product[128];
if (read_line_file("/sys/class/dmi/id/sys_vendor", vendor, sizeof vendor) &&
read_line_file("/sys/class/dmi/id/product_name", product, sizeof product))
printf("Laptop model: %s %s (DMI)\n", vendor, product);
else if (read_line_file("/sys/class/dmi/id/product_name", product,
sizeof product))
printf("Laptop model: %s (DMI)\n", product);
else
printf("Laptop model: unreadable (/sys/class/dmi/id)\n");
}
static void print_identity(hy_t *h, mmio_t *m)
{
uint8_t version;
int mj, mn;
print_model();
mj = mmio_at(m, ECMJ);
mn = mmio_at(m, ECMN);
printf("Embedded controller version: %d.%d (0x%08lX = %02X %02X)\n", mj, mn,
ECMJ, (unsigned)mj, (unsigned)mn);
if (hy_version(h, &version))
printf("Healthy table version: unreadable (0xBB 50)\n");
else
printf("Healthy table version: %d (0xBB 50)\n", version);
}
static void print_project(void)
{
printf("\n");
printf("%s version: %s\n", APP_NAME, APP_VERSION);
printf("Source code: %s\n", APP_URL);
printf("Support the project: %s\n", APP_KOFI);
printf("License: %s\n", APP_LICENSE);
printf("%s\n", APP_COPYRIGHT);
}
int cmd_version(args_t *a)
{
ec_t ec;
hy_t h;
mmio_t mm;
if (geteuid() == 0) {
ec_open(&ec, a->cmd_port, a->data_port, a->verbose);
h.ec = &ec;
h.gap = a->gap;
mmio_open(&mm, ERM2);
print_identity(&h, &mm);
mmio_close(&mm);
ec_close(&ec);
} else {
print_model();
printf("Embedded controller version: root required\n");
printf("Healthy table version: root required\n");
}
print_project();
return 0;
}
int cmd_fan_info(args_t *a)
{
ec_t ec;
hy_t h;
mmio_t mm;
int duty[MAX_FANS], mode[MAX_FANS], rpm[MAX_FANS];
int hi[MAX_FANS], lo[MAX_FANS], ref[MAX_FANS];
int count, idx, agree = 0, checked = 0, spinning = 0, rc = 0;
bool uniform = true;
ec_open(&ec, a->cmd_port, a->data_port, a->verbose);
h.ec = &ec;
h.gap = a->gap;
mmio_open(&mm, ERM2);
count = fan_count_or_default(&h);
if (count < 1 || count > MAX_FANS) {
printf("Fan count: unreadable (0x30 out of range)\n");
rc = 1;
goto out;
}
printf("Fan count: %d (0x30=%d)\n", count, count);
for (idx = 0; idx < count; idx++) {
uint8_t d = 0, m = 0, rh = 0, rl = 0;
duty[idx] = -1;
mode[idx] = -1;
rpm[idx] = -1;
ref[idx] = -1;
hi[idx] = 0;
lo[idx] = 0;
if (hy_select(&h, idx))
continue;
if (!hy_read(&h, REG_PWM_DUTY, &d))
duty[idx] = d;
if (!hy_read(&h, REG_TEST_MODE, &m))
mode[idx] = m;
if (!hy_read(&h, REG_RPM_HI, &rh) && !hy_read(&h, REG_RPM_LO, &rl)) {
hi[idx] = rh;
lo[idx] = rl;
rpm[idx] = (rh << 8) | rl;
}
if (idx < 2)
ref[idx] = mmio_be16(&mm, TACH_OFFSET + 2 * (unsigned long)idx);
if (ref[idx] > 0)
spinning++;
}
for (idx = 1; idx < count; idx++)
if (mode[idx] != mode[0])
uniform = false;
if (!uniform)
printf("Fan control: differs between fans (see below)\n");
else if (mode[0] < 0)
printf("Fan control: unreadable (0x31)\n");
else
printf("Fan control: %s (0x31=%d)\n", mode_name(mode[0]), mode[0]);
for (idx = 0; idx < count; idx++) {
unsigned long addr = ERM2 + TACH_OFFSET + 2 * (unsigned long)idx;
int expect = ref[idx];
printf("\nfan%d:\n", idx);
if (duty[idx] < 0)
printf(" PWM duty: unreadable (0x35)\n");
else
printf(" PWM duty: %d (%d%%) (0x35=%d)\n", duty[idx],
duty_to_percent(duty[idx]), duty[idx]);
if (!uniform)
printf(" Fan control: %s (0x31=%d)\n", mode_name(mode[idx]),
mode[idx]);
if (rpm[idx] < 0)
printf(" Fan speed reg: unreadable (0x34/0x33)\n");
else
printf(" Fan speed reg: %d rpm (0x34/0x33 = %02X %02X)\n", rpm[idx],
(unsigned)hi[idx], (unsigned)lo[idx]);
if (expect < 0)
printf(" Fan speed mmio: no aperture slot\n");
else
printf(" Fan speed mmio: %d rpm (0x%08lX)\n", expect, addr);
if (rpm[idx] < 0 || expect < 0) {
printf(" Verdict: UNKNOWN\n");
continue;
}
checked++;
if (abs(rpm[idx] - expect) <= TACH_TOL) {
agree++;
printf(" Verdict: MATCH\n");
} else {
printf(" Verdict: MISMATCH\n");
}
}
printf("\n");
if (!spinning) {
printf("Result: both tachometers read zero, spin the fans up and retry.\n");
rc = 1;
} else if (checked == count && agree == count) {
printf("Result: VALIDATED against the MMIO aperture.\n");
printf("If the program works on your device and it is not listed\nin the tested devices section on github, please open an issue.\n");
} else {
printf("Result: NOT VALIDATED, do not write anything.\n");
rc = 1;
}
out:
mmio_close(&mm);
ec_close(&ec);
return rc;
}
int cmd_temps_info(args_t *a)
{
mmio_t mm;
int cpu, board;
(void)a;
mmio_open(&mm, ERAM);
cpu = mmio_at(&mm, CTMP);
board = mmio_at(&mm, CLOT);
mmio_close(&mm);
printf("CPU: %d C (0x%08lX = %02X, ERAM+0x58 CTMP)\n", cpu, CTMP,
(unsigned)cpu);
printf("Board: %d C (0x%08lX = %02X, ERAM+0x01 CLOT)\n", board, CLOT,
(unsigned)board);
printf("Max: %d C (higher of the two)\n", imax(cpu, board));
return 0;
}
int cmd_fan_speed(args_t *a)
{
ec_t ec;
hy_t h;
uint8_t mode;
int n, idx;
ec_open(&ec, a->cmd_port, a->data_port, a->verbose);
h.ec = &ec;
h.gap = a->gap;
n = fan_count_or_default(&h);
if (n < 1 || n > MAX_FANS)
n = 2;
if (hy_read(&h, REG_TEST_MODE, &mode))
printf("Fan control: unreadable (0x31)\n");
else
printf("Fan control: %s (0x31=%d)\n", mode_name(mode), mode);
for (idx = 0; idx < n; idx++) {
int rpm;
if (hy_select(&h, idx) || hy_rpm(&h, &rpm))
printf("fan %d: speed unreadable\n", idx);
else
printf("fan %d: %d rpm\n", idx, rpm);
}
ec_close(&ec);
return 0;
}
static int verify(hy_t *h, int duty, const int *pending, int npending,
int *failed)
{
int i, nfailed = 0;
for (i = 0; i < npending; i++) {
int idx = pending[i], rb, md;
bool ok;
printf("fan %d:\n", idx);
if (readback(h, idx, &rb, &md)) {
printf(" Set: FAILED, readback error: %s\n", ec_error);
printf(" PWM duty: unreadable (0x35)\n");
ok = false;
} else {
ok = duty_close(rb, duty);
if (ok)
printf(" Set: OK\n");
else
printf(" Set: FAILED, wanted duty %d\n", duty);
printf(" PWM duty: %d (%d%%) (0x35=%d)\n", rb, duty_to_percent(rb),
rb);
}
if (!ok)
failed[nfailed++] = idx;
}
return nfailed;
}
static int drive(hy_t *h, int duty, const int *targets, int ntargets,
args_t *a, int *left)
{
int pending[MAX_FANS], npending = ntargets;
int failed[MAX_FANS], nfailed;
int attempt, i;
char list[64];
memcpy(pending, targets, sizeof(int) * (size_t)ntargets);
for (attempt = 1; attempt <= a->retries; attempt++) {
join_ints(list, sizeof list, pending, npending);
printf("Attempt %d/%d, fans %s, duty %d.\n", attempt, a->retries, list, duty);
for (i = 0; i < npending; i++)
if (apply_duty(h, pending[i], duty, a->order))
printf(" fan %d FAIL, write failed: %s.\n", pending[i], ec_error);
if (a->no_verify)
return 0;
nfailed = verify(h, duty, pending, npending, failed);
if (!nfailed)
return 0;
memcpy(pending, failed, sizeof(int) * (size_t)nfailed);
npending = nfailed;
}
memcpy(left, pending, sizeof(int) * (size_t)npending);
return npending;
}
static int run_set(args_t *a, int duty)
{
ec_t ec;
hy_t h;
mmio_t mm;
int count, targets[MAX_FANS], ntargets, left[MAX_FANS], nleft, fans[2], i;
char list[64];
if (duty < 0 || duty > 255)
die("Duty must be 0..255, or -1 to hand control back to the EC.");
ec_open(&ec, a->cmd_port, a->data_port, a->verbose);
h.ec = &ec;
h.gap = a->gap;
mmio_open(&mm, ERM2);
count = fan_count_or_default(&h);
if (count < 1 || count > MAX_FANS) {
mmio_close(&mm);
ec_close(&ec);
die("Fan count from 0x30 is implausible, refusing to write.");
}
mmio_fans(&mm, fans);
printf("Fan count: %d, speeds before: %d/%d rpm.\n", count, fans[0], fans[1]);
if (a->index < 0) {
ntargets = count;
for (i = 0; i < count; i++)
targets[i] = i;
} else {
ntargets = 1;
targets[0] = a->index;
}
nleft = drive(&h, duty, targets, ntargets, a, left);
mmio_fans(&mm, fans);
printf("Fan count: %d, speeds after: %d/%d rpm.\n", count, fans[0], fans[1]);
mmio_close(&mm);
ec_close(&ec);
if (nleft) {
join_ints(list, sizeof list, left, nleft);
printf("\n");
printf("Fans %s did not take the setting after %d attempts.\n", list,
a->retries);
return 1;
}
return 0;
}
static int run_release(args_t *a)
{
ec_t ec;
hy_t h;
int left[MAX_FANS];
int n, nleft;
char list[64];
ec_open(&ec, a->cmd_port, a->data_port, a->verbose);
h.ec = &ec;
h.gap = a->gap;
n = fan_count_or_default(&h);
if (n < 1 || n > MAX_FANS)
n = 2;
hand_back(&h, n);
nleft = still_manual(&h, n, left);
if (nleft) {
join_ints(list, sizeof list, left, nleft);
printf("Fans %s still in manual, retrying.\n", list);
hand_back(&h, n);
nleft = still_manual(&h, n, left);
}
ec_close(&ec);
if (nleft) {
join_ints(list, sizeof list, left, nleft);
printf("Fans %s are still in manual, the EC did not take the release.\n",
list);
return 1;
}
printf("Handed fan control back to the EC.\n");
return 0;
}
int cmd_set(args_t *a)
{
if (a->duty == RELEASE_ARG)
return run_release(a);
return run_set(a, a->duty);
}
int cmd_setp(args_t *a)
{
int duty;
if (a->percent == RELEASE_ARG)
return run_release(a);
if (a->percent < 0 || a->percent > 100)
die("Percent must be 0..100, or -1 to hand control back to the EC.");
duty = percent_to_duty(a->percent);
printf("%d%% maps to duty %d.\n", a->percent, duty);
return run_set(a, duty);
}
+13
View File
@@ -0,0 +1,13 @@
#ifndef AFC_COMMANDS_H
#define AFC_COMMANDS_H
#include "common.h"
int cmd_version(args_t *a);
int cmd_fan_info(args_t *a);
int cmd_fan_speed(args_t *a);
int cmd_temps_info(args_t *a);
int cmd_set(args_t *a);
int cmd_setp(args_t *a);
#endif
+77
View File
@@ -0,0 +1,77 @@
#ifndef AFC_COMMON_H
#define AFC_COMMON_H
#include <stdbool.h>
#define DATA_PORT 0x25C
#define CMD_PORT 0x25D
#define PREAMBLE 0xFF
#define CMD_VERSION 0xBB
#define CMD_TABLE 0xDD
#define TBL_READ 0x02
#define TBL_WRITE 0x82
#define REG_FAN_COUNT 0x30
#define REG_TEST_MODE 0x31
#define REG_FAN_INDEX 0x32
#define REG_RPM_LO 0x33
#define REG_RPM_HI 0x34
#define REG_PWM_DUTY 0x35
#define ERM2 0xFEDD8B00UL
#define ERAM 0xFEDD8300UL
#define PAGE_MASK (~0xFFFUL)
#define CTMP (ERAM + 0x58)
#define CLOT (ERAM + 0x01)
#define ECMJ (ERAM + 0xE4)
#define ECMN (ERAM + 0xE5)
#define TACH_OFFSET 0x7C
#define APP_NAME "asus-fan-control-ec"
#define APP_VERSION "v1.0.0"
#define APP_URL "https://github.com/Keyitdev/asus-fan-control-ec"
#define APP_KOFI "https://ko-fi.com/keyitdev"
#define APP_LICENSE "GPLv3+"
#define APP_COPYRIGHT "Copyright (C) 2026 Keyitdev."
#define DEFAULT_CONFIG "/etc/asus-fan-curve.conf"
#define PANIC_TEMP 96
#define HYSTERESIS 3
#define INTERVAL 3.0
#define OBF 0x01
#define IBF 0x02
#define POLL_LIMIT 1000
#define POLL_DELAY 0.0001
#define RETRIES 2
#define IO_GAP 0.02
#define TOL_PCT 5
#define TOL_MIN 3
#define READ_RETRIES 3
#define TACH_TOL 64
#define RELEASE_ARG (-1)
#define CURVE_UNSET (-2)
#define MAX_FANS 2
#define MAX_POINTS 64
enum { ORDER_MODE_FIRST, ORDER_DUTY_FIRST };
enum { SENSOR_CPU, SENSOR_BOARD, SENSOR_MAX };
enum { APPLY_FAILED, APPLY_CLEAN, APPLY_RETRIED };
typedef struct {
unsigned cmd_port;
unsigned data_port;
double gap;
bool verbose;
int index;
int retries;
bool no_verify;
int order;
int duty;
int percent;
const char *config;
double interval;
int hysteresis;
int panic_temp;
int sensor;
bool once;
bool dry_run;
bool silent;
} args_t;
#endif
+296
View File
@@ -0,0 +1,296 @@
#define _GNU_SOURCE
#include "curve.h"
#include "ec.h"
#include "fan.h"
#include "healthy.h"
#include "mmio.h"
#include "util.h"
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static volatile sig_atomic_t stop_flag = 0;
static int point_cmp(const void *a, const void *b)
{
const point_t *p = a, *q = b;
if (p->temp != q->temp)
return p->temp < q->temp ? -1 : 1;
if (p->percent != q->percent)
return p->percent < q->percent ? -1 : 1;
return 0;
}
static int load_curve(const char *path, point_t *points)
{
FILE *f = fopen(path, "r");
char line[256];
int n = 0, num = 0, i;
if (!f)
die("Config not found: %s.", path);
while (fgets(line, sizeof line, f)) {
char *hash, *sep, *end, *rest;
long percent, temp;
num++;
hash = strchr(line, '#');
if (hash)
*hash = '\0';
rest = line;
while (*rest && isspace((unsigned char)*rest))
rest++;
end = rest + strlen(rest);
while (end > rest && isspace((unsigned char)end[-1]))
*--end = '\0';
if (!*rest)
continue;
sep = strpbrk(rest, ",;");
if (!sep || strpbrk(sep + 1, ",;")) {
fclose(f);
die("%s:%d: expected 'percent,temp'.", path, num);
}
*sep = '\0';
errno = 0;
percent = strtol(rest, &end, 10);
while (end && *end && isspace((unsigned char)*end))
end++;
if (errno || end == rest || *end) {
fclose(f);
die("%s:%d: not a pair of integers.", path, num);
}
rest = sep + 1;
while (*rest && isspace((unsigned char)*rest))
rest++;
errno = 0;
temp = strtol(rest, &end, 10);
while (end && *end && isspace((unsigned char)*end))
end++;
if (errno || end == rest || *end) {
fclose(f);
die("%s:%d not a pair of integers", path, num);
}
if ((percent < 0 && percent != RELEASE_ARG) || percent > 100) {
fclose(f);
die("%s:%d: percent must be 0..100, or -1 for EC control.", path, num);
}
if (temp < 0 || temp > 120) {
fclose(f);
die("%s:%d: temperature out of range.", path, num);
}
if (n == MAX_POINTS) {
fclose(f);
die("%s has too many points.", path);
}
points[n].temp = (int)temp;
points[n].percent = (int)percent;
n++;
}
fclose(f);
if (!n)
die("%s has no usable lines.", path);
qsort(points, (size_t)n, sizeof points[0], point_cmp);
for (i = 1; i < n; i++)
if (points[i].temp == points[i - 1].temp)
die("%s has duplicate temperatures.", path);
return n;
}
static const char *percent_text(char *buf, size_t size, int percent)
{
if (percent == RELEASE_ARG)
snprintf(buf, size, "EC (auto)");
else
snprintf(buf, size, "%d%%", percent);
return buf;
}
static void describe_curve(const point_t *points, int n)
{
char text[16];
int i;
if (points[0].temp > 0)
printf(" below %d C -> 0%%\n", points[0].temp);
for (i = 0; i < n; i++) {
percent_text(text, sizeof text, points[i].percent);
if (i + 1 < n)
printf(" %d-%d C -> %s\n", points[i].temp, points[i + 1].temp, text);
else
printf(" %d C and above -> %s\n", points[i].temp, text);
}
}
static int curve_band(const point_t *points, int n, int temp, int current,
int hysteresis)
{
int band = -1, keep = -1, i;
for (i = 0; i < n; i++) {
if (temp >= points[i].temp)
band = i;
if (temp + hysteresis >= points[i].temp)
keep = i;
}
if (current == CURVE_UNSET || band >= current)
return band;
return imax(band, imin(current, keep));
}
static int band_percent(const point_t *points, int band)
{
return band < 0 ? 0 : points[band].percent;
}
static int apply_percent(hy_t *h, int count, int percent, args_t *a)
{
int duty = percent_to_duty(percent);
int marks[MAX_FANS];
int attempt, r, idx;
bool retried = false;
for (attempt = 1; attempt <= a->retries; attempt++) {
bool all_seen = false, agreed = true;
for (idx = 0; idx < count; idx++)
apply_duty(h, idx, duty, a->order);
for (r = 1; r <= READ_RETRIES; r++) {
all_seen = true;
for (idx = 0; idx < count; idx++) {
int rb, md;
marks[idx] = readback(h, idx, &rb, &md) ? -1 : rb;
if (marks[idx] < 0)
all_seen = false;
}
if (all_seen)
break;
retried = true;
if (r < READ_RETRIES)
printf(" Readback failed, retrying read %d/%d.\n", r + 1,
READ_RETRIES);
}
if (all_seen) {
for (idx = 1; idx < count; idx++)
if (marks[idx] != marks[0])
agreed = false;
if (agreed && duty_close(marks[0], duty))
return retried ? APPLY_RETRIED : APPLY_CLEAN;
}
if (attempt < a->retries) {
retried = true;
printf(" Setting not confirmed, retrying write %d/%d.\n",
attempt + 1, a->retries);
}
}
return APPLY_FAILED;
}
static void on_stop(int sig)
{
(void)sig;
stop_flag = 1;
}
int cmd_curve(args_t *a)
{
point_t points[MAX_POINTS];
ec_t ec;
hy_t h;
mmio_t mm;
int n, count, current = CURVE_UNSET, band = CURVE_UNSET;
struct sigaction sa;
n = load_curve(a->config, points);
printf("Curve loaded from %s.\n", a->config);
describe_curve(points, n);
printf("sensor=%s interval=%.1fs hysteresis=%dC panic=%dC\n",
sensor_name(a->sensor),
a->interval, a->hysteresis, a->panic_temp);
if (a->dry_run)
return 0;
ec_open(&ec, a->cmd_port, a->data_port, a->verbose);
h.ec = &ec;
h.gap = a->gap;
mmio_open(&mm, ERM2);
count = fan_count_or_default(&h);
if (count < 1 || count > MAX_FANS) {
mmio_close(&mm);
ec_close(&ec);
die("Fan count from 0x30 is implausible, refusing to run.");
}
memset(&sa, 0, sizeof sa);
sa.sa_handler = on_stop;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGHUP, &sa, NULL);
for (;;) {
int cpu, board, temp, want, next, fans[2], ticks, i;
bool panic;
const char *status, *mode;
char clock[16], target[8];
time_t now;
mmio_temps(&mm, &cpu, &board);
temp = sensor_pick(a->sensor, cpu, board);
next = curve_band(points, n, temp, band, a->hysteresis);
want = band_percent(points, next);
panic = temp >= a->panic_temp;
if (panic)
want = 100;
if (want != current) {
int applied = want == RELEASE_ARG ? release_to_ec(&h, count)
: apply_percent(&h, count, want, a);
if (applied != APPLY_FAILED) {
current = want;
band = next;
}
status = applied == APPLY_FAILED ? "FAILED"
: applied == APPLY_RETRIED ? "retried" : "applied";
} else {
band = next;
status = "hold";
}
mode = current == RELEASE_ARG ? "EC (auto)"
: current == CURVE_UNSET ? "unknown" : "manual";
if (want == RELEASE_ARG)
snprintf(target, sizeof target, "%4s", "--");
else
snprintf(target, sizeof target, "%3d%%", want);
mmio_fans(&mm, fans);
now = time(NULL);
strftime(clock, sizeof clock, "%H:%M:%S", localtime(&now));
if (!a->silent) {
printf("%s temp=%dC target=%s %-9s %-7s fan0=%5d fan1=%5d%s\n", clock,
temp, target, mode, status, fans[0], fans[1],
panic ? " PANIC" : "");
fflush(stdout);
}
if (a->once || stop_flag)
break;
ticks = (int)(a->interval * 10);
for (i = 0; i < ticks && !stop_flag; i++)
nsleep(0.1);
if (stop_flag)
break;
}
if (!a->once) {
hand_back(&h, count);
printf("Handed fan control back to the EC.\n");
}
mmio_close(&mm);
ec_close(&ec);
return 0;
}
+13
View File
@@ -0,0 +1,13 @@
#ifndef AFC_CURVE_H
#define AFC_CURVE_H
#include "common.h"
typedef struct {
int temp;
int percent;
} point_t;
int cmd_curve(args_t *a);
#endif
+163
View File
@@ -0,0 +1,163 @@
#define _GNU_SOURCE
#include "ec.h"
#include "common.h"
#include "util.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#if defined(__i386__) || defined(__x86_64__)
#include <sys/io.h>
#define HAVE_PORT_IO 1
#else
#define HAVE_PORT_IO 0
#endif
char ec_error[64] = "";
int ec_open(ec_t *e, unsigned cmd_port, unsigned data_port, bool verbose)
{
e->cmd_port = cmd_port;
e->data_port = data_port;
e->verbose = verbose;
e->fd = -1;
e->direct = false;
#if HAVE_PORT_IO
if (cmd_port < 0x400 && data_port < 0x400 &&
ioperm(cmd_port, 1, 1) == 0 && ioperm(data_port, 1, 1) == 0) {
e->direct = true;
return 0;
}
#endif
e->fd = open("/dev/port", O_RDWR);
if (e->fd < 0)
die("Cannot open /dev/port: %s.", strerror(errno));
return 0;
}
void ec_close(ec_t *e)
{
if (e->fd >= 0)
close(e->fd);
e->fd = -1;
}
static uint8_t ec_in8(ec_t *e, unsigned port)
{
uint8_t v;
#if HAVE_PORT_IO
if (e->direct)
return inb((unsigned short)port);
#endif
if (pread(e->fd, &v, 1, (off_t)port) != 1)
die("Cannot read port 0x%03X: %s.", port, strerror(errno));
return v;
}
static void ec_out8(ec_t *e, unsigned port, uint8_t val)
{
if (e->verbose)
printf(" out 0x%03X <- %02X\n", port, (unsigned)val);
#if HAVE_PORT_IO
if (e->direct) {
outb(val, (unsigned short)port);
return;
}
#endif
if (pwrite(e->fd, &val, 1, (off_t)port) != 1)
die("Cannot write port 0x%03X: %s.", port, strerror(errno));
}
static uint8_t ec_status(ec_t *e)
{
return ec_in8(e, e->cmd_port);
}
static int ec_timeout(const char *what)
{
snprintf(ec_error, sizeof ec_error, "%s", what);
return -1;
}
static int ec_drain(ec_t *e)
{
int i;
for (i = 0; i < POLL_LIMIT; i++) {
if (!(ec_status(e) & OBF))
return 0;
ec_in8(e, e->data_port);
nsleep(POLL_DELAY);
}
return ec_timeout("obf never cleared");
}
static int ec_wait_ibf(ec_t *e)
{
int i;
for (i = 0; i < POLL_LIMIT; i++) {
if (!(ec_status(e) & IBF))
return 0;
nsleep(POLL_DELAY);
}
return ec_timeout("ibf never cleared");
}
static int ec_wait_obf(ec_t *e)
{
int i;
for (i = 0; i < POLL_LIMIT; i++) {
if (ec_status(e) & OBF)
return 0;
nsleep(POLL_DELAY);
}
return ec_timeout("obf never set");
}
static int ec_once(ec_t *e, uint8_t cmd, const uint8_t *payload, size_t n,
bool want_result, uint8_t *out)
{
size_t i;
if (ec_drain(e) || ec_wait_ibf(e))
return -1;
ec_out8(e, e->cmd_port, PREAMBLE);
if (ec_wait_ibf(e))
return -1;
ec_out8(e, e->cmd_port, cmd);
for (i = 0; i < n; i++) {
if (ec_wait_ibf(e))
return -1;
ec_out8(e, e->data_port, payload[i]);
}
if (ec_wait_ibf(e))
return -1;
if (!want_result)
return 0;
if (ec_wait_obf(e))
return -1;
if (out)
*out = ec_in8(e, e->data_port);
return 0;
}
int ec_xact(ec_t *e, uint8_t cmd, const uint8_t *payload, size_t n,
bool want_result, uint8_t *out)
{
int i;
if (n > 8)
die("Payload limit is 8 bytes.");
for (i = 0; i < RETRIES; i++)
if (ec_once(e, cmd, payload, n, want_result, out) == 0)
return 0;
return -1;
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef AFC_EC_H
#define AFC_EC_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
typedef struct {
int fd;
bool direct;
unsigned cmd_port;
unsigned data_port;
bool verbose;
} ec_t;
extern char ec_error[64];
int ec_open(ec_t *e, unsigned cmd_port, unsigned data_port, bool verbose);
void ec_close(ec_t *e);
int ec_xact(ec_t *e, uint8_t cmd, const uint8_t *payload, size_t n,
bool want_result, uint8_t *out);
#endif
+109
View File
@@ -0,0 +1,109 @@
#define _GNU_SOURCE
#include "fan.h"
#include "common.h"
#include "util.h"
#include <stdlib.h>
int percent_to_duty(int percent)
{
return (int)(percent * 255 / 100.0 + 0.5);
}
int duty_to_percent(int duty)
{
return (int)(duty * 100 / 255.0 + 0.5);
}
bool duty_close(int readback_value, int want)
{
int slack = want * TOL_PCT / 100;
if (slack < TOL_MIN)
slack = TOL_MIN;
return abs(readback_value - want) <= slack;
}
const char *mode_name(int mode)
{
if (mode < 0)
return "unreadable";
return mode ? "Manual" : "EC automatic";
}
int fan_count_or_default(hy_t *h)
{
uint8_t n;
if (hy_read(h, REG_FAN_COUNT, &n))
return 0;
return (n >= 1 && n <= MAX_FANS) ? n : 0;
}
int apply_duty(hy_t *h, int index, int duty, int order)
{
if (hy_select(h, index))
return -1;
if (order == ORDER_MODE_FIRST) {
if (hy_write(h, REG_TEST_MODE, 1))
return -1;
if (hy_select(h, index))
return -1;
if (hy_write(h, REG_PWM_DUTY, (uint8_t)duty))
return -1;
} else {
if (hy_write(h, REG_PWM_DUTY, (uint8_t)duty))
return -1;
if (hy_write(h, REG_TEST_MODE, 1))
return -1;
}
return 0;
}
int readback(hy_t *h, int index, int *duty, int *mode)
{
uint8_t d, m;
if (hy_select(h, index) || hy_read(h, REG_PWM_DUTY, &d) ||
hy_read(h, REG_TEST_MODE, &m))
return -1;
*duty = d;
*mode = m;
return 0;
}
void hand_back(hy_t *h, int count)
{
int idx;
for (idx = 0; idx < count; idx++) {
if (hy_select(h, idx))
continue;
hy_write(h, REG_TEST_MODE, 0);
}
}
int still_manual(hy_t *h, int count, int *left)
{
int idx, nleft = 0;
for (idx = 0; idx < count; idx++) {
int rb, md;
if (readback(h, idx, &rb, &md) == 0 && md)
left[nleft++] = idx;
}
return nleft;
}
int release_to_ec(hy_t *h, int count)
{
int left[MAX_FANS];
hand_back(h, count);
if (!still_manual(h, count, left))
return APPLY_CLEAN;
hand_back(h, count);
return still_manual(h, count, left) ? APPLY_FAILED : APPLY_RETRIED;
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef AFC_FAN_H
#define AFC_FAN_H
#include "healthy.h"
#include <stdbool.h>
int percent_to_duty(int percent);
int duty_to_percent(int duty);
bool duty_close(int readback_value, int want);
const char *mode_name(int mode);
int fan_count_or_default(hy_t *h);
int apply_duty(hy_t *h, int index, int duty, int order);
int readback(hy_t *h, int index, int *duty, int *mode);
void hand_back(hy_t *h, int count);
int still_manual(hy_t *h, int count, int *left);
int release_to_ec(hy_t *h, int count);
#endif
+45
View File
@@ -0,0 +1,45 @@
#define _GNU_SOURCE
#include "healthy.h"
#include "common.h"
#include "util.h"
int hy_version(hy_t *h, uint8_t *out)
{
uint8_t payload[1] = { 0x50 };
return ec_xact(h->ec, CMD_VERSION, payload, 1, true, out);
}
int hy_read(hy_t *h, uint8_t reg, uint8_t *out)
{
uint8_t payload[3] = { TBL_READ, reg, 0x00 };
return ec_xact(h->ec, CMD_TABLE, payload, 3, true, out);
}
int hy_write(hy_t *h, uint8_t reg, uint8_t value)
{
uint8_t payload[3] = { TBL_WRITE, reg, value };
if (ec_xact(h->ec, CMD_TABLE, payload, 3, false, NULL))
return -1;
nsleep(h->gap);
return 0;
}
int hy_select(hy_t *h, int index)
{
return hy_write(h, REG_FAN_INDEX, (uint8_t)index);
}
int hy_rpm(hy_t *h, int *out)
{
uint8_t hi, lo;
if (hy_read(h, REG_RPM_HI, &hi) || hy_read(h, REG_RPM_LO, &lo))
return -1;
*out = (hi << 8) | lo;
return 0;
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef AFC_HEALTHY_H
#define AFC_HEALTHY_H
#include "ec.h"
#include <stdint.h>
typedef struct {
ec_t *ec;
double gap;
} hy_t;
int hy_version(hy_t *h, uint8_t *out);
int hy_read(hy_t *h, uint8_t reg, uint8_t *out);
int hy_write(hy_t *h, uint8_t reg, uint8_t value);
int hy_select(hy_t *h, int index);
int hy_rpm(hy_t *h, int *out);
#endif
+247
View File
@@ -0,0 +1,247 @@
#define _GNU_SOURCE
#include "commands.h"
#include "common.h"
#include "curve.h"
#include "util.h"
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static void need_root(void)
{
if (geteuid() != 0)
die("Root privileges required.");
}
static const char INT_MSG[] =
"\nInterrupted. Fans keep the last setting, use 'set -1' to hand control "
"back to the EC.\n";
static void on_interrupt(int sig)
{
(void)sig;
if (write(STDOUT_FILENO, INT_MSG, sizeof INT_MSG - 1) < 0) {
}
_exit(130);
}
static void usage_text(FILE *out)
{
fprintf(out,
"usage: " APP_NAME " [global options] <command> [options]\n"
"\n"
"global options:\n"
" --cmd-port N --data-port N --gap SECONDS --verbose\n"
"\n"
"commands:\n"
" set DUTY [--fan N] [--retries N] [--no-verify]\n"
" [--order mode-first|duty-first]\n"
" duty 0-255, or -1 to hand control back to the EC\n"
" -1 always covers every fan, 0x31 is global\n"
" setp PERCENT [same options as set], or -1 for the same release\n"
" curve [--config PATH] [--interval S] [--hysteresis C]\n"
" [--panic-temp C] [--sensor cpu|board|max] [--retries N]\n"
" [--order ORDER] [--once] [--dry-run] [--silent]\n"
" config lines are 'percent,temp'; percent -1 hands that\n"
" band back to the EC\n"
" fan-speed\n"
" fan-info\n"
" temps-info\n"
" help\n"
" version\n");
}
static void usage(void)
{
usage_text(stderr);
exit(2);
}
static int cmd_help(void)
{
usage_text(stdout);
return 0;
}
static const char *need_value(int argc, char **argv, int *i)
{
if (*i + 1 >= argc)
die("%s requires a value.", argv[*i]);
return argv[++(*i)];
}
static long int_auto(const char *s, const char *what)
{
char *end;
long v;
errno = 0;
v = strtol(s, &end, 0);
if (errno || end == s || *end)
die("Invalid %s: %s.", what, s);
return v;
}
static double dbl_arg(const char *s, const char *what)
{
char *end;
double v;
errno = 0;
v = strtod(s, &end);
if (errno || end == s || *end)
die("invalid %s: %s", what, s);
return v;
}
static int pick(const char *value, const char *what, const char *const *names,
int n)
{
int i;
for (i = 0; i < n; i++)
if (strcmp(value, names[i]) == 0)
return i;
die("Invalid %s: %s.", what, value);
}
static bool global_option(args_t *a, int argc, char **argv, int *i)
{
const char *arg = argv[*i];
if (strcmp(arg, "--cmd-port") == 0)
a->cmd_port = (unsigned)int_auto(need_value(argc, argv, i), "--cmd-port");
else if (strcmp(arg, "--data-port") == 0)
a->data_port = (unsigned)int_auto(need_value(argc, argv, i), "--data-port");
else if (strcmp(arg, "--gap") == 0)
a->gap = dbl_arg(need_value(argc, argv, i), "--gap");
else if (strcmp(arg, "--verbose") == 0)
a->verbose = true;
else
return false;
return true;
}
int main(int argc, char **argv)
{
static const char *const orders[] = { "mode-first", "duty-first" };
static const char *const sensors[] = { "cpu", "board", "max" };
args_t a;
struct sigaction sa;
const char *cmd = NULL;
bool have_duty = false;
int i;
for (i = 1; i < argc; i++)
if (strcmp(argv[i], "help") == 0 || strcmp(argv[i], "--help") == 0 ||
strcmp(argv[i], "-h") == 0)
return cmd_help();
memset(&a, 0, sizeof a);
a.cmd_port = CMD_PORT;
a.data_port = DATA_PORT;
a.gap = IO_GAP;
a.index = -1;
a.retries = 3;
a.order = ORDER_MODE_FIRST;
a.config = DEFAULT_CONFIG;
a.interval = INTERVAL;
a.hysteresis = HYSTERESIS;
a.panic_temp = PANIC_TEMP;
a.sensor = SENSOR_MAX;
i = 1;
while (i < argc && argv[i][0] == '-' && argv[i][1]) {
if (!global_option(&a, argc, argv, &i))
usage();
i++;
}
if (i >= argc)
usage();
cmd = argv[i++];
if (strcmp(cmd, "version") != 0)
need_root();
for (; i < argc; i++) {
const char *arg = argv[i];
if (global_option(&a, argc, argv, &i))
continue;
if (arg[0] != '-' || isdigit((unsigned char)arg[1])) {
if (strcmp(cmd, "set") == 0 && !have_duty) {
a.duty = (int)int_auto(arg, "duty");
have_duty = true;
} else if (strcmp(cmd, "setp") == 0 && !have_duty) {
a.percent = (int)int_auto(arg, "percent");
have_duty = true;
} else {
usage();
}
continue;
}
if (strcmp(arg, "--fan") == 0)
a.index = (int)int_auto(need_value(argc, argv, &i), "--fan");
else if (strcmp(arg, "--retries") == 0)
a.retries = (int)int_auto(need_value(argc, argv, &i), "--retries");
else if (strcmp(arg, "--no-verify") == 0)
a.no_verify = true;
else if (strcmp(arg, "--order") == 0)
a.order = pick(need_value(argc, argv, &i), "--order", orders, 2);
else if (strcmp(arg, "--sensor") == 0)
a.sensor = pick(need_value(argc, argv, &i), "--sensor", sensors, 3);
else if (strcmp(arg, "--config") == 0)
a.config = need_value(argc, argv, &i);
else if (strcmp(arg, "--interval") == 0)
a.interval = dbl_arg(need_value(argc, argv, &i), "--interval");
else if (strcmp(arg, "--hysteresis") == 0)
a.hysteresis = (int)int_auto(need_value(argc, argv, &i), "--hysteresis");
else if (strcmp(arg, "--panic-temp") == 0)
a.panic_temp = (int)int_auto(need_value(argc, argv, &i), "--panic-temp");
else if (strcmp(arg, "--once") == 0)
a.once = true;
else if (strcmp(arg, "--dry-run") == 0)
a.dry_run = true;
else if (strcmp(arg, "--silent") == 0)
a.silent = true;
else {
usage();
}
}
if (strcmp(cmd, "set") == 0 && !have_duty)
die("set requires a duty value.");
if (strcmp(cmd, "setp") == 0 && !have_duty)
die("setp requires a percent value.");
if (a.index >= MAX_FANS)
die("--fan must be 0..%d.", MAX_FANS - 1);
if (a.retries < 1)
die("--retries must be at least 1.");
memset(&sa, 0, sizeof sa);
sa.sa_handler = on_interrupt;
sigaction(SIGINT, &sa, NULL);
if (strcmp(cmd, "version") == 0)
return cmd_version(&a);
if (strcmp(cmd, "fan-info") == 0)
return cmd_fan_info(&a);
if (strcmp(cmd, "temps-info") == 0)
return cmd_temps_info(&a);
if (strcmp(cmd, "fan-speed") == 0)
return cmd_fan_speed(&a);
if (strcmp(cmd, "set") == 0)
return cmd_set(&a);
if (strcmp(cmd, "setp") == 0)
return cmd_setp(&a);
if (strcmp(cmd, "curve") == 0)
return cmd_curve(&a);
usage();
return 2;
}
+86
View File
@@ -0,0 +1,86 @@
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include "mmio.h"
#include "common.h"
#include "util.h"
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
void mmio_open(mmio_t *m, unsigned long base)
{
void *p;
m->fd = open("/dev/mem", O_RDONLY | O_SYNC);
if (m->fd < 0)
die("Cannot open /dev/mem: %s.", strerror(errno));
m->page = base & PAGE_MASK;
m->off = base - m->page;
p = mmap(NULL, 0x1000, PROT_READ, MAP_SHARED, m->fd, (off_t)m->page);
if (p == MAP_FAILED)
die("Cannot map 0x%lX: %s.", m->page, strerror(errno));
m->map = p;
}
void mmio_close(mmio_t *m)
{
if (m->map)
munmap((void *)m->map, 0x1000);
if (m->fd >= 0)
close(m->fd);
m->map = NULL;
m->fd = -1;
}
int mmio_be16(mmio_t *m, unsigned long offset)
{
unsigned long i = m->off + offset;
return (m->map[i] << 8) | m->map[i + 1];
}
void mmio_fans(mmio_t *m, int fans[2])
{
fans[0] = mmio_be16(m, TACH_OFFSET);
fans[1] = mmio_be16(m, TACH_OFFSET + 2);
}
int mmio_at(mmio_t *m, unsigned long address)
{
return m->map[address - m->page];
}
void mmio_temps(mmio_t *m, int *cpu, int *board)
{
*cpu = mmio_at(m, CTMP);
*board = mmio_at(m, CLOT);
}
const char *sensor_name(int sensor)
{
switch (sensor) {
case SENSOR_CPU:
return "cpu";
case SENSOR_BOARD:
return "board";
default:
return "max";
}
}
int sensor_pick(int sensor, int cpu, int board)
{
switch (sensor) {
case SENSOR_CPU:
return cpu;
case SENSOR_BOARD:
return board;
default:
return imax(cpu, board);
}
}
+20
View File
@@ -0,0 +1,20 @@
#ifndef AFC_MMIO_H
#define AFC_MMIO_H
typedef struct {
int fd;
volatile unsigned char *map;
unsigned long page;
unsigned long off;
} mmio_t;
void mmio_open(mmio_t *m, unsigned long base);
void mmio_close(mmio_t *m);
int mmio_be16(mmio_t *m, unsigned long offset);
int mmio_at(mmio_t *m, unsigned long address);
void mmio_fans(mmio_t *m, int fans[2]);
void mmio_temps(mmio_t *m, int *cpu, int *board);
const char *sensor_name(int sensor);
int sensor_pick(int sensor, int cpu, int board);
#endif
+62
View File
@@ -0,0 +1,62 @@
#define _GNU_SOURCE
#include "util.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
exit(1);
}
void nsleep(double seconds)
{
struct timespec ts;
if (seconds <= 0.0)
return;
ts.tv_sec = (time_t)seconds;
ts.tv_nsec = (long)((seconds - (double)ts.tv_sec) * 1e9);
if (ts.tv_nsec < 0)
ts.tv_nsec = 0;
if (ts.tv_nsec > 999999999L)
ts.tv_nsec = 999999999L;
nanosleep(&ts, NULL);
}
bool read_line_file(const char *path, char *buf, size_t size)
{
FILE *f = fopen(path, "r");
size_t len;
if (!f)
return false;
if (!fgets(buf, (int)size, f)) {
fclose(f);
return false;
}
fclose(f);
len = strlen(buf);
while (len && (buf[len - 1] == '\n' || buf[len - 1] == '\r'))
buf[--len] = '\0';
return len > 0;
}
void join_ints(char *buf, size_t size, const int *v, int n)
{
int i;
size_t used = 0;
buf[0] = '\0';
for (i = 0; i < n && used + 8 < size; i++)
used += (size_t)snprintf(buf + used, size - used, "%s%d", i ? " " : "", v[i]);
}
+15
View File
@@ -0,0 +1,15 @@
#ifndef AFC_UTIL_H
#define AFC_UTIL_H
#include <stdbool.h>
#include <stddef.h>
void die(const char *fmt, ...) __attribute__((noreturn, format(printf, 1, 2)));
void nsleep(double seconds);
bool read_line_file(const char *path, char *buf, size_t size);
void join_ints(char *buf, size_t size, const int *v, int n);
static inline int imin(int a, int b) { return a < b ? a : b; }
static inline int imax(int a, int b) { return a > b ? a : b; }
#endif