Publish Platina Linux source base for Xiaomi Mi 8 Lite

This commit is contained in:
Sukecz
2026-10-23 11:10:29 +02:00
commit b7eb4289b7
95 changed files with 275710 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
* text=auto eol=lf
*.patch -text -whitespace
+20
View File
@@ -0,0 +1,20 @@
name: Offline project checks
on:
push:
pull_request:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: check-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- name: Validate sources and run offline tests
run: make check
+29
View File
@@ -0,0 +1,29 @@
# Private inputs and generated outputs stay local.
/config/
/backups/
/artifacts/
/work/
/sources/
/tools/
/logs/
/reports/
/archive/
**/AGENTS.md
**/AGENTS.*
**/*private*
**/*secret*
*.txt
*.key
*.pem
*.env
.env*
*.img
*.apk
*.elf
*.bin
*.zip
*.tar.gz
*.nmconnection
!ports/**/platina-usb.nmconnection
**/__pycache__/
*.py[cod]
+18
View File
@@ -0,0 +1,18 @@
# Changelog
## Unreleased — integrated display candidate
- Kernel 7.2.12-r1 adds the Platina Tianma NT36672A panel to the normal driver and device tree.
- Full kernel and module build passed; the existing-installation boot candidate passed offline checks.
- Added display on/off/brightness/status, timed images and host-side image preparation.
- Panel activation, repeated power cycles and power use still require physical testing.
## 0.1.1 — verified integration
- Boot into headless postmarketOS from eMMC with SSH over Wi-Fi or USB networking.
- Key-only SSH, disabled root/password login, NetworkManager reconnect and OpenRC autostart.
- Corrected initramfs module indexes and verified normal restarts.
- Displayed the Platina logo for seven seconds using an explicitly loaded temporary LCD helper.
- Automatic logo and backlight shutdown were physically confirmed on a Tianma Mi 8 Lite.
The integration version is separate from the kernel and distribution versions.
+24
View File
@@ -0,0 +1,24 @@
# Contributing
Start with the [feature status](README.md#feature-status), [build guide](docs/BUILDING.md)
and [hardware notes](docs/HARDWARE.md). Keep changes small and include the affected
phone model, panel variant, kernel version and the result you actually tested.
Edit recipes in `ports/candidate/`, update the matching SHA512 entries and package
revision, and keep `project/sources.lock.json` consistent. Do not edit generated
checkout files as the only source of a change. Run `make check` before submitting.
For hardware changes, distinguish a successful build from a real phone test.
Use 🟢 for physically verified functionality, 🟠 for partial support or work awaiting
hardware testing, and 🔴 for known non-working or unsupported functionality. Update
the README status table and date when evidence changes. Never promote a driver to
working simply because it exists in the kernel configuration.
Submit device logs after removing credentials, device identifiers, public keys,
local addresses and personal paths. Never commit firmware blobs, phone backups,
private configuration, generated images or agent instructions.
Original contributions are GPL-2.0-only unless a file states another applicable
license. Preserve third-party copyrights, SPDX identifiers and license notices;
see [licensing](docs/LICENSING.md). A pull request does not authorize flashing
someone else's device or changing their network.
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 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 licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey 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 2 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 is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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 Library General
Public License instead of this License.
+24
View File
@@ -0,0 +1,24 @@
Copyright (c) <year> <owner> . All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://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 <http://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:
{project} Copyright (C) {year} {fullname}
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
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright holders are identified in NOTICE and the original source files.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+28
View File
@@ -0,0 +1,28 @@
.PHONY: help check test doctor prepare sync kernel images verify audit version splash
PROFILE ?= candidate
OUTPUT ?= candidate-$(shell date +%Y%m%d-%H%M%S)
help:
@./scripts/project --help
check:
@./scripts/project check
@python3 scripts/check-public-tree.py
test:
@python3 -m unittest discover -s tests -v
doctor:
@./scripts/project doctor
prepare:
@./scripts/project prepare --profile "$(PROFILE)"
sync:
@./scripts/project sync --profile "$(PROFILE)"
kernel:
@./scripts/project kernel --profile "$(PROFILE)"
images:
@./scripts/project images --output "$(OUTPUT)"
verify:
@./scripts/project verify "$(DIR)"
audit:
@./scripts/project audit "$(DIR)"
version:
@./scripts/platina-release.py show
splash:
@./scripts/platina-release.py build
+56
View File
@@ -0,0 +1,56 @@
Platina Linux — Xiaomi Mi 8 Lite / platina
Original Platina integration code, documentation and artwork:
Copyright (C) 2026 Sukecz and Platina contributors.
Licensed GPL-2.0-only unless a file or the following notice specifies otherwise.
The original Platina logo is supplied under the same project license; the name
and logo do not imply endorsement by Xiaomi, Qualcomm, Alpine or postmarketOS.
This repository contains an aggregate of independently licensed components.
The top-level license does not relicense third-party source or firmware.
Linux / SDM660 kernel changes and configuration
- Linux contributors and the authors identified in patch headers/source files.
- https://github.com/sdm660-mainline/linux
- GPL-2.0-only for the kernel as a whole. Preserve per-file SPDX notices, including
GPL-2.0-or-later and compatible dual-license options where present.
- Linux stable incremental patches originate from kernel.org.
Community Xiaomi Mi 8 Lite port
- Cesar Tamayo / macosmojave2-alt and credited patch authors.
- https://github.com/macosmojave2-alt/postmarket-mi8lite-platina
- Device package data declares MIT; kernel additions declare the applicable GPL
licenses. Original maintainer names, copyrights and patch notices are retained.
- No assumption is made that the community repository has one blanket license.
- Its firmware board-index helper is not redistributed: the public helper and
firmware packaging recipe were written for this repository.
postmarketOS packaging / pmaports
- postmarketOS contributors; package maintainers remain credited in APKBUILD.
- https://gitlab.postmarketos.org/postmarketOS/pmaports
- Packaging material inherited from pmaports retains GPLv3, subject to
explicit per-file/package-data notices. The kernel APKBUILD's license field
describes the resulting kernel package, not a relicensing of its build recipe.
- GPLv3 packaging and GPLv2 kernel patches are independent works in an aggregate.
Tianma panel reference
- Xiaomi / The Linux Foundation / authors of MiCode platina-o-oss.
- https://github.com/MiCode/Xiaomi_Kernel_OpenSource/tree/0bb2780bccb9c7e05f0edf5db8860e779179b5f9
- GPL-2.0-only downstream panel data, with variant values recorded from matching
stock panel data. Exact reference hashes are in tianma-reference.json.
External dependencies
- pmbootstrap (GPLv3), the full kernel and distro packages are fetched
from pinned upstream sources during preparation/build. Their original notices
and distribution obligations remain applicable; their source trees are not
vendored here. Python/Pillow and other host tools keep their own licenses.
Firmware
- No GPU, Wi-Fi, modem or calibration binaries are included.
- The firmware APK's license=proprietary describes user-supplied firmware payloads.
It does not restrict the GPL-2.0-only recipe/helper source written here.
- No redistribution permission for those payloads is granted by this repository.
License texts: LICENSE (GPLv2), LICENSES/GPL-3.0, LICENSES/MIT and
LICENSES/BSD-2-Clause. Upstream copyright and license notices take precedence
for inherited material. See docs/LICENSING.md for scope and source links.
+128
View File
@@ -0,0 +1,128 @@
<p align="center">
<img src="project/branding/platina-linux-logo.png" alt="Platina Linux — Xiaomi Mi 8 Lite headless Linux server" width="300" />
</p>
# Platina Linux for Xiaomi Mi 8 Lite
Turn a **Xiaomi Mi 8 Lite (platina, M1808D2TG, Qualcomm Snapdragon 660 / SDM660)**
into a small **headless Linux server** with Wi-Fi, USB networking and SSH.
Platina Linux is a device integration built on **postmarketOS and Alpine Linux**,
using the SDM660 mainline-oriented kernel port. It boots Linux directly from eMMC;
this is not Android, a container inside Android, or a desktop phone OS.
[![Source checks](https://github.com/Sukecz/platina-linux/actions/workflows/check.yml/badge.svg)](https://github.com/Sukecz/platina-linux/actions/workflows/check.yml)
[![License: GPL v2](https://img.shields.io/badge/License-GPL_v2-blue.svg)](LICENSE)
[![Device: Xiaomi Mi 8 Lite](https://img.shields.io/badge/device-Xiaomi_Mi_8_Lite-ff6900)](docs/HARDWARE.md)
**Verified integration: 0.1.1** · **Kernel: 7.2.12-sdm660** · **Development / early hardware testing**
[Installation](docs/INSTALLATION.md) · [Build from source](docs/BUILDING.md)
· [Display development](docs/DISPLAY.md) · [Changelog](CHANGELOG.md) · [Licensing](docs/LICENSING.md)
## What it does
- **Real Linux on the phone:** an ARM64 Alpine userspace, package manager and OpenRC services.
- **Remote administration:** key-only OpenSSH over Wi-Fi or the USB network gadget,
with root login and SSH password login disabled.
- **Reconnect automatically:** NetworkManager restores the configured Wi-Fi connection;
USB networking provides a separate local administration path.
- **Headless by default:** keep the backlight dark while running background services.
- **Battery and charger operation:** use Wi-Fi while running on the battery or a separate charger.
- **A useful display foundation:** the existing logo works with a temporary helper;
the integrated Tianma driver and commands for brightness, power and custom images
are prepared for their next hardware test.
- **Repeatable development:** pinned source revisions, versioned recipes, checksum
verification, offline tests and separate build/export/audit steps.
The goal is a practical always-on server. **Long-term 24/7 stability and sustained
power balance have not yet been qualified.** Existing phone components keep their
own support limits; this project does not claim full smartphone functionality.
## Feature status
**Last reviewed: 2026-10-23.** Status describes tests on the maintainer's Mi 8 Lite,
not a guarantee for every device or panel variant.
🟢 **Verified** · 🟠 **Partial / prepared / awaiting hardware testing** · 🔴 **Not working / unsupported**
| Feature | Status | What has been verified |
|---|:---:|---|
| Linux boot from internal eMMC | 🟢 | Installed system, normal startup and repeated restarts |
| ARM64 userspace and OpenRC | 🟢 | postmarketOS v26.06 / Alpine; services start after boot |
| SSH over Wi-Fi | 🟢 | Direct LAN login with an administrator key |
| SSH over USB networking | 🟢 | USB gadget administration on a Linux host |
| SSH authentication hardening | 🟢 | Password and root SSH login disabled; administrator uses sudo |
| Wi-Fi reconnect | 🟢 | Reconnect after radio recovery; network configuration persists |
| USB network recovery | 🟢 | Software disconnect/reconnect and address recovery |
| mDNS hostname | 🟢 | `platina.local` on a compatible local network |
| eMMC / ext4 storage | 🟢 | Read/write root filesystem and offline image checks |
| Battery operation | 🟢 | Wi-Fi administration with data USB physically disconnected |
| Separate charger operation | 🟢 | Operation and charging confirmed with a suitable charger/cable |
| Battery / thermal telemetry | 🟢 | Battery information and CPU, GPU and battery temperature readings |
| Short boot logo | 🟢 | Logo and subsequent backlight shutdown physically confirmed in 0.1.1 |
| Integrated Tianma NT36672A panel driver | 🟠 | Kernel 7.2.12-r1 built; boot/module candidate audited offline, not yet boot-tested |
| Display power, brightness and custom images | 🟠 | Control tools and image conversion tested offline; panel power cycles await hardware test |
| Beszel monitoring | 🟠 | Native monitoring tested separately; optional custom hub/power-chart integration is outside this source base |
| VPN access from outside the home network | 🟠 | A LAN jump-host route was tested; a real off-site client test is pending |
| Continuous 48–72-hour uptime | 🟠 | Qualification is pending; shorter successful tests are not a soak test |
| Sustained charging / wall power use | 🟠 | Short charger tests passed; long-term balance and wall-meter measurements are pending |
| CPU frequency scaling | 🟠 | Port/platform limitation; no supported full scaling claim |
| Audio, Bluetooth, camera and SD card | 🟠 | Not functionally qualified by this project |
| Touchscreen on the tested device | 🔴 | Controller initialization fails; headless administration is unaffected |
| Mobile calls / mobile data | 🔴 | Outside the supported headless-server feature set |
| Android apps / Android services | 🔴 | This system replaces the running Android environment |
| Other Xiaomi Mi 8 models / other phones | 🔴 | This port targets **Mi 8 Lite / platina only** |
The checked-in candidate sources are **kernel 7.2.12-r1 + device 5-r31**. They include
the new display work; **they are not the same as the physically verified 0.1.1
installation**. The public firmware recipe is 2-r5, with a newly written packaging
helper; proprietary firmware payloads are supplied locally by each builder.
No prebuilt installation images or binary firmware are published here.
## Hardware
**Tested:** Xiaomi Mi 8 Lite, model **M1808D2TG**, codename **platina**, Snapdragon 660,
4 GB RAM / 64 GB eMMC, **Tianma NT36672A 1080 × 2280 LCD**.
Other RAM/storage variants and BOE panel variants are not qualified. Check the
codename and actual panel before using the display candidate. The Mi 8, Mi 8 SE,
Mi 8 Pro and Mi 8 Lite are different devices.
## Getting started
You need an unlocked bootloader, a Linux build host, your own SSH public key,
matching stock firmware inputs and a recovery plan. **Initial installation erases
Android user data.** Follow the [installation guide](docs/INSTALLATION.md), including
its backup, device identification and RAM-test stages before a permanent flash.
```sh
git clone https://github.com/Sukecz/platina-linux.git
cd platina-linux
make doctor
make check
```
The public tree contains the current port recipes, build and audit tools,
display sources, regression tests and documentation. Configuration, firmware,
phone backups and generated images remain local.
## Updating this project
The table above is maintained alongside code changes. A successful compilation
means **built**, an offline audit means **audited**, and a physical phone test means
**hardware verified**. These states are recorded separately.
Platina's integration version lives in `project/release.json`; it is independent
of the Linux and Alpine version numbers. The integrated display candidate will
become a new integration version only after installation and hardware validation.
## Credits and license
Built on [postmarketOS](https://postmarketos.org/), [Alpine Linux](https://alpinelinux.org/),
[SDM660 mainline](https://github.com/sdm660-mainline/linux) and the
[community Mi 8 Lite port](https://github.com/macosmojave2-alt/postmarket-mi8lite-platina).
The panel sequence is based on Xiaomi's published kernel sources and matching
stock panel data. Original authors and source notices are retained.
**Original Platina contributions: GPL-2.0-only.** Third-party code retains its
own licenses; firmware remains proprietary and is not included. See
[LICENSE](LICENSE), [NOTICE](NOTICE) and the [licensing notes](docs/LICENSING.md).
+108
View File
@@ -0,0 +1,108 @@
# Building Platina Linux
This is a source-only development port. The candidate kernel builds, but the new
integrated Tianma display still needs its first successful physical boot test.
An image built here is a candidate, not a ready-made stable release.
## Build host
Use Linux, Python 3.11+, Git, Make, a POSIX shell and sudo. The build creates
pmbootstrap chroots and needs Internet access, substantial disk space and time.
It uses two jobs at nice level 10. No host services or phones are restarted.
On Debian/Ubuntu, typical host tools are:
```sh
sudo apt install git python3 make sudo openssh-client e2fsprogs util-linux kmod mtools fastboot
# Optional: only needed for make splash / custom image conversion.
sudo apt install python3-pil fonts-dejavu-core
```
`make doctor` reports missing core tools without installing them. Kernel compilers
and package dependencies are installed inside the build chroots by pmbootstrap.
Python's standard library is enough for the basic offline test suite; image
conversion uses Pillow on the build host.
## Personal build inputs
```sh
mkdir -p config
cp /PATH/TO/YOUR/ADMINISTRATOR-KEY.pub config/admin-builder.pub
```
Use a dedicated key if appropriate. Only its **public** half enters the image.
The user account is `server`, with passwordless sudo for administration. Password
and root SSH login are disabled. Keep the private key outside this repository.
Firmware is not distributed here. From a legally obtained matching stock ROM,
extract `images/NON-HLOS.bin` without running any ROM scripts, and obtain the
matching `a512_zap.elf` GPU firmware from your own vendor firmware. The pinned
reference is the Mi 8 Lite global stock firmware V12.0.3.0.QDTMIXM; other inputs
are rejected if their hashes differ.
The recipe expects three local inputs: `a512_zap.elf`,
`firmware-xiaomi-platina-bdwlan.tar.gz` and `firmware-xiaomi-platina-modem.tar.gz`.
The helper reads the FAT firmware image with mtools, creates deterministic
archives and checks all three against the recipe before writing them:
```sh
python3 scripts/prepare-firmware.py \
--modem-image /PATH/TO/NON-HLOS.bin \
--gpu-firmware /PATH/TO/a512_zap.elf
```
The output is `config/firmware/`, which is ignored by Git. Missing matching
firmware is a build prerequisite; this repository does not silently substitute
another phone's calibration, modem firmware or administrator key.
## Prepare and compile
```sh
make check
./scripts/project prepare --profile candidate --fetch
make kernel PROFILE=candidate
make images OUTPUT=candidate-local
make verify DIR=artifacts/candidate-local
make audit DIR=artifacts/candidate-local
```
Preparation pins pmbootstrap, pmaports and its channel table from
`project/sources.lock.json`. It creates a new managed checkout and refuses to
overwrite one. After changing a versioned recipe, run `make sync` before rebuilding.
Checksum checks parse APKBUILD as text rather than executing its shell on the host.
The image contains the public key and proprietary firmware you provided. It is
therefore **your local installation image**, not automatically a public artifact.
The builder stops pmbootstrap mounts before copying/hashing filesystem images.
Source revisions are pinned, but external Alpine repositories/toolchain packages
are not fully frozen; bit-for-bit reproducible full builds are not promised.
## Scope initramfs module indexes
The mkinitfs version used by this port can copy full-rootfs module indexes into
an initramfs containing only some modules. Before booting or flashing, regenerate
indexes for the modules that are actually included:
```sh
python3 scripts/scope-initramfs-modules.py artifacts/candidate-local/boot.img \
--release 7.2.12-sdm660 --output artifacts/candidate-local-scoped
make verify DIR=artifacts/candidate-local-scoped
```
Use **candidate-local-scoped/boot.img** with **candidate-local/xiaomi-platina.img**.
The scoping tool preserves the kernel, DTB and rootfs command line; it does not
create a second root filesystem and does not flash anything.
Exported files include boot.img, xiaomi-platina.img, initramfs, kernel and DTB.
Keep the manifest and corresponding APKs for your own rollback records.
## Optional display assets
```sh
make splash
python3 scripts/prepare-display-frame.py your-image.png --output artifacts/custom-frame
```
The original logo is preserved; the integration version is added during rendering.
These commands create local bundles. `make images` does not yet install the
versioned splash bundle automatically; see [display setup](DISPLAY.md).
+88
View File
@@ -0,0 +1,88 @@
# Platina display support
The tested Mi 8 Lite has a **Tianma NT36672A 1080 × 2280** panel. Display support
has two separate states:
| State | Status |
|---|---|
| Integration 0.1.1 logo with a temporary LCD power/wake helper | 🟢 Physically verified, including automatic start and subsequent backlight shutdown |
| Integrated driver / DT in kernel 7.2.12-r1 | 🟠 Compiled and audited offline; physical boot and power cycles pending |
The candidate is in `ports/candidate/linux-postmarketos-qcom-sdm660/0030-platina-tianma-panel.patch`.
It adds the panel-specific command sequence, correct regulator names, reset timing,
DT binding and initialization-error cleanup to the NT36672A driver. The stock
command sequence is recorded in `project/display/tianma-reference.json` and
compared by offline tests. This is not a verified BOE TD4320 configuration.
## Optional controller setup
After testing a successful boot with the integrated driver, install the renderer
and controller on **your phone**. The files listed below are source files from
this repository; transfer them using your own authenticated SSH connection.
```sh
# On the phone, from the directory to which you transferred these scripts:
sudo install -m755 phone-splash.py /usr/local/sbin/platina-splash
sudo install -m755 phone-display.py /usr/local/sbin/platina-display
```
For the logo, run `make splash` on the build host. Transfer its three runtime files
`release.json`, `version` and `frame.bgrx.gz` from `artifacts/platina-linux-0.1.1/`
into a new phone directory `/usr/local/share/platina/releases/0.1.1/`, then create
`/usr/local/share/platina/current` pointing to `releases/0.1.1`. If updating an
existing setup, back up its assets/hook first and use a new versioned directory.
The phone renderer uses Python's standard library, without Pillow or a desktop.
```sh
sudo platina-display status
sudo platina-display on --brightness 25
sudo platina-display brightness --brightness 10
sudo platina-display off
sudo platina-display show --seconds 7
sudo platina-display show --directory /PATH/TO/CUSTOM-FRAME --seconds 60
```
`status` only reads sysfs. Changes require root and the actual bound Tianma driver;
the tool refuses the old panel-simple driver or a simultaneously loaded temporary
DCS helper. `on` keeps the current framebuffer visible until `off` is requested;
it may show the console. `show` is bounded to one hour and turns the panel off on
completion, ordinary error, SIGTERM or Ctrl-C. Display operations share the splash
lock. An external SIGKILL cannot run Python cleanup.
`off` requests `FB_BLANK_POWERDOWN` through DRM after clearing the backlight.
A brightness value of zero alone is not proof that the LCD rails are powered off.
Regulator counts and actual repeated wake behavior must be checked on the device.
Prepare another image on the build host:
```sh
python3 scripts/prepare-display-frame.py picture.png --output artifacts/custom-frame
```
The converter preserves aspect ratio, adds black padding and produces a preview,
BGRX framebuffer data and a checksum manifest. Transfer the generated frame bundle
separately; this command does not contact the phone.
## Boot logo
The optional `phone-headless.start` hook starts the logo in the background for
seven seconds, with a timeout and cleanup. On the integrated panel it selects the
new controller. On the old boot it selects the temporary session only when that
kernel-specific module was explicitly installed. Do not install the old helper
blindly, or auto-load it alongside the integrated driver.
Only install the hook after manual rendering and powerdown have worked. The
current clean-image builder keeps the backlight dark and does not automatically
install a generated splash bundle. SSH must remain independent of splash success.
## Hardware acceptance
Confirm the picture physically, test several brightness values and at least ten
off/on cycles, inspect DRM/DCS/kernel errors and compare regulator state before
and after. Verify normal reboot, logo timeout, SSH and temperature/charging.
Measured power savings are a separate result; they have not been established.
Do not live-unbind/rebind the MSM DRM stack: a previous attempt caused an Oops.
For future dashboards the same frame format can carry status screens. Animations
or interactive UIs can later use standard DRM/KMS or a Wayland client after the
panel lifecycle works reliably. Touchscreen support remains a separate porting task.
+19
View File
@@ -0,0 +1,19 @@
# Xiaomi Mi 8 Lite / platina hardware
The target is **Xiaomi Mi 8 Lite**, codename **platina**, Qualcomm **Snapdragon 660
(SDM660)**, ARM64. Maintainer tests used model **M1808D2TG**, 4 GB RAM and 64 GB eMMC.
Verify your own device; its marketing name alone does not identify the board.
The tested LCD is **Tianma NT36672A**, 1080 × 2280. The original community port
selected a BOE TD4320 descriptor. Those panels are not interchangeable merely
because their resolution matches. The current source candidate changes the DT
to the tested Tianma variant. BOE devices require their own configuration and test.
The device package uses USB network gadget mode and NetworkManager. Charging
behavior depends on the cable, host port and charger. Test the chosen supply
under the intended load; a visible charge indicator is not a sustained power test.
The phone has to stay awake for this headless-server use case.
Before repurposing an older phone, inspect its battery and check its storage
health. Keep a recovery route through the unlocked bootloader and Fastboot.
See the [feature matrix](../README.md#feature-status) for actual support status.
+145
View File
@@ -0,0 +1,145 @@
# Install Linux on Xiaomi Mi 8 Lite (platina)
**Development port.** The maintainer's existing installation boots and provides
SSH, but the checked-in integrated Tianma display candidate has not yet passed
its physical boot/power-cycle test. There is no supported prebuilt installer.
Build your own images using [BUILDING.md](BUILDING.md).
These steps are for a **fresh installation** on **Mi 8 Lite / platina**.
Flashing `userdata` destroys Android apps and personal data. For an existing Linux
installation, do not follow the userdata step: keep its filesystem UUID and use
a separately prepared boot/module update with a current backup.
## 1. Prepare recovery and identify the device
- Back up your Android data, the original boot/vbmeta images and the phone-specific
partitions needed for recovery, using a method you have actually verified.
Fastboot is not a universal partition-backup tool.
- Retain the matching stock ROM and a working host-side Fastboot recovery path.
Backups may contain identity/calibration data; keep them private.
- Unlock the bootloader through Xiaomi's supported process before installing Linux.
Unlocking itself can erase data. This project supplies no bootloader bypass.
- Check the **platina** codename and **Tianma NT36672A** panel variant.
See [hardware](HARDWARE.md). Do not use the Tianma candidate on an unverified BOE unit.
- Use reliable USB power and a charged, healthy battery. Keep physical access
throughout the first boot and recovery test.
Enter Fastboot with **Volume Down + Power** from power-off. With only the intended
phone attached, inspect it before any write:
```sh
fastboot devices
fastboot getvar product
fastboot oem device-info
fastboot getvar partition-size:boot
fastboot getvar partition-size:userdata
```
Confirm product `platina`, unlocked status and sufficient partition sizes.
The tested Fastboot boot-image limit was `0x3ffc000` bytes. Recheck your device;
a full raw backup of a partition can exceed the maximum accepted image length.
General device/mode information is also in the
[postmarketOS Mi 8 Lite wiki](https://wiki.postmarketos.org/wiki/Xiaomi_Mi_8_Lite_(xiaomi-platina)).
That page may describe a different kernel/port; use this repository's feature
matrix for this integration's support status.
## 2. Build and verify your own image pair
Follow BUILDING.md through the offline audit and module-index scoping stages.
The examples below assume these files exist:
```sh
ROOTFS=artifacts/candidate-local/xiaomi-platina.img
BOOT=artifacts/candidate-local-scoped/boot.img
make verify DIR=artifacts/candidate-local
make verify DIR=artifacts/candidate-local-scoped
```
The boot command line must refer to the UUID of that root filesystem. Do not mix
a newly generated clean rootfs with a boot prepared for another installation.
All exported modules must match the kernel. Archive your build manifest and APKs.
## 3. Fresh rootfs, vbmeta and RAM boot
**The following commands write to the phone. Run them only after completing the
backup, identification and offline checks.** A RAM boot avoids a permanent kernel
write, but it does not undo a preceding userdata or vbmeta write.
```sh
# Permanently replaces Android user data with your local Linux root filesystem.
fastboot -S 128M flash userdata "$ROOTFS"
# Generates and flashes AVB metadata with verification disabled for this port.
./scripts/pmbootstrap flasher flash_vbmeta
# Test the new kernel/initramfs in RAM before writing the boot partition.
fastboot boot "$BOOT"
```
Stop on any error. Do not flash GPT, bootloader, recovery, persist or modem identity
partitions. Leave the bootloader unlocked. The Fastboot `OKAY` message alone
proves neither that Linux booted nor that the display works.
If USB transfer hangs, investigate the host/cable/Fastboot transport before retrying.
Do not replace a failed RAM test with a blind permanent flash. Never unbind/rebind
MSM DRM on a live system as a substitute for booting the correct device tree.
## 4. Establish SSH and Wi-Fi
The phone's USB gadget address is **172.16.42.1/24**, user **server**. Configure the
host side of the identified USB network interface for **172.16.42.2/24**, without
replacing the host's normal default route. Some desktops do not automatically
choose that address. Use your Linux host's normal network manager and configure
only the interface belonging to this phone.
Verify the phone's SSH host key through a trusted local console or a verified
recovery session before recording it in known_hosts. `ssh-keyscan` by itself does
not authenticate the device. Keep strict host-key checking enabled.
```sh
ssh -i /PATH/TO/YOUR/PRIVATE-KEY -o StrictHostKeyChecking=yes server@172.16.42.1
```
The phone's dedicated administrator has passwordless sudo; password and root SSH
login are disabled. Add your Wi-Fi profile interactively on the phone, so the
passphrase does not become a repository file or shell argument:
```sh
sudo nmcli --ask device wifi connect YOUR_WIFI_SSID
ip -brief address show wlan0
```
Use its DHCP address, or `platina.local` where mDNS works. Test a second SSH
session over Wi-Fi before unplugging USB. USB administration does not by itself
provide Internet access: the host must explicitly share a connection if needed.
No router, firewall, forwarding or VPN changes are made by the build tools.
## 5. Validate, then install the boot image
Verify `uname -r`, the root filesystem, OpenRC services, SSH, Wi-Fi reconnect,
charging/temperature and kernel logs. For the new display candidate, require a
visible correct picture and repeated on/off tests; see [DISPLAY.md](DISPLAY.md).
Retain your stock boot and a way to return to Fastboot throughout.
When the RAM boot is successful, return physically to Fastboot and install the
**same tested** boot image:
```sh
fastboot flash boot "$BOOT"
fastboot reboot
```
Confirm a normal eMMC boot and automatic service startup, then test a separate
charger with Wi-Fi. Test long-term stability and charging under the intended
workload before relying on it as a 24/7 server.
## Recovery and future updates
On a failed candidate, return to Fastboot and restore the verified boot image for
the matching installation and module tree. A stock Android boot alone does not
restore Android userdata that has already been replaced. Follow your stock-ROM
recovery procedure if reverting the whole installation.
For later kernel updates, preserve rootfs UUID, pair kernel/modules/initramfs,
back up the active module tree and configuration, and check any package hooks
before installation. Do not automatically install a new kernel from a rolling
repository. Build, offline audit, RAM test and permanent flash are separate steps.
+58
View File
@@ -0,0 +1,58 @@
# Licensing
## Decision
**GPL-2.0-only** is the license for original Platina integration contributions,
including original scripts, tests, documentation and the supplied logo, unless
an individual file specifies otherwise. See [LICENSE](../LICENSE) and [NOTICE](../NOTICE).
The main reason is practical: this is a Linux kernel/device port, and its kernel
patches should remain usable under Linux's GPLv2 terms. This does not mean that
all software running on the phone has to use GPLv2.
| Option considered | Fit for this project |
|---|---|
| MIT | Good for permissive standalone tools; would not remove inherited kernel/copyleft requirements |
| Apache-2.0 | Explicit patent terms, but not compatible with GPL-2.0-only kernel combinations |
| GPL-3.0-only | Useful for many projects; cannot simply replace Linux's GPL-2.0-only terms |
| **GPL-2.0-only** | **Chosen for original integration work and kernel changes; matches the kernel's licensing baseline** |
Sources: [Linux kernel licensing rules](https://docs.kernel.org/process/license-rules.html),
[GNU license compatibility](https://www.gnu.org/licenses/license-list.html), and
[Apache's GPL compatibility explanation](https://apache.org/licenses/GPL-compatibility.html).
## Third-party material keeps its license
This source repository is an aggregate, not a claim that all included components
are one GPLv2 program. Existing copyrights and SPDX notices are retained.
- **Kernel patches/configuration:** kernel GPLv2 terms and relevant per-file SPDX
identifiers. Some files allow later GPL versions or have compatible dual licenses.
- **Inherited pmaports packaging:** GPLv3 where the upstream packaging
license applies. The package's `license=` field describes its installed payload;
it is not by itself a license grant for every packaging script.
- **Device data:** MIT as declared by the community device package, with original
author/maintainer attribution retained. Applicable kernel DT notices still apply.
- **Public firmware recipe and board-index helper:** newly written GPL-2.0-only
source. The public firmware revision is 2-r5 to distinguish this packaging change.
- **Firmware binaries:** proprietary and absent from this Git repository. Each
builder supplies matching inputs locally and must respect their own usage rights.
- **External toolchains/packages:** retain their own licenses; the source repository
does not vendor the full distro or claim ownership of those projects.
The upstream community repository has no blanket top-level LICENSE at the time
of this review. We therefore preserve its explicit kernel/device notices and do
not redistribute its firmware helper under an invented blanket license.
Full attribution and license texts are in NOTICE and LICENSES/.
## Source publication versus image publication
This initial public repository contains source and the project logo. It does not
publish APKs, prebuilt disk/boot images, stock ROMs or device calibration backups.
Building a local image does not automatically grant permission to redistribute
its proprietary firmware, nor make a personalized SSH key/configuration public.
Any future binary release requires a separate component/source and firmware-rights
review. A GPL-covered kernel binary must be accompanied by the corresponding
source and notices under the applicable license terms. Existing third-party
rights are preserved; the repository's project license cannot replace them.
@@ -0,0 +1,59 @@
# Local experimental headless adaptation; see project docs/SOURCE-AUDIT.md.
maintainer="Platina local project <platina@example.invalid>"
pkgname=device-xiaomi-platina
pkgdesc="Xiaomi Mi 8 Lite - experimental headless server"
pkgver=5
pkgrel=31
url="https://github.com/macosmojave2-alt/postmarket-mi8lite-platina"
license="MIT"
arch="aarch64"
options="!check !archcheck"
depends="
firmware-qcom-adreno-a530
firmware-xiaomi-platina
linux-firmware-qca
linux-postmarketos-qcom-sdm660
mkbootimg
msm-firmware-loader
postmarketos-base
chrony-openrc
pam-rundir
avahi
avahi-openrc
networkmanager-openrc
networkmanager-cli
networkmanager-wifi
wireless-regdb
dbus-openrc
postmarketos-usb-moded-openrc
postmarketos-usb-moded-default-profile-developer
tzdata
soc-qcom-sdm660
soc-qcom-sdm660-rproc
"
makedepends="devicepkg-dev"
install="$pkgname.post-install"
source="deviceinfo kernel-cmdline.conf modules-initfs disable-suspend.start gpu-firmware.files platina-networkmanager.conf platina-usb.nmconnection platina-usb-network.start platina-avahi.conf"
build() {
devicepkg_build $startdir $pkgname
}
package() {
devicepkg_package $startdir $pkgname
install -Dm755 "$srcdir/disable-suspend.start" "$pkgdir/etc/local.d/disable-suspend.start"
install -Dm644 "$srcdir/gpu-firmware.files" "$pkgdir/usr/share/mkinitfs/files/00-platina-gpu-firmware.files"
install -Dm644 "$srcdir/platina-networkmanager.conf" "$pkgdir/etc/NetworkManager/conf.d/30-platina-wifi.conf"
install -Dm600 "$srcdir/platina-usb.nmconnection" "$pkgdir/etc/NetworkManager/system-connections/platina-usb.nmconnection"
install -Dm755 "$srcdir/platina-usb-network.start" "$pkgdir/etc/local.d/platina-usb-network.start"
install -Dm644 "$srcdir/platina-avahi.conf" "$pkgdir/usr/share/platina/avahi-daemon.conf"
}
sha512sums="
c692b8c5935011955892071ab52b468c17ef186f21a5c2c7927453b2ae2ab8e80bb9d433c96a4e309a1bcec644c86adb9f0781c3fa02a39979d5880af464fb3d deviceinfo
3221917497d75c8ee6c151f2ed01a4dfdd3fe4e6a691b693b963bfb57fda9e1b482c50b77efa55a6dc4145ba08e9685e23482ddd488128983d79924f677f4eeb kernel-cmdline.conf
3901ca92054e15136091e5111feb5a33ca4fb7544020b9df421974409cab0d04989054c209215cb5e4a58da3ac142ebd47049fa75eb922ca6630e6b8297e0bad modules-initfs
53d9813f7537bc7d6f2ff7a623ed36c6f1243f3b66bbbc1ac2ebd55897a638e7867e447bea3b0353500d6b1a9a0142e18c1a708f3ff968f8970beedc1175279a disable-suspend.start
afc76d9275689bfa47065a14a2f9b0322576d5c269fa46663f4dab5b7299707450f4bbd7e0e6ea926b6afc7b73642dd33bed449d7c0999de53f48d2300d75f8c gpu-firmware.files
29dacca516ae2a0aea7e1c523131e120a13dca330af7f52b210971cf3613fe8a9267fd100499df8cf64478228f383c69f915092930468e2b3fb95271aa3512c2 platina-networkmanager.conf
dd56237bcc3e6c3219310dca6358b8f2269e40534f2670b0fdef27d5db3dad7d7742a24b24b6478a5e12689c60ab9353abf1713e5af237c07d4617e15c47da12 platina-usb.nmconnection
82272323ff6feb710f32ff34787cd85ccc189c6a8e77bed0de4dd0855f997939b1fd5952c6ab416be59e77a9f5b96bad67417737ae4361af9365d85f46ea29cc platina-usb-network.start
c620fb012b2b24ab25929952af2289caaaea6ac96a080b34b48e640c1d39c5662e1cd77bd26f89a864c127e514401243a41d6b7e53c8004c35cec045949f527f platina-avahi.conf
"
@@ -0,0 +1,13 @@
#!/bin/sh
set -e
if [ -f /usr/share/platina/avahi-daemon.conf ]; then
mkdir -p /etc/avahi
cp /usr/share/platina/avahi-daemon.conf /etc/avahi/avahi-daemon.conf
chmod 644 /etc/avahi/avahi-daemon.conf
fi
# Headless/OpenRC image: enable network and time services without the UI meta package.
if command -v rc-update >/dev/null 2>&1; then
for service in local networkmanager usb-moded chronyd avahi-daemon; do
rc-update add "$service" default
done
fi
@@ -0,0 +1,36 @@
# Reference: <https://postmarketos.org/deviceinfo>
# Please use double quotes only. You can source this file in shell
# scripts.
deviceinfo_format_version="0"
deviceinfo_name="Xiaomi Mi 8 Lite"
deviceinfo_manufacturer="Xiaomi"
deviceinfo_codename="xiaomi-platina"
deviceinfo_year="2018"
deviceinfo_dtb="qcom/sdm660-xiaomi-platina"
deviceinfo_append_dtb="true"
deviceinfo_arch="aarch64"
deviceinfo_drm="true"
# Device related
deviceinfo_chassis="handset"
deviceinfo_external_storage="true"
deviceinfo_screen_width="1080"
deviceinfo_screen_height="2280"
# Bootloader related
deviceinfo_flash_method="fastboot"
deviceinfo_flash_fastboot_partition_vbmeta="vbmeta"
deviceinfo_generate_bootimg="true"
deviceinfo_flash_sparse="true"
deviceinfo_flash_pagesize="4096"
deviceinfo_flash_offset_base="0x00000000"
deviceinfo_flash_offset_kernel="0x00008000"
deviceinfo_flash_offset_ramdisk="0x01000000"
deviceinfo_flash_offset_second="0x00f00000"
deviceinfo_flash_offset_tags="0x00000100"
# Xiaomi Communications Co., Ltd.
deviceinfo_usb_idVendor="0x2717"
# Mi/Redmi series (RNDIS)
deviceinfo_usb_idProduct="0xff80"
@@ -0,0 +1,11 @@
#!/bin/sh
# Mi 8 Lite (platina): evita que el sistema entre en suspend y tumbe el USB/SSH.
# Se ejecuta en cada arranque (local.d de OpenRC).
if [ -w /sys/power/state ]; then
chmod 000 /sys/power/state 2>/dev/null
fi
# Desactivar autosuspend de todos los dispositivos USB por si acaso.
for f in /sys/bus/usb/devices/*/power/control; do
[ -w "$f" ] && echo on > "$f" 2>/dev/null
done
exit 0
@@ -0,0 +1,6 @@
/lib/firmware/qcom/a530_pm4.fw
/lib/firmware/qcom/a530_pfp.fw
/lib/firmware/qcom/a530v3_gpmu.fw2
/lib/firmware/postmarketos/a512_zap.mbn
/lib/firmware/regulatory.db
/lib/firmware/regulatory.db.p7s
@@ -0,0 +1,4 @@
msm.prefer_mdp5=false
pd_ignore_unused
clk_ignore_unused
usbcore.autosuspend=-1
@@ -0,0 +1,14 @@
msm
pmi8998_fg
qcom_smbx
qcom-spmi-rradc
qcom_pil_info
ath10k_core
snd_soc_core
qcom_vadc_common
snd_soc_qcom_common
btqca
qcom_q6v5
qcom_common
snd_soc_qcom_sdw
btrtl
@@ -0,0 +1,16 @@
[server]
host-name=platina
domain-name=local
use-ipv4=yes
use-ipv6=no
allow-interfaces=wlan0
[wide-area]
enable-wide-area=no
[publish]
publish-hinfo=no
publish-workstation=no
[reflector]
enable-reflector=no
@@ -0,0 +1,12 @@
[main]
# USB routing uses static DNS. Do not replace it when Wi-Fi is disconnected.
dns=none
[device-platina-wifi]
match-device=interface-name:wlan0
managed=1
wifi.scan-rand-mac-address=no
[device-platina-usb]
match-device=interface-name:usb0
managed=1
@@ -0,0 +1,5 @@
#!/bin/sh
# NetworkManager autoconnect also handles USB appearing after boot or reconnect.
# Do not block boot when the cable is absent.
nmcli --wait 0 connection up platina-usb >/dev/null 2>&1 || true
exit 0
@@ -0,0 +1,18 @@
[connection]
id=platina-usb
uuid=e6cc4c76-9736-4bd4-b92f-37d89bcd8348
type=ethernet
interface-name=usb0
autoconnect=true
autoconnect-retries=0
[ethernet]
[ipv4]
method=manual
address1=172.16.42.1/24,172.16.42.2
route-metric=100
ignore-auto-dns=true
[ipv6]
method=disabled
@@ -0,0 +1,47 @@
# SPDX-License-Identifier: GPL-2.0-only
# Copyright (C) 2026 Sukecz
# This recipe is open source; the firmware it packages remains proprietary.
maintainer="Sukecz <222629366+Sukecz@users.noreply.github.com>"
pkgname=firmware-xiaomi-platina
pkgver=2
pkgrel=5
pkgdesc="User-supplied Xiaomi Mi 8 Lite GPU, Wi-Fi and modem firmware"
url="https://github.com/Sukecz/platina-linux"
arch="aarch64"
license="proprietary"
options="!strip !check !archcheck !spdx !tracedeps pmb:cross-native"
makedepends="qca-swiss-army-knife python3"
source="
a512_zap.elf
gen-board-2.py
firmware-xiaomi-platina-bdwlan.tar.gz
firmware-xiaomi-platina-modem.tar.gz
"
builddir="$srcdir"
build() {
ath10k-fwencoder --create \
--features=wowlan,no-nwifi-decap-4addr-padding,allows-mesh-bcast,mgmt-tx-by-ref,non-bmi,single-chan-info-per-channel \
--set-wmi-op-version=tlv --set-htt-op-version=tlv --set-fw-api=5
python3 "$srcdir/gen-board-2.py" "$srcdir/bdwlan" "$srcdir/bdwlan/board-2.json"
cd "$srcdir/bdwlan"
ath10k-bdencoder -c board-2.json -o "$srcdir/board-2.bin"
}
package() {
local wifi="$pkgdir/lib/firmware/ath10k/WCN3990/hw1.0"
local platform="$pkgdir/lib/firmware/postmarketos"
install -Dm644 "$srcdir/firmware-5.bin" "$wifi/firmware-5.bin"
install -Dm644 "$srcdir/board-2.bin" "$wifi/board-2.bin"
install -Dm644 "$srcdir/bdwlan/wlanmdsp.mbn" "$platform/wlanmdsp.mbn"
install -Dm644 "$srcdir/a512_zap.elf" "$platform/a512_zap.mbn"
install -dm755 "$platform"
install -m644 "$srcdir/modem/mba.mbn" "$srcdir/modem/modem.mdt" \
"$srcdir"/modem/modem.b* "$platform/"
}
sha512sums="
44e003d5d75265fed5192d2dc384cf9b6867b5c2008cca1a50c8fc77f4b918df37d5f7c6bc63d0e9e9e4908eaf9c5250347e1edf08231c79eae0366942de70db a512_zap.elf
6c27a45c8322743ef231da3560a43cbd83fc7bf339af133a3ec2a082ab55d63e0c945652caae4f934307536d919a18fa2a91e5a4daa3698125ec9260ce81f70c gen-board-2.py
61d1dd7e3273b3327e0217e1c9fe418034e1c2c65b18c0e1ba71978799eb159723cc71407a236a3ac3185e1948a45d3d346983a47504abb211d28c8c6e249f69 firmware-xiaomi-platina-bdwlan.tar.gz
2402fe62d1350e61d53d9f928c17ba0f6a7e4b76552946327067b01194945982935601812693e9567748fc7c8b67ef90b4ad49fee16533038e89acc9f26cc506 firmware-xiaomi-platina-modem.tar.gz
"
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
# Copyright (C) 2026 Sukecz
"""Index a user's local Qualcomm board files for ath10k-bdencoder."""
import argparse
import json
from pathlib import Path
import re
def index(directory):
entries = []
for path in sorted(directory.glob('bdwlan.*')):
if not path.is_file():
continue
suffix = path.suffix[1:]
aliases = ['bus=snoc']
if suffix == 'bin':
aliases.extend('bus=snoc,qmi-board-id=' + value for value in ('ff', '0'))
else:
value = suffix[1:] if re.fullmatch('b[0-9a-fA-F]{2}', suffix) else suffix
if not re.fullmatch('[0-9a-fA-F]+', value):
continue
aliases = ['bus=snoc,qmi-board-id=' + value]
entries.append({'names': aliases, 'data': path.name})
if not entries:
raise ValueError('No valid bdwlan files in the input directory')
return entries
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('directory', type=Path)
parser.add_argument('output', type=Path)
args = parser.parse_args()
args.output.write_text(json.dumps(index(args.directory), indent=2))
@@ -0,0 +1,192 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] arm64: dts: qcom: sdm660-xiaomi-platina: enable display + synaptics TCM touch
Enable the display pipeline + BOE TD4320 panel (1080x2280) via panel-simple,
WLED (2 strings), model the LCDB VSP/VSN as fixed regulators, and enable the
Synaptics TouchComm (TCM) touchscreen, brought up independently of the panel so
it does not disturb the shared TDDI rails.
Also drop the platina removed_region@85800000 and cdsp-region@94e00000 reserved
memory nodes that overlap nodes already defined in sdm630.dtsi / are unreferenced.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
@@ -63,16 +63,6 @@
no-map;
};
- cdsp-region@94e00000 {
- reg = <0x00 0x94e00000 0x00 0x600000>;
- no-map;
- };
-
- removed_region@85800000 {
- reg = <0x00 0x85800000 0x00 0x3700000>;
- no-map;
- };
-
framebuffer_memory@9d400000 {
reg = <0x0 0x9d400000 0x0 (1080 * 2280 * 4)>;
no-map;
@@ -89,6 +79,31 @@
regulator-boot-on;
};
+ /*
+ * The panel positive/negative supplies (VSP/VSN, +/-5.4V) are
+ * generated by the PM660L LCDB block, for which there is no mainline
+ * driver yet (see sdm660-mainline issue #125). The bootloader leaves
+ * LCDB enabled at boot; model VSP/VSN as fixed always-on regulators so
+ * the panel can probe and uses the voltages the bootloader set up.
+ */
+ panel_vsp: panel-vsp-regulator {
+ compatible = "regulator-fixed";
+ regulator-name = "panel_vsp";
+ regulator-min-microvolt = <5400000>;
+ regulator-max-microvolt = <5400000>;
+ regulator-always-on;
+ regulator-boot-on;
+ };
+
+ panel_vsn: panel-vsn-regulator {
+ compatible = "regulator-fixed";
+ regulator-name = "panel_vsn";
+ regulator-min-microvolt = <5400000>;
+ regulator-max-microvolt = <5400000>;
+ regulator-always-on;
+ regulator-boot-on;
+ };
+
cam_avdd_front_vreg: cam-avdd-front-vreg {
compatible = "regulator-fixed";
regulator-name = "cam-avdd-front-vreg";
@@ -236,7 +251,12 @@
};
&adreno_gpu {
- status = "disabled";
+ status = "okay";
+};
+
+&adreno_gpu_zap {
+ firmware-name = "a512_zap.mbn";
+ memory-region = <&zap_shader_region>;
};
&blsp_i2c2 {
@@ -252,14 +272,28 @@
&blsp_i2c4 {
status = "okay";
- touchscreen@1 {
- compatible = "novatek,nt36672a-ts";
- reg = <0x1>;
- iovcc-supply = <&vreg_l11a_1p8>;
+ /*
+ * Synaptics TouchComm (TCM) touchscreen. This unit has the Synaptics
+ * variant (the stock kernel dmesg shows the Novatek and Focaltech
+ * probes failing and the Synaptics controller at 4-0020 being present).
+ * It speaks the TCM command/report protocol (not RMI4), driven by the
+ * synaptics-tcm-i2c driver. It is integrated with the TD4320 TDDI
+ * panel, so it follows the panel power state via panel=<&panel>.
+ * vdd is the digital 1.8V rail; vbus is the panel analog rail (LCDB,
+ * kept on by the bootloader). reset tlmm66, IRQ tlmm67.
+ */
+ touchscreen@20 {
+ compatible = "syna,tcm-i2c";
+ reg = <0x20>;
+
+ vdd-supply = <&vreg_l11a_1p8>;
+
+
pinctrl-0 = <&ts_int_active &ts_rst_n>;
pinctrl-names = "default";
interrupts-extended = <&tlmm 67 IRQ_TYPE_EDGE_FALLING>;
reset-gpios = <&tlmm 66 GPIO_ACTIVE_LOW>;
+
touchscreen-size-x = <1080>;
touchscreen-size-y = <2280>;
};
@@ -270,11 +304,11 @@
};
&gpucc {
- status = "disabled";
+ status = "okay";
};
&mmcc {
- status = "disabled";
+ status = "okay";
};
&pm660_gpios {
@@ -789,3 +823,67 @@
dr_mode = "peripheral";
extcon = <&extcon_usb>;
};
+
+&mdss {
+ status = "okay";
+};
+
+&mdss_dsi0 {
+ status = "okay";
+
+ #address-cells = <1>;
+ #size-cells = <0>;
+
+ vdd-supply = <&vreg_l1b_0p925>;
+ vdda-supply = <&vreg_l1a_1p225>;
+
+ panel: panel@0 {
+ compatible = "xiaomi,platina-td4320", "boe,td4320";
+ reg = <0>;
+
+ iovcc-supply = <&vreg_l11a_1p8>;
+ vsp-supply = <&panel_vsp>;
+ vsn-supply = <&panel_vsn>;
+
+ reset-gpios = <&tlmm 53 GPIO_ACTIVE_LOW>;
+
+ backlight = <&pm660l_wled>;
+
+ pinctrl-names = "default";
+ pinctrl-0 = <&panel_reset_n &mdp_vsync_n>;
+
+ port {
+ panel_in: endpoint {
+ remote-endpoint = <&mdss_dsi0_out>;
+ };
+ };
+ };
+};
+
+&mdss_dsi0_out {
+ data-lanes = <0 1 2 3>;
+ remote-endpoint = <&panel_in>;
+};
+
+&mdss_dsi0_phy {
+ vcca-supply = <&vreg_l1b_0p925>;
+ status = "okay";
+};
+
+&mmss_smmu {
+ status = "okay";
+};
+
+&pm660l_wled {
+ qcom,switching-freq = <800>;
+ qcom,current-limit-microamp = <20000>;
+ qcom,num-strings = <2>;
+
+ status = "okay";
+};
+
+/* Audio DAI links are wired up in 0018-platina-audio (internal sndcard);
+ * q6asm-dai provides the MultiMedia frontends, so enable it. */
+&q6asmdai {
+ status = "okay";
+};
@@ -0,0 +1,57 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] drm/panel: simple: add BOE TD4320 (Xiaomi Mi 8 Lite platina)
Per the postmarketOS mainlining FAQ: when the device shows the boot splash with
mainline (platina does), the panel is already initialized by the bootloader, so
the simple-panel driver (no command init) should work. Add the BOE TD4320
1080x2280 panel to panel-simple with video mode + HSE, instead of sending the
downstream command sequence which left the panel showing stripes then black.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
--- a/drivers/gpu/drm/panel/b/drivers/gpu/drm/panel/panel-simple.c 2026-06-18 15:17:49.929505993 -0500
+++ b/drivers/gpu/drm/panel/panel-simple.c 2026-06-18 15:17:24.484507501 -0500
@@ -5777,8 +5777,43 @@
.lanes = 4,
};
+static const struct drm_display_mode boe_td4320_mode = {
+ .clock = (1080 + 92 + 20 + 112) * (2280 + 12 + 4 + 60) * 60 / 1000,
+ .hdisplay = 1080,
+ .hsync_start = 1080 + 92,
+ .hsync_end = 1080 + 92 + 20,
+ .htotal = 1080 + 92 + 20 + 112,
+ .vdisplay = 2280,
+ .vsync_start = 2280 + 12,
+ .vsync_end = 2280 + 12 + 4,
+ .vtotal = 2280 + 12 + 4 + 60,
+ .width_mm = 68,
+ .height_mm = 144,
+ .type = DRM_MODE_TYPE_DRIVER,
+};
+
+static const struct panel_desc_dsi boe_td4320 = {
+ .desc = {
+ .modes = &boe_td4320_mode,
+ .num_modes = 1,
+ .bpc = 8,
+ .size = {
+ .width = 68,
+ .height = 144,
+ },
+ .connector_type = DRM_MODE_CONNECTOR_DSI,
+ },
+ .flags = MIPI_DSI_MODE_VIDEO | MIPI_DSI_MODE_VIDEO_HSE |
+ MIPI_DSI_CLOCK_NON_CONTINUOUS,
+ .format = MIPI_DSI_FMT_RGB888,
+ .lanes = 4,
+};
+
static const struct of_device_id dsi_of_match[] = {
{
+ .compatible = "boe,td4320",
+ .data = &boe_td4320
+ }, {
.compatible = "auo,b080uan01",
.data = &auo_b080uan01
}, {
@@ -0,0 +1,735 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] input: touchscreen: add Synaptics TouchComm (TCM) I2C driver
Mainline driver for Synaptics TouchComm (TCM) touch controllers (e.g. the Synaptics
variant of the BOE TD4320 TDDI panel on the Xiaomi Mi 8 Lite). TCM uses a command/report
message protocol over I2C and is not RMI4-compatible. The driver only enables the shared
vdd rail (never disables it), retries the identify/app-info handshake, parses the variable
touch report config for multitouch type B and reports BTN_TOUCH for single-touch clients.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
--- /dev/null
+++ b/drivers/input/touchscreen/synaptics-tcm-i2c.c
@@ -0,0 +1,691 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Synaptics TouchComm (TCM) I2C touchscreen driver.
+ *
+ * Minimal mainline driver for Synaptics TCM (TouchComm v1) touch controllers
+ * such as the one integrated with the BOE TD4320 TDDI panel on the Xiaomi
+ * Mi 8 Lite (platina). These controllers use a command/report message protocol
+ * over I2C and are NOT compatible with the RMI4 register interface.
+ *
+ * The controller runs application firmware from its own storage (it reports
+ * MODE_APPLICATION right after reset), so no host firmware download is needed.
+ *
+ * Protocol and touch report parsing are based on the downstream
+ * drivers/input/touchscreen/synaptics_tcm vendor driver.
+ *
+ * Copyright (c) 2026 pmOS Mi8Lite <macosmojave2@gmail.com>
+ */
+
+#include <linux/delay.h>
+#include <linux/gpio/consumer.h>
+#include <linux/i2c.h>
+#include <linux/input.h>
+#include <linux/input/mt.h>
+#include <linux/input/touchscreen.h>
+#include <linux/interrupt.h>
+#include <linux/module.h>
+#include <linux/regulator/consumer.h>
+#include <linux/unaligned.h>
+#include <drm/drm_panel.h>
+
+/* TCM message framing */
+#define TCM_MESSAGE_MARKER 0xa5
+#define TCM_MESSAGE_PADDING 0x5a
+#define TCM_HEADER_SIZE 4
+#define TCM_RD_BUF 256
+
+/* Commands (host -> device) */
+#define TCM_CMD_IDENTIFY 0x02
+#define TCM_CMD_RESET 0x04
+#define TCM_CMD_ENABLE_REPORT 0x05
+#define TCM_CMD_DISABLE_REPORT 0x06
+#define TCM_CMD_GET_APP_INFO 0x20
+#define TCM_CMD_GET_TOUCH_REPORT_CONFIG 0x25
+
+/* Status codes (device -> host, in response message header code field) */
+#define TCM_STATUS_OK 0x01
+#define TCM_STATUS_CONTINUED_READ 0x03
+
+/* Report codes (async, device -> host) */
+#define TCM_REPORT_IDENTIFY 0x10
+#define TCM_REPORT_TOUCH 0x11
+
+/* Touch report config opcodes (describe the touch report bitstream layout) */
+enum tcm_touch_report_code {
+ TOUCH_END = 0,
+ TOUCH_FOREACH_ACTIVE_OBJECT,
+ TOUCH_FOREACH_OBJECT,
+ TOUCH_FOREACH_END,
+ TOUCH_PAD_TO_NEXT_BYTE,
+ TOUCH_TIMESTAMP,
+ TOUCH_OBJECT_N_INDEX,
+ TOUCH_OBJECT_N_CLASSIFICATION,
+ TOUCH_OBJECT_N_X_POSITION,
+ TOUCH_OBJECT_N_Y_POSITION,
+ TOUCH_OBJECT_N_Z,
+ TOUCH_OBJECT_N_X_WIDTH,
+ TOUCH_OBJECT_N_Y_WIDTH,
+ TOUCH_OBJECT_N_TX_POSITION_TIXELS,
+ TOUCH_OBJECT_N_RX_POSITION_TIXELS,
+ TOUCH_0D_BUTTONS_STATE,
+ TOUCH_GESTURE_DOUBLE_TAP,
+ TOUCH_FRAME_RATE,
+ TOUCH_POWER_IM,
+ TOUCH_CID_IM,
+ TOUCH_RAIL_IM,
+ TOUCH_CID_VARIANCE_IM,
+ TOUCH_NSM_FREQUENCY,
+ TOUCH_NSM_STATE,
+ TOUCH_NUM_OF_ACTIVE_OBJECTS,
+ TOUCH_NUM_OF_CPU_CYCLES_USED_SINCE_LAST_FRAME,
+};
+
+/* object classification (status) values */
+#define TCM_OBJECT_NONE 0
+#define TCM_OBJECT_FINGER 1
+#define TCM_OBJECT_GLOVED_FINGER 2
+
+#define TCM_MAX_OBJECTS 10
+#define TCM_CONFIG_SIZE 256
+
+struct syna_tcm {
+ struct i2c_client *client;
+ struct input_dev *input;
+ struct touchscreen_properties prop;
+ struct gpio_desc *reset_gpio;
+ struct regulator *vdd;
+ bool powered;
+
+ struct drm_panel_follower panel_follower;
+ bool is_panel_follower;
+ bool enabled;
+
+ unsigned int max_x;
+ unsigned int max_y;
+ unsigned int max_objects;
+
+ u8 config[TCM_CONFIG_SIZE];
+ unsigned int config_len;
+
+ u8 rxbuf[TCM_RD_BUF];
+};
+
+/* ---- low level I2C message I/O ---- */
+
+/*
+ * Read a whole TCM message in a single I2C read. The controller pads any
+ * bytes beyond the message with TCM_MESSAGE_PADDING (0x5a), so reading a
+ * fixed oversized buffer is safe. On success *code/*payload_len describe the
+ * message and the payload starts at buf[TCM_HEADER_SIZE].
+ */
+static int syna_read_message(struct syna_tcm *ts, u8 *code,
+ unsigned int *payload_len)
+{
+ struct i2c_client *client = ts->client;
+ struct i2c_msg msg = {
+ .addr = client->addr,
+ .flags = I2C_M_RD,
+ .len = TCM_RD_BUF,
+ .buf = ts->rxbuf,
+ };
+ int ret;
+
+ ret = i2c_transfer(client->adapter, &msg, 1);
+ if (ret != 1)
+ return ret < 0 ? ret : -EIO;
+
+ if (ts->rxbuf[0] != TCM_MESSAGE_MARKER)
+ return -EIO;
+
+ *code = ts->rxbuf[1];
+ *payload_len = get_unaligned_le16(&ts->rxbuf[2]);
+ if (*payload_len + TCM_HEADER_SIZE > TCM_RD_BUF)
+ *payload_len = TCM_RD_BUF - TCM_HEADER_SIZE;
+
+ return 0;
+}
+
+/* Write a command with optional payload. */
+static int syna_write_command(struct syna_tcm *ts, u8 cmd,
+ const u8 *payload, u16 len)
+{
+ struct i2c_client *client = ts->client;
+ u8 buf[8];
+ struct i2c_msg msg = {
+ .addr = client->addr,
+ .flags = 0,
+ .buf = buf,
+ };
+ int ret;
+
+ if (len + 3 > sizeof(buf))
+ return -EINVAL;
+
+ buf[0] = cmd;
+ put_unaligned_le16(len, &buf[1]);
+ if (len)
+ memcpy(&buf[3], payload, len);
+ msg.len = 3 + len;
+
+ ret = i2c_transfer(client->adapter, &msg, 1);
+ return ret == 1 ? 0 : (ret < 0 ? ret : -EIO);
+}
+
+/*
+ * Send a command and wait (polling) for its response. Used during probe when
+ * the IRQ is not requested yet. Any async reports received while waiting are
+ * skipped. The response payload (if any) is copied into resp.
+ */
+static int syna_command(struct syna_tcm *ts, u8 cmd, const u8 *payload, u16 len,
+ u8 *resp, unsigned int resp_size, unsigned int *resp_len)
+{
+ unsigned int plen;
+ u8 code;
+ int ret, tries;
+
+ ret = syna_write_command(ts, cmd, payload, len);
+ if (ret)
+ return ret;
+
+ /* wait for the response message, skipping async reports */
+ for (tries = 0; tries < 50; tries++) {
+ usleep_range(2000, 3000);
+
+ ret = syna_read_message(ts, &code, &plen);
+ if (ret)
+ continue;
+
+ /* async reports have code >= REPORT_IDENTIFY; skip them */
+ if (code >= TCM_REPORT_IDENTIFY)
+ continue;
+
+ if (code != TCM_STATUS_OK)
+ return -EIO;
+
+ if (resp && resp_size) {
+ plen = min(plen, resp_size);
+ memcpy(resp, &ts->rxbuf[TCM_HEADER_SIZE], plen);
+ if (resp_len)
+ *resp_len = plen;
+ }
+ return 0;
+ }
+
+ return -ETIMEDOUT;
+}
+
+/* ---- touch report parsing ---- */
+
+/* Extract `bits` bits from the payload bitstream at `offset`. */
+static u32 syna_get_bits(const u8 *data, unsigned int data_len,
+ unsigned int offset, unsigned int bits)
+{
+ u32 output = 0;
+ unsigned int remaining = bits;
+ unsigned int got = 0;
+
+ if (bits == 0 || bits > 32)
+ return 0;
+ if (offset + bits > data_len * 8)
+ return 0;
+
+ while (remaining) {
+ unsigned int byte_off = offset / 8;
+ unsigned int bit_off = offset % 8;
+ unsigned int avail = 8 - bit_off;
+ unsigned int take = min(avail, remaining);
+ u32 mask = 0xff >> (8 - take);
+ u32 val = (data[byte_off] >> bit_off) & mask;
+
+ output |= val << got;
+ got += take;
+ offset += take;
+ remaining -= take;
+ }
+
+ return output;
+}
+
+struct syna_object {
+ unsigned int status;
+ unsigned int x;
+ unsigned int y;
+};
+
+/*
+ * Parse a touch report payload according to the touch report config and emit
+ * MT type-B events. Mirrors the downstream config walker.
+ */
+static void syna_parse_touch(struct syna_tcm *ts, const u8 *data,
+ unsigned int data_len)
+{
+ struct syna_object objs[TCM_MAX_OBJECTS] = {};
+ const u8 *cfg = ts->config;
+ unsigned int cfg_len = ts->config_len;
+ unsigned int offset = 0; /* bit offset in payload */
+ unsigned int idx = 0; /* index into config */
+ unsigned int obj = 0;
+ unsigned int active_objects = 0;
+ unsigned int num_active = 0;
+ bool have_num_active = false;
+ bool active_only = false;
+ unsigned int foreach_idx = 0;
+ unsigned int objects_done = 0;
+ int active_count = 0;
+ int i;
+
+ while (idx < cfg_len) {
+ u8 code = cfg[idx++];
+ unsigned int bits;
+
+ switch (code) {
+ case TOUCH_END:
+ goto report;
+ case TOUCH_FOREACH_ACTIVE_OBJECT:
+ foreach_idx = idx;
+ active_only = true;
+ obj = 0;
+ objects_done = 0;
+ break;
+ case TOUCH_FOREACH_OBJECT:
+ foreach_idx = idx;
+ active_only = false;
+ obj = 0;
+ objects_done = 0;
+ break;
+ case TOUCH_FOREACH_END:
+ objects_done++;
+ /*
+ * The report packs only the objects it actually carries,
+ * back to back. Loop over the per-object config again
+ * only while the report still has data left (and we have
+ * not hit the object / active-object limit). Without this
+ * bound, iterating past the data would read zeroes and a
+ * TOUCH_OBJECT_N_INDEX field would clobber object 0.
+ */
+ if (objects_done < ts->max_objects &&
+ offset < data_len * 8 &&
+ (!have_num_active || objects_done < num_active)) {
+ idx = foreach_idx;
+ obj++;
+ }
+ break;
+ case TOUCH_PAD_TO_NEXT_BYTE:
+ offset = ALIGN(offset, 8);
+ break;
+ case TOUCH_TIMESTAMP:
+ bits = cfg[idx++];
+ offset += bits;
+ break;
+ case TOUCH_OBJECT_N_INDEX:
+ bits = cfg[idx++];
+ obj = syna_get_bits(data, data_len, offset, bits);
+ offset += bits;
+ break;
+ case TOUCH_OBJECT_N_CLASSIFICATION:
+ bits = cfg[idx++];
+ if (obj < TCM_MAX_OBJECTS)
+ objs[obj].status =
+ syna_get_bits(data, data_len, offset, bits);
+ offset += bits;
+ break;
+ case TOUCH_OBJECT_N_X_POSITION:
+ bits = cfg[idx++];
+ if (obj < TCM_MAX_OBJECTS)
+ objs[obj].x =
+ syna_get_bits(data, data_len, offset, bits);
+ offset += bits;
+ break;
+ case TOUCH_OBJECT_N_Y_POSITION:
+ bits = cfg[idx++];
+ if (obj < TCM_MAX_OBJECTS)
+ objs[obj].y =
+ syna_get_bits(data, data_len, offset, bits);
+ offset += bits;
+ break;
+ case TOUCH_NUM_OF_ACTIVE_OBJECTS:
+ bits = cfg[idx++];
+ num_active = syna_get_bits(data, data_len, offset, bits);
+ have_num_active = true;
+ if (num_active > ts->max_objects)
+ num_active = ts->max_objects;
+ active_objects = num_active;
+ offset += bits;
+ break;
+ /* fields we read past but don't use */
+ case TOUCH_OBJECT_N_Z:
+ case TOUCH_OBJECT_N_X_WIDTH:
+ case TOUCH_OBJECT_N_Y_WIDTH:
+ case TOUCH_OBJECT_N_TX_POSITION_TIXELS:
+ case TOUCH_OBJECT_N_RX_POSITION_TIXELS:
+ case TOUCH_0D_BUTTONS_STATE:
+ case TOUCH_GESTURE_DOUBLE_TAP:
+ case TOUCH_FRAME_RATE:
+ case TOUCH_POWER_IM:
+ case TOUCH_CID_IM:
+ case TOUCH_RAIL_IM:
+ case TOUCH_CID_VARIANCE_IM:
+ case TOUCH_NSM_FREQUENCY:
+ case TOUCH_NSM_STATE:
+ case TOUCH_NUM_OF_CPU_CYCLES_USED_SINCE_LAST_FRAME:
+ bits = cfg[idx++];
+ offset += bits;
+ break;
+ default:
+ /* unknown opcode followed by a bit count */
+ bits = cfg[idx++];
+ offset += bits;
+ break;
+ }
+ }
+
+report:
+ (void)active_objects;
+ for (i = 0; i < ts->max_objects && i < TCM_MAX_OBJECTS; i++) {
+ bool active = objs[i].status == TCM_OBJECT_FINGER ||
+ objs[i].status == TCM_OBJECT_GLOVED_FINGER;
+
+ input_mt_slot(ts->input, i);
+ input_mt_report_slot_state(ts->input, MT_TOOL_FINGER, active);
+ if (active) {
+ active_count++;
+ touchscreen_report_pos(ts->input, &ts->prop,
+ objs[i].x, objs[i].y, true);
+ }
+ }
+ /* single-touch emulation for clients that rely on BTN_TOUCH */
+ input_report_key(ts->input, BTN_TOUCH, active_count > 0);
+ input_mt_sync_frame(ts->input);
+ input_sync(ts->input);
+}
+
+/* ---- IRQ ---- */
+
+static irqreturn_t syna_irq(int irq, void *dev_id)
+{
+ struct syna_tcm *ts = dev_id;
+ unsigned int plen;
+ u8 code;
+
+ if (syna_read_message(ts, &code, &plen))
+ return IRQ_HANDLED;
+
+ if (code == TCM_REPORT_TOUCH)
+ syna_parse_touch(ts, &ts->rxbuf[TCM_HEADER_SIZE], plen);
+
+ return IRQ_HANDLED;
+}
+
+/* ---- power / reset ---- */
+
+static int syna_power_on(struct syna_tcm *ts)
+{
+ int ret;
+
+ /*
+ * Enable our digital rail. This rail (and the analog LCDB rail) is
+ * shared with the TDDI panel, so we only ever turn it ON and never
+ * disable it: powering it down would kill the panel. The analog supply
+ * is left to the bootloader/panel (always on), we do not manage it.
+ */
+ if (!ts->powered) {
+ ret = regulator_enable(ts->vdd);
+ if (ret)
+ return ret;
+ ts->powered = true;
+ }
+
+ /* the bootloader leaves the panel/touch rails on; give it a moment */
+ msleep(20);
+
+ if (ts->reset_gpio) {
+ gpiod_set_value_cansleep(ts->reset_gpio, 1);
+ usleep_range(1000, 2000);
+ gpiod_set_value_cansleep(ts->reset_gpio, 0);
+ /* controller needs ~200ms to boot into application firmware */
+ msleep(200);
+ }
+
+ return 0;
+}
+
+/*
+ * We deliberately never power the controller down: its rails are shared with
+ * the always-on TDDI panel. The most we do on stop is assert the touch-only
+ * reset GPIO (tlmm66), which does not affect the panel.
+ */
+static void syna_power_off(struct syna_tcm *ts)
+{
+ if (ts->reset_gpio)
+ gpiod_set_value_cansleep(ts->reset_gpio, 1);
+}
+
+/* ---- controller setup (query info + config, enable reports) ---- */
+
+static int syna_setup(struct syna_tcm *ts)
+{
+ struct device *dev = &ts->client->dev;
+ u8 app_info[64];
+ unsigned int len;
+ u8 code, rep;
+ unsigned int plen;
+ int ret, tries, attempt;
+
+ /*
+ * The controller may not answer immediately after an independent probe
+ * (the shared TDDI rails take time to settle). Retry the identify +
+ * app-info handshake for a few seconds before giving up.
+ */
+ for (attempt = 0; ; attempt++) {
+ /* drain the identify report the controller sends after reset */
+ for (tries = 0; tries < 20; tries++) {
+ usleep_range(2000, 3000);
+ if (!syna_read_message(ts, &code, &plen) &&
+ code == TCM_REPORT_IDENTIFY)
+ break;
+ }
+
+ ret = syna_command(ts, TCM_CMD_GET_APP_INFO, NULL, 0,
+ app_info, sizeof(app_info), &len);
+ if (!ret && len >= 38)
+ break;
+
+ if (attempt >= 20)
+ return dev_err_probe(dev, ret ? ret : -EIO,
+ "controller not responding (app info)\n");
+ msleep(100);
+ }
+
+ /* app_info layout (struct syna_tcm_app_info): max_x/max_y/max_objects
+ * are 16-bit LE at offsets 32/34/36 (after the 16-byte
+ * customer_config_id at offset 16).
+ */
+ ts->max_x = get_unaligned_le16(&app_info[32]);
+ ts->max_y = get_unaligned_le16(&app_info[34]);
+ ts->max_objects = get_unaligned_le16(&app_info[36]);
+
+ if (!ts->max_x || !ts->max_y ||
+ ts->max_objects == 0 || ts->max_objects > TCM_MAX_OBJECTS) {
+ dev_warn(dev, "implausible app info x=%u y=%u obj=%u, using defaults\n",
+ ts->max_x, ts->max_y, ts->max_objects);
+ ts->max_x = 1080;
+ ts->max_y = 2280;
+ ts->max_objects = TCM_MAX_OBJECTS;
+ }
+
+ ret = syna_command(ts, TCM_CMD_GET_TOUCH_REPORT_CONFIG, NULL, 0,
+ ts->config, sizeof(ts->config), &ts->config_len);
+ if (ret)
+ return dev_err_probe(dev, ret, "failed to get report config\n");
+
+ /* enable touch reports */
+ rep = TCM_REPORT_TOUCH;
+ ret = syna_command(ts, TCM_CMD_ENABLE_REPORT, &rep, 1, NULL, 0, NULL);
+ if (ret)
+ return dev_err_probe(dev, ret, "failed to enable touch report\n");
+
+ dev_info(dev, "Synaptics TCM touch %ux%u, %u objects\n",
+ ts->max_x, ts->max_y, ts->max_objects);
+ return 0;
+}
+
+static int syna_start(struct syna_tcm *ts)
+{
+ int ret;
+
+ ret = syna_power_on(ts);
+ if (ret)
+ return ret;
+
+ ret = syna_setup(ts);
+ if (ret) {
+ syna_power_off(ts);
+ return ret;
+ }
+
+ enable_irq(ts->client->irq);
+ ts->enabled = true;
+ return 0;
+}
+
+static void syna_stop(struct syna_tcm *ts)
+{
+ disable_irq(ts->client->irq);
+ ts->enabled = false;
+ syna_power_off(ts);
+}
+
+/* ---- drm panel follower (power-sync with the TDDI panel) ---- */
+
+static int syna_panel_prepared(struct drm_panel_follower *follower)
+{
+ struct syna_tcm *ts = container_of(follower, struct syna_tcm,
+ panel_follower);
+
+ return syna_start(ts);
+}
+
+static int syna_panel_unpreparing(struct drm_panel_follower *follower)
+{
+ struct syna_tcm *ts = container_of(follower, struct syna_tcm,
+ panel_follower);
+
+ if (ts->enabled)
+ syna_stop(ts);
+ return 0;
+}
+
+static const struct drm_panel_follower_funcs syna_follower_funcs = {
+ .panel_prepared = syna_panel_prepared,
+ .panel_unpreparing = syna_panel_unpreparing,
+};
+
+/* ---- probe ---- */
+
+static int syna_probe(struct i2c_client *client)
+{
+ struct device *dev = &client->dev;
+ struct syna_tcm *ts;
+ int ret;
+
+ ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL);
+ if (!ts)
+ return -ENOMEM;
+
+ ts->client = client;
+ i2c_set_clientdata(client, ts);
+
+ /*
+ * Only the digital rail is managed here. The analog supply is the panel
+ * LCDB rail, left on by the bootloader; we must not touch it. The vdd
+ * rail is shared with the panel iovcc, so we only turn it on (never off).
+ */
+ ts->vdd = devm_regulator_get(dev, "vdd");
+ if (IS_ERR(ts->vdd))
+ return dev_err_probe(dev, PTR_ERR(ts->vdd),
+ "failed to get vdd regulator\n");
+
+ ts->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH);
+ if (IS_ERR(ts->reset_gpio))
+ return dev_err_probe(dev, PTR_ERR(ts->reset_gpio),
+ "failed to get reset gpio\n");
+
+ /* default geometry; refined from app info in syna_setup() */
+ ts->max_x = 1080;
+ ts->max_y = 2280;
+ ts->max_objects = TCM_MAX_OBJECTS;
+
+ ts->input = devm_input_allocate_device(dev);
+ if (!ts->input)
+ return -ENOMEM;
+
+ ts->input->name = "Synaptics TCM Touchscreen";
+ ts->input->id.bustype = BUS_I2C;
+
+ input_set_capability(ts->input, EV_KEY, BTN_TOUCH);
+ input_set_abs_params(ts->input, ABS_MT_POSITION_X, 0, ts->max_x, 0, 0);
+ input_set_abs_params(ts->input, ABS_MT_POSITION_Y, 0, ts->max_y, 0, 0);
+ touchscreen_parse_properties(ts->input, true, &ts->prop);
+
+ ret = input_mt_init_slots(ts->input, TCM_MAX_OBJECTS,
+ INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED);
+ if (ret)
+ return dev_err_probe(dev, ret, "failed to init MT slots\n");
+
+ ret = devm_request_threaded_irq(dev, client->irq, NULL, syna_irq,
+ IRQF_ONESHOT | IRQF_NO_AUTOEN,
+ "synaptics-tcm", ts);
+ if (ret)
+ return dev_err_probe(dev, ret, "failed to request irq\n");
+
+ /* register input before the controller can raise IRQs */
+ ret = input_register_device(ts->input);
+ if (ret)
+ return dev_err_probe(dev, ret, "failed to register input\n");
+
+ /*
+ * If the touch node references the panel (panel = <&panel>), follow the
+ * panel's power state so we power on in sync with the TDDI display.
+ * Otherwise bring the controller up immediately.
+ */
+ if (drm_is_panel_follower(dev)) {
+ ts->is_panel_follower = true;
+ ts->panel_follower.funcs = &syna_follower_funcs;
+ ret = devm_drm_panel_add_follower(dev, &ts->panel_follower);
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "failed to add panel follower\n");
+ } else {
+ ret = syna_start(ts);
+ if (ret)
+ return ret;
+ }
+
+ return 0;
+}
+
+static const struct of_device_id syna_of_match[] = {
+ { .compatible = "syna,tcm-i2c" },
+ { }
+};
+MODULE_DEVICE_TABLE(of, syna_of_match);
+
+static const struct i2c_device_id syna_id[] = {
+ { "synaptics-tcm-i2c" },
+ { }
+};
+MODULE_DEVICE_TABLE(i2c, syna_id);
+
+static struct i2c_driver syna_driver = {
+ .driver = {
+ .name = "synaptics-tcm-i2c",
+ .of_match_table = syna_of_match,
+ },
+ .probe = syna_probe,
+ .id_table = syna_id,
+};
+module_i2c_driver(syna_driver);
+
+MODULE_DESCRIPTION("Synaptics TouchComm (TCM) I2C touchscreen driver");
+MODULE_AUTHOR("pmOS Mi8Lite <macosmojave2@gmail.com>");
+MODULE_LICENSE("GPL");
--- a/drivers/input/touchscreen/Kconfig
+++ b/drivers/input/touchscreen/Kconfig
@@ -1309,6 +1309,18 @@
To compile this driver as a module, choose M here: the
module will be called surface3_spi.
+config TOUCHSCREEN_SYNAPTICS_TCM
+ tristate "Synaptics TouchComm (TCM) I2C touchscreen"
+ depends on I2C
+ help
+ Say Y here if you have a Synaptics TouchComm (TCM) touch controller,
+ such as the one integrated with the BOE TD4320 TDDI panel on the
+ Xiaomi Mi 8 Lite (platina). These controllers use a command/report
+ message protocol and are not compatible with RMI4.
+
+ To compile this driver as a module, choose M here: the module will be
+ called synaptics-tcm-i2c.
+
config TOUCHSCREEN_SX8654
tristate "Semtech SX8654 touchscreen"
depends on I2C
--- a/drivers/input/touchscreen/Makefile
+++ b/drivers/input/touchscreen/Makefile
@@ -109,6 +109,7 @@
wm97xx-ts-$(CONFIG_TOUCHSCREEN_WM9712) += wm9712.o
wm97xx-ts-$(CONFIG_TOUCHSCREEN_WM9713) += wm9713.o
obj-$(CONFIG_TOUCHSCREEN_WM97XX_MAINSTONE) += mainstone-wm97xx.o
+obj-$(CONFIG_TOUCHSCREEN_SYNAPTICS_TCM) += synaptics-tcm-i2c.o
obj-$(CONFIG_TOUCHSCREEN_SX8654) += sx8654.o
obj-$(CONFIG_TOUCHSCREEN_TPS6507X) += tps6507x-ts.o
obj-$(CONFIG_TOUCHSCREEN_ZET6223) += zet6223.o
@@ -0,0 +1,46 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] arm64: dts: qcom: sdm660-xiaomi-platina: enable battery + charger
Enable battery monitoring on the Xiaomi Mi 8 Lite: the PM660 charger
(qcom,pm660-charger), the PMI8998-style fuel gauge (qcom,pmi8998-fg) and
the round-robin ADC (qcom,pm660-rradc) it depends on. Model the 3350 mAh
cell as a simple-battery, matching what Xiaomi Redmi Note 7 (lavender)
does on the same SDM660 + PM660 PMIC.
This populates /sys/class/power_supply so charge percentage and power
management work.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
@@ -887,3 +887,29 @@
&q6asmdai {
status = "okay";
};
+
+/ {
+ battery: battery {
+ compatible = "simple-battery";
+ charge-full-design-microamp-hours = <3350000>;
+ voltage-min-design-microvolt = <3400000>;
+ voltage-max-design-microvolt = <4400000>;
+ };
+};
+
+&pm660_charger {
+ monitored-battery = <&battery>;
+
+ status = "okay";
+};
+
+&pm660_fg {
+ monitored-battery = <&battery>;
+ power-supplies = <&pm660_charger>;
+
+ status = "okay";
+};
+
+&pm660_rradc {
+ status = "okay";
+};
@@ -0,0 +1,45 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] arm64: dts: qcom: sdm660-xiaomi-platina: enable modem + WCN3990 WiFi (direct supplies)
Enable the modem (MSS) remoteproc and the WCN3990 WiFi.
Power the WLAN block with the four rails the stock Android DT of this
exact device uses (icnss node in the live-extracted DT):
vdd-cx-mx -> LDO A5 (0.848 V)
vdd-1.8-xo -> LDO A9
vdd-1.3-rfa-> LDO A6
vdd-3.3-ch0-> LDO A19
There is no ch1 rail (the chip reports num_rf_chains = 1, single chain)
and Android drives the rails directly - there is no wcn3990-pmu power
sequencer on this board. This mirrors sdm660-xiaomi-lavender, where WiFi
scan/connect is known to work with the same SoC and firmware generation
(WLAN.HL.1.0.1). A previous revision of this patch modeled a wcn3990-pmu
node with a vddio rail, which does not match the platina hardware; with
it the WLAN firmware crashed (err_qdi.c EX:wlan_process) as soon as a
scan was started.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
@@ -913,3 +913,20 @@
&pm660_rradc {
status = "okay";
};
+
+&remoteproc_mss {
+ firmware-name = "postmarketos/mba.mbn", "postmarketos/modem.mdt";
+
+ status = "okay";
+};
+
+&wifi {
+ vdd-0.8-cx-mx-supply = <&vreg_l5a_0p848>;
+ vdd-1.8-xo-supply = <&vreg_l9a_1p8>;
+ vdd-1.3-rfa-supply = <&vreg_l6a_1p3>;
+ vdd-3.3-ch0-supply = <&vreg_l19a_3p3>;
+
+ qcom,calibration-variant = "xiaomi_platina";
+
+ status = "okay";
+};
@@ -0,0 +1,88 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] ath10k: work around WCN3990/SDM660 firmware crashes (psmode, group key, 5GHz scan)
The WCN3990 WLAN firmware on SDM660 (WLAN.HL.1.0.1.c6, runs as a
protection domain inside the modem Q6) fatally crashes
(err_qdi.c EX:wlan_process, always PC=b00c75b8) as soon as it receives
the WMI set_psmode command, which mac80211/ath10k send unconditionally
during STA vif bring-up and around scans. Any scan (active or passive,
any band) kills the firmware and only a full reboot recovers it.
Port the workarounds that were verified on this device (Xiaomi Mi 8
Lite, platina) on the 6.17-based tree:
1. never send set_psmode on WCN3990 (skip ath10k_mac_vif_setup_ps),
2. never advertise SUPPORTS_PS/SUPPORTS_DYNAMIC_PS on WCN3990 so
mac80211 does not trigger PS transitions,
3. force passive scan on 5GHz (firmware does not tune the radio on
active 5GHz scans; rx_clear_count is identical across channels),
4. don't install a junk group key on DISABLE_KEY on WCN3990 (crashes
the firmware on disconnect - same class of bug).
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
--- a/drivers/net/wireless/ath/ath10k/mac.c
+++ b/drivers/net/wireless/ath/ath10k/mac.c
@@ -290,9 +290,12 @@
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
if (cmd == DISABLE_KEY) {
- if (flags & WMI_KEY_GROUP) {
+ if ((flags & WMI_KEY_GROUP) && !QCA_REV_WCN3990(ar)) {
/* Not all hardware handles group-key deletion operation
* correctly. Replace the key with a junk value to invalidate it.
+ * On WCN3990 (WLAN.HL.1.0.1 firmware in the SDM660 modem)
+ * installing a junk group key crashes the firmware, so take
+ * the plain-disable path there.
*/
get_random_bytes(key->key, key->keylen);
} else {
@@ -1959,6 +1962,16 @@
lockdep_assert_held(&arvif->ar->conf_mutex);
+ /*
+ * The WCN3990 WLAN firmware on the SDM660 (running inside the modem
+ * Q6) crashes with EX:wlan_process PC=b00c75b8 as soon as it receives
+ * the WMI set_psmode command. This command is otherwise sent
+ * unconditionally during STA vif bring-up / scan. Skip it entirely on
+ * WCN3990 so the firmware stays alive and scan/connect can proceed.
+ */
+ if (QCA_REV_WCN3990(ar))
+ return 0;
+
if (arvif->vif->type != NL80211_IFTYPE_STATION)
return 0;
@@ -3450,6 +3463,14 @@
passive = channel->flags & IEEE80211_CHAN_NO_IR;
ch->passive = passive;
+ /* Force passive scan on 5GHz to work around WCN3990
+ * firmware bug where active scan doesn't tune the
+ * radio on 5GHz non-DFS channels. The radio reports
+ * identical rx_clear_count across channels.
+ */
+ if (QCA_REV_WCN3990(ar) && band == NL80211_BAND_5GHZ)
+ ch->passive = true;
+
/* the firmware is ignoring the "radar" flag of the
* channel and is scanning actively using Probe Requests
* on "Radar detection"/DFS channels which are not
@@ -10072,7 +10093,15 @@
ieee80211_hw_set(ar->hw, SIGNAL_DBM);
- if (!test_bit(ATH10K_FW_FEATURE_NO_PS,
+ /*
+ * The WCN3990 WLAN firmware (WLAN.HL.1.0.1.c6) running inside the modem
+ * on the SDM660 crashes (EX:wlan_process, PC=b00c75b8) the moment it
+ * receives the WMI set_psmode command that mac80211 triggers when power
+ * save is advertised. Do not advertise PS for WCN3990 so mac80211 never
+ * sends set_psmode; this keeps the device operational (scan/connect).
+ */
+ if (!QCA_REV_WCN3990(ar) &&
+ !test_bit(ATH10K_FW_FEATURE_NO_PS,
ar->running_fw->fw_file.fw_features)) {
ieee80211_hw_set(ar->hw, SUPPORTS_PS);
ieee80211_hw_set(ar->hw, SUPPORTS_DYNAMIC_PS);
@@ -0,0 +1,69 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] ath10k: WCN3990/SDM660: encode scan channel list like qcacld
The WLAN.HL.1.0.1 firmware running in the SDM660 modem fatally asserts
(err_qdi.c EX:wlan_process) on the first channel tune of any scan,
active or passive, on any band. Verified on Xiaomi Mi 8 Lite (platina)
to be independent of: board data file used (all 18 device calibrations),
regdomain in the board data (0x809c and unlocked 0x0), firmware build
(c6-00023 and c6-00027), modem build (-00076 and -00087), regulators
(all rails verified on at runtime) and the RF reference clock (on).
What does differ is the WMI_SCAN_CHAN_LIST payload. qcacld (the stock
Android driver, which scans fine on the same device/firmware) sends per
channel only the regulatory power, in plain dBm, leaving max_power,
max_tx_power, antenna_max and reg_class_id at zero, and does not allow
VHT on 2.4GHz. Mainline ath10k sends max_power/reg_power/max_tx_power
as doubled half-dBm values (e.g. 40 for 20dBm) while the firmware's WMI
headers document max_tx_power as "1 dBm units"; the firmware's TPC
lookup against the per-device board data then fails at tune time.
Mirror the qcacld encoding on WCN3990.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
--- a/drivers/net/wireless/ath/ath10k/mac.c
+++ b/drivers/net/wireless/ath/ath10k/mac.c
@@ -3449,7 +3449,11 @@
ch->allow_ht = true;
/* FIXME: when should we really allow VHT? */
- ch->allow_vht = true;
+ if (QCA_REV_WCN3990(ar))
+ /* qcacld only allows VHT on 5GHz; mirror it */
+ ch->allow_vht = channel->band == NL80211_BAND_5GHZ;
+ else
+ ch->allow_vht = true;
ch->allow_ibss =
!(channel->flags & IEEE80211_CHAN_NO_IR);
@@ -3481,9 +3485,26 @@
ch->freq = channel->center_freq;
ch->band_center_freq1 = channel->center_freq;
ch->min_power = 0;
- ch->max_power = channel->max_power * 2;
- ch->max_reg_power = channel->max_reg_power * 2;
- ch->max_antenna_gain = channel->max_antenna_gain;
+ if (QCA_REV_WCN3990(ar)) {
+ /* The WLAN.HL.1.0.1 firmware on the SDM660
+ * modem takes these fields the way qcacld
+ * sends them: only the regulatory power, in
+ * plain dBm (max_tx_power is documented as
+ * "1 dBm units" in the WMI headers). The
+ * doubled half-dBm values below make the TPC
+ * lookup against the per-device board data
+ * fail and the firmware fatally asserts on
+ * the first channel tune of any scan
+ * (err_qdi.c EX:wlan_process).
+ */
+ ch->max_power = 0;
+ ch->max_reg_power = channel->max_reg_power;
+ ch->max_antenna_gain = 0;
+ } else {
+ ch->max_power = channel->max_power * 2;
+ ch->max_reg_power = channel->max_reg_power * 2;
+ ch->max_antenna_gain = channel->max_antenna_gain;
+ }
ch->reg_class_id = 0; /* FIXME */
/* FIXME: why use only legacy modes, why not any
@@ -0,0 +1,60 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] ath10k: wmi-tlv: append the trailing scan TLVs qcacld sends
The WLAN.HL.1.0.1.c6 firmware of the WCN3990 on SDM660 fatally asserts
(err_qdi.c EX:wlan_process, RT:2072) as soon as the scan state machine
processes the first channel of any scan (active or passive, any band).
Verified on Xiaomi Mi 8 Lite (platina) to be independent of board data,
regdomain, firmware/modem build, regulators, RF clock, power values in
the channel list, and PS mode.
qcacld - the driver this firmware was developed against, and which scans
fine on the same device - always appends two more TLVs to
WMI_START_SCAN_CMDID after the IE array: the probe request vendor OUI
whitelist (ARRAY_STRUC) and the per-channel phy mode list (ARRAY_BYTE),
both zero-length in a normal scan ("Add ZERO legth phy mode TLV" in
wmi_unified_tlv.c). Mainline stops after the IE array. Append the two
trailing zero-length TLVs to match qcacld's wire format.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
--- a/drivers/net/wireless/ath/ath10k/wmi-tlv.c
+++ b/drivers/net/wireless/ath/ath10k/wmi-tlv.c
@@ -1995,7 +1995,9 @@
sizeof(*tlv) + chan_len +
sizeof(*tlv) + ssid_len +
sizeof(*tlv) + bssid_len +
- sizeof(*tlv) + ie_len;
+ sizeof(*tlv) + ie_len +
+ sizeof(*tlv) + /* zero-length vendor OUI array */
+ sizeof(*tlv); /* zero-length phy mode list */
skb = ath10k_wmi_alloc_skb(ar, len);
if (!skb)
@@ -2065,6 +2067,26 @@
ptr += sizeof(*tlv);
ptr += ie_len;
+ /* The WMI-TLV firmware of the WCN3990 on SDM660 (WLAN.HL.1.0.1.c6)
+ * expects the two trailing arrays qcacld always appends to
+ * WMI_START_SCAN_CMDID, even when they are empty: the probe request
+ * vendor OUI whitelist and the per-channel phy mode list. Without
+ * them the firmware accepts the command but fatally asserts
+ * (err_qdi.c EX:wlan_process) as soon as the scan state machine
+ * processes the first channel. Append both as zero-length TLVs,
+ * exactly like qcacld does for a normal (non wide-band, no
+ * whitelist) scan.
+ */
+ tlv = ptr;
+ tlv->tag = __cpu_to_le16(WMI_TLV_TAG_ARRAY_STRUCT);
+ tlv->len = __cpu_to_le16(0);
+ ptr += sizeof(*tlv);
+
+ tlv = ptr;
+ tlv->tag = __cpu_to_le16(WMI_TLV_TAG_ARRAY_BYTE);
+ tlv->len = __cpu_to_le16(0);
+ ptr += sizeof(*tlv);
+
ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi tlv start scan\n");
return skb;
}
@@ -0,0 +1,40 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] ath10k: don't request scan channel stats on WCN3990
The WLAN.HL.1.0.1.c6 firmware of the WCN3990 on SDM660 (Xiaomi Mi 8
Lite, platina) fatally asserts (err_qdi.c EX:wlan_process, RT:2072,
a fixed ~87ms after tuning to every scan channel) whenever the scan is
requested with WMI_SCAN_CHAN_STAT_EVENT. Bisected at runtime with WMI
flag knobs after eliminating board data, regdomain, channel powers,
trailing TLVs, firmware/modem builds, PS mode, band crossing and
regulators/clocks: clearing this single bit turns every scan from a
guaranteed firmware crash into a reliable full scan of both bands
(30 BSS found in testing). Reading the MAC cycle counters for the
channel stats appears to hit a dead hardware block on this platform.
Don't set the flag on WCN3990. Only channel survey data is lost.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
--- a/drivers/net/wireless/ath/ath10k/wmi.c
+++ b/drivers/net/wireless/ath/ath10k/wmi.c
@@ -7096,7 +7096,18 @@
| WMI_SCAN_EVENT_FOREIGN_CHANNEL
| WMI_SCAN_EVENT_FOREIGN_CHANNEL_EXIT
| WMI_SCAN_EVENT_DEQUEUED;
- arg->scan_ctrl_flags |= WMI_SCAN_CHAN_STAT_EVENT;
+ /* On the WCN3990 of the SDM660 (WLAN.HL.1.0.1.c6 firmware running
+ * inside the modem, Xiaomi Mi 8 Lite) requesting channel stats makes
+ * the WLAN firmware fatally assert (err_qdi.c EX:wlan_process,
+ * RT:2072) a fixed ~87ms after tuning to every scan channel - active
+ * or passive, any band, any board data. Reading the MAC cycle
+ * counters for the stats appears to hit a dead hardware block on
+ * this platform (rx_clear_count was already known to read frozen).
+ * Bisected at runtime via WMI flag knobs: clearing this single flag
+ * makes scans complete reliably. Only channel survey data is lost.
+ */
+ if (!QCA_REV_WCN3990(ar))
+ arg->scan_ctrl_flags |= WMI_SCAN_CHAN_STAT_EVENT;
arg->n_bssids = 1;
arg->bssids[0].bssid = "\xFF\xFF\xFF\xFF\xFF\xFF";
}
@@ -0,0 +1,904 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] clk: qcom: add SDM660 CPU (OSM) clock driver
CPU frequency scaling driver for SDM660. Programs the OSM (LUT, cycle
counters, boost/DCVS FSMs, PLL/RCGR config, APM, ITM handoff, sequencer
microcode, mem-acc/APM voltage, cluster PLLs) then enables it; cpufreq-dt
scales via the cpu OPP tables. The cluster PLL reconfig parks the mux on
GPLL0 first to avoid hanging the (little) cluster that runs from it.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
diff --git a/drivers/clk/qcom/clk-cpu-sdm660.c b/drivers/clk/qcom/clk-cpu-sdm660.c
new file mode 100644
index 0000000..d89c18c
--- /dev/null
+++ b/drivers/clk/qcom/clk-cpu-sdm660.c
@@ -0,0 +1,855 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * SDM660 CPU (OSM) clock driver for mainline Linux.
+ *
+ * The SDM660 scales its two Kryo-260 CPU clusters with the OSM (Operating
+ * State Manager) hardware, like the SDM845 - but unlike the SDM845 the
+ * SDM660 bootloader does NOT program the OSM: it leaves ENABLE=0 and the
+ * frequency/voltage LUT empty and runs the cores from a fixed bypass source
+ * (this is why mainline has no cpufreq on SDM660). On Android the secure
+ * world (TrustZone) programs the OSM sequencer/config; on mainline there is
+ * no TZ doing that, so this driver does the full "secure_init" setup itself:
+ *
+ * per cluster: program the freq/voltage LUT from the DT speedbin tables,
+ * program the PLL/RCGR config words and the APM voltage switch;
+ * once: program the ITM handoff and load the OSM sequencer microcode;
+ * then: enable the OSM. From then on cpufreq only writes a LUT index
+ * into DCVS_PERF_STATE_DESIRED and the OSM drives PLL, mux and
+ * voltage on its own.
+ *
+ * No ACD, LLM, trace or FSM optimisations (all optional on SDM660), open-loop
+ * voltages (no CPR3). Reverse-engineered and reduced from the LineageOS
+ * clk-cpu-osm-660 driver.
+ *
+ * Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
+ */
+
+#include <linux/bitfield.h>
+#include <linux/clk.h>
+#include <linux/clk-provider.h>
+#include <linux/delay.h>
+#include <linux/firmware/qcom/qcom_scm.h>
+#include <linux/io.h>
+#include <linux/module.h>
+#include <linux/of.h>
+#include <linux/platform_device.h>
+#include <linux/slab.h>
+
+/* OSM register offsets (relative to each cluster's OSM base) */
+#define ENABLE_REG 0x1004
+#define SPM_CC_CTRL 0x1028
+#define SEQ_MEM_ADDR 0x500
+#define SEQ_CFG_BR_ADDR 0x170
+#define INDEX_REG 0x1150
+#define FREQ_REG 0x1154
+#define VOLT_REG 0x1158
+#define OVERRIDE_REG 0x115c
+#define SPARE_REG 0x1164
+#define OSM_REG_SIZE 32
+#define OSM_TABLE_SIZE 40
+#define DCVS_PERF_STATE_DESIRED_REG 0x1f10
+#define SEQ_REG(n) (0x300 + (n) * 4)
+
+/* Voltage word: bits[21:16] = virtual corner, bits[11:0] = open-loop mV */
+#define OSM_VC_MASK GENMASK(21, 16)
+#define OSM_OLV_MASK GENMASK(11, 0)
+
+/* PLL / RCGR config words programmed into the OSM sequencer registers */
+#define PLL_MIN_LVAL 43
+#define PLL_POST_DIV1 0x1f
+#define PLL_POST_DIV2 0x11f
+#define GPLL_SEL 0x400
+#define PLL_EARLY_SEL 0x500
+#define PLL_MAIN_SEL 0x300
+#define RCG_UPDATE 0x3
+#define RCG_UPDATE_SUCCESS 0x2
+
+/* APM (Array Power Mux) switch words */
+#define APM_MX_MODE 0
+#define APM_APC_MODE BIT(1)
+#define APM_MODE_SWITCH_MASK (FIELD_PREP(GENMASK(4, 2), 7) | \
+ FIELD_PREP(GENMASK(1, 0), 3))
+#define APM_MX_MODE_VAL 0
+#define APM_APC_MODE_VAL 0x3
+
+/* ITM handoff */
+#define ITM_CL0_DISABLE_CL1_ENABLED 0x2
+#define ITM_CL0_ENABLED_CL1_DISABLE 0x1
+
+/* Cluster PLL (relative to each cluster's PLL base) */
+#define PLL_MODE 0x0
+#define PLL_L_VAL 0x4
+#define PLL_USER_CTRL 0xc
+#define PLL_CONFIG_CTL_LO 0x10
+#define PLL_WAIT_LOCK_TIME_US 10
+#define PLL_SETUP_L_VAL 0x20
+#define PLL_SETUP_USER_CTRL 0x01000008
+#define PLL_SETUP_CONFIG_CTL 0x20004aa8
+
+/* DCVS boost/safe FSMs (relative to OSM base) */
+#define PDN_FSM_CTRL_REG 0x1070
+#define CC_BOOST_EN_MASK BIT(0)
+#define CC_BOOST_TIMER_REG0 0x1074
+#define CC_BOOST_TIMER_REG1 0x1078
+#define CC_BOOST_TIMER_REG2 0x107c
+#define DCVS_BOOST_EN_MASK BIT(2)
+#define DCVS_BOOST_TIMER_REG0 0x1084
+#define DCVS_BOOST_TIMER_REG1 0x1088
+#define DCVS_BOOST_TIMER_REG2 0x108c
+#define PS_BOOST_EN_MASK BIT(1)
+#define PS_BOOST_TIMER_REG0 0x1094
+#define PS_BOOST_TIMER_REG1 0x1098
+#define PS_BOOST_TIMER_REG2 0x109c
+#define BOOST_PROG_SYNC_DELAY_REG 0x10a0
+#define OSM_PLL_SW_OVERRIDE_EN 0x10c0
+#define PLL_SW_OVERRIDE_DROOP_EN BIT(0)
+#define PLL_WAIT_LOCK_TIME_NS 10000
+#define SAFE_FREQ_WAIT_NS 5000
+#define DEXT_DECREMENT_WAIT_NS 1000
+
+/* Cycle counter */
+#define OSM_CYCLE_COUNTER_CTRL_REG 0x1f00
+#define OSM_CYCLE_COUNTER_USE_XO_EDGE BIT(8)
+
+/* clocks (Hz) */
+#define OSM_CLK_RATE 200000000
+#define XO_CLK_RATE 19200000
+
+#define OSM_CORE_TABLE_SIZE 0x2000
+#define NUM_CLUSTERS 2
+
+/* nsec -> OSM clock cycles (osm_clk_rate * nsec / 1e9) */
+static inline u32 osm_count_ns(u64 nsec)
+{
+ u64 t = (u64)OSM_CLK_RATE * nsec;
+
+ do_div(t, 1000000000);
+ return t;
+}
+
+/*
+ * OSM sequencer microcode. This is the "program" the OSM executes to perform
+ * the PLL/mux/voltage transitions; without it ENABLE=1 does nothing. Verbatim
+ * from the downstream clk-cpu-osm-660 (identical for pwrcl and perfcl).
+ */
+static const u32 seq_instr[] = {
+ 0xc2005000, 0x2c9e3b21, 0xc0ab2cdc, 0xc2882525, 0x359dc491, 0x700a500b,
+ 0x5001aefc, 0xaefd7000, 0x390938c8, 0xcb44c833, 0xce56cd54, 0x341336e0,
+ 0xa4baadba, 0xb480a493, 0x10004000, 0x70005001, 0x1000500c, 0xc792c5a1,
+ 0x501625e1, 0x3da335a2, 0x50170006, 0x50150006, 0x1000c633, 0x1000acb3,
+ 0xc422acb4, 0xaefc1000, 0x700a500b, 0x70005001, 0x5010aefd, 0x5012700b,
+ 0xad41700c, 0x84e5adb9, 0xb3808566, 0x239b0003, 0x856484e3, 0xb9800007,
+ 0x2bad0003, 0xac3aa20b, 0x0003181b, 0x0003bb40, 0xa30d239b, 0x500c181b,
+ 0x5011500f, 0x181b3413, 0x853984b9, 0x0003bd80, 0xa0012ba4, 0x72050803,
+ 0x500e1000, 0x500c1000, 0x1c011c0a, 0x3b181c06, 0x1c073b43, 0x1c061000,
+ 0x1c073983, 0x1c02500c, 0x10001c0a, 0x70015002, 0x81031000, 0x70025003,
+ 0x70035004, 0x3b441000, 0x81553985, 0x70025003, 0x50054003, 0xa1467009,
+ 0x0003b1c0, 0x4005238b, 0x835a1000, 0x855c84db, 0x1000a51f, 0x84de835d,
+ 0xa52c855c, 0x50061000, 0x39cd3a4c, 0x3ad03a8f, 0x10004006, 0x70065007,
+ 0xa00f2c12, 0x08034007, 0xaefc7205, 0xaefd700d, 0xa9641000, 0x40071c1a,
+ 0x700daefc, 0x1000aefd, 0x70065007, 0x50101c16, 0x40075012, 0x700daefc,
+ 0x2411aefd, 0xa8211000, 0x0803a00f, 0x500c7005, 0x1c1591e0, 0x500f5014,
+ 0x10005011, 0x500c2bd4, 0x0803a00f, 0x10007205, 0xa00fa9d1, 0x0803a821,
+ 0xa9d07005, 0x91e0500c, 0x500f1c15, 0x10005011, 0x1c162bce, 0x50125010,
+ 0xa022a82a, 0x70050803, 0x1c1591df, 0x5011500f, 0x5014500c, 0x0803a00f,
+ 0x10007205, 0x501391a4, 0x22172217, 0x70075008, 0xa9634008, 0x1c1a0006,
+ 0x70085009, 0x10004009, 0x00008ed9, 0x3e05c8dd, 0x1c033604, 0xabaf1000,
+ 0x856284e1, 0x0003bb80, 0x1000239f, 0x0803a037, 0x10007205, 0x8dc61000,
+ 0x38a71c2a, 0x1c2a8dc4, 0x100038a6, 0x1c2a8dc5, 0x8dc73867, 0x38681c2a,
+ 0x8c491000, 0x8d4b8cca, 0x10001c00, 0x8ccd8c4c, 0x1c008d4e, 0x8c4f1000,
+ 0x8d518cd0, 0x10001c00, 0xa759a79a, 0x1000a718, 0xbf80af9b, 0x00001000,
+};
+
+static const u32 seq_br_instr[] = {
+ 0x00000248, 0x0000020e, 0x0000021c, 0x000000f6, 0x00000112, 0x0000011c,
+ 0x000000e4, 0x000000ea, 0x000000c6, 0x000000d6, 0x00000126, 0x00000108,
+ 0x00000184, 0x000001a8, 0x000001b0, 0x00000134, 0x00000158, 0x0000016e,
+ 0x0000014a, 0x000000c2, 0x00000190, 0x000001d2, 0x000001cc, 0x000001d4,
+ 0x000001e8, 0x00000000, 0x000001f6, 0x00000032, 0x00000066, 0x000000b0,
+ 0x000000a6, 0x000001fc, 0x0000003c, 0x00000044, 0x0000005c, 0x00000060,
+ 0x00000204, 0x00000030, 0x0000022a, 0x00000234, 0x0000023e, 0x00000000,
+ 0x00000250, 0x00000000, 0x00000000, 0x0000009a, 0x0000020c,
+};
+
+struct osm_entry {
+ u32 freq_data;
+ u32 override_data;
+ u32 spare_data;
+ u32 virtual_corner; /* 0-based */
+ u32 open_loop_volt; /* mV */
+ unsigned long frequency;
+};
+
+struct sdm660_osm_clk {
+ struct clk_hw hw;
+ void __iomem *base; /* this cluster's OSM base (read) */
+ phys_addr_t phys; /* this cluster's OSM base (phys, for SCM) */
+ void __iomem *pll_base; /* this cluster's HFPLL base */
+ void __iomem *rcgr_base; /* this cluster's APCS RCGR mux */
+ /* per-cluster config addresses (physical values fed to the OSM) */
+ u32 l_val_base;
+ u32 apcs_pll_user_ctl;
+ u32 apcs_cfg_rcgr;
+ u32 apcs_cmd_rcgr;
+ u32 apcs_itm_present;
+ u32 apm_mode_ctl;
+ u32 apm_ctrl_status;
+ u32 itm_handoff; /* ITM_CL0_* value for this cluster */
+ struct osm_entry table[OSM_TABLE_SIZE];
+ int num_entries;
+};
+
+#define to_osm_clk(_hw) container_of(_hw, struct sdm660_osm_clk, hw)
+
+/*
+ * The OSM register block has two write-protection domains on this SoC,
+ * confirmed live via /dev/mem: control/LUT registers at offset >= 0x1000
+ * (ENABLE, the freq/volt LUT, the boost/DCVS FSMs, DCVS_PERF_STATE_DESIRED)
+ * accept ordinary non-secure writes, but the whole sequencer region below
+ * that - the branch table at 0x170 and the SEQ_MEM microcode / SEQ_REG
+ * parameter area at 0x300-0x5ff - is XPU-protected: a plain writel from the
+ * kernel is silently dropped, leaving the sequencer empty so the OSM enables
+ * but never transitions. Those writes must go through the secure world, which
+ * is exactly what the downstream driver does (scm_io_write) - the TrustZone on
+ * this device implements SCM_IO_WRITE (the OSM is programmed this way under
+ * Android). So route < 0x1000 through qcom_scm_io_writel and the rest direct.
+ */
+#define OSM_SECURE_LIMIT 0x1000
+
+static void osm_w(struct sdm660_osm_clk *c, u32 val, u32 off)
+{
+ /*
+ * r54 diagnostic: previously off < OSM_SECURE_LIMIT was routed through
+ * qcom_scm_io_writel, which is a silent no-op on this SoC (SCM readback
+ * returned 0). Write everything directly to test whether a plain kernel
+ * writel to the sequencer region actually lands (checked via SCM
+ * readback in probe: reg21 should read back PLL_MIN_LVAL if it does).
+ */
+ writel_relaxed(val, c->base + off);
+}
+
+static inline u32 osm_r(struct sdm660_osm_clk *c, u32 off)
+{
+ return readl_relaxed(c->base + off);
+}
+
+/* --- clk_ops: with the OSM running, set_rate is a single index vote --- */
+
+static int osm_search(struct sdm660_osm_clk *c, unsigned long rate)
+{
+ int i;
+
+ for (i = 0; i < c->num_entries; i++)
+ if (c->table[i].frequency == rate)
+ return i;
+ return -EINVAL;
+}
+
+static int sdm660_osm_set_rate(struct clk_hw *hw, unsigned long rate,
+ unsigned long parent_rate)
+{
+ struct sdm660_osm_clk *c = to_osm_clk(hw);
+ int index = osm_search(c, rate);
+
+ if (index < 0)
+ return index;
+ osm_w(c, index, DCVS_PERF_STATE_DESIRED_REG);
+ wmb(); /* ensure the vote reaches the OSM */
+ return 0;
+}
+
+static unsigned long sdm660_osm_recalc_rate(struct clk_hw *hw,
+ unsigned long parent_rate)
+{
+ struct sdm660_osm_clk *c = to_osm_clk(hw);
+ u32 index = osm_r(c, DCVS_PERF_STATE_DESIRED_REG);
+
+ if (index >= c->num_entries)
+ index = c->num_entries - 1;
+ return c->table[index].frequency;
+}
+
+static int sdm660_osm_determine_rate(struct clk_hw *hw,
+ struct clk_rate_request *req)
+{
+ struct sdm660_osm_clk *c = to_osm_clk(hw);
+ unsigned long best = c->table[0].frequency;
+ int i;
+
+ for (i = 0; i < c->num_entries; i++)
+ if (c->table[i].frequency <= req->rate &&
+ c->table[i].frequency > best)
+ best = c->table[i].frequency;
+ req->rate = best;
+ return 0;
+}
+
+static const struct clk_ops sdm660_osm_ops = {
+ .set_rate = sdm660_osm_set_rate,
+ .recalc_rate = sdm660_osm_recalc_rate,
+ .determine_rate = sdm660_osm_determine_rate,
+};
+
+/* --- one-time OSM programming --- */
+
+static void osm_setup_lut(struct sdm660_osm_clk *c)
+{
+ int i;
+
+ for (i = 0; i < OSM_TABLE_SIZE; i++) {
+ u32 freq = 0, volt = 0, override = 0, spare = 0;
+ u32 off = i * OSM_REG_SIZE;
+
+ if (i < c->num_entries) {
+ freq = c->table[i].freq_data;
+ volt = FIELD_PREP(OSM_VC_MASK, c->table[i].virtual_corner) |
+ FIELD_PREP(OSM_OLV_MASK, c->table[i].open_loop_volt);
+ override = c->table[i].override_data;
+ spare = c->table[i].spare_data;
+ }
+ osm_w(c, i, INDEX_REG + off);
+ osm_w(c, freq, FREQ_REG + off);
+ osm_w(c, volt, VOLT_REG + off);
+ osm_w(c, override, OVERRIDE_REG + off);
+ osm_w(c, spare, SPARE_REG + off);
+ }
+ wmb();
+}
+
+static void osm_program_apm(struct sdm660_osm_clk *c)
+{
+ osm_w(c, c->apm_mode_ctl, SEQ_REG(2));
+ osm_w(c, c->apm_ctrl_status, SEQ_REG(3));
+ osm_w(c, APM_MX_MODE, SEQ_REG(77));
+ osm_w(c, APM_MX_MODE_VAL, SEQ_REG(78));
+ osm_w(c, APM_MODE_SWITCH_MASK, SEQ_REG(79));
+ osm_w(c, APM_APC_MODE, SEQ_REG(80));
+ osm_w(c, APM_APC_MODE_VAL, SEQ_REG(81));
+}
+
+/* program the PLL/RCGR config + APM the OSM sequencer needs (secure_init) */
+static void osm_program_config(struct sdm660_osm_clk *c)
+{
+ osm_w(c, FIELD_PREP(GENMASK(23, 16), 0xf), SPM_CC_CTRL);
+ osm_w(c, c->l_val_base, SEQ_REG(0));
+ osm_w(c, PLL_MIN_LVAL, SEQ_REG(21));
+ osm_w(c, c->apcs_pll_user_ctl, SEQ_REG(18));
+ osm_w(c, PLL_POST_DIV2, SEQ_REG(19));
+ osm_w(c, PLL_POST_DIV1, SEQ_REG(29));
+
+ osm_program_apm(c);
+
+ osm_w(c, c->apcs_cfg_rcgr, SEQ_REG(16));
+ osm_w(c, c->apcs_cmd_rcgr, SEQ_REG(33));
+ osm_w(c, RCG_UPDATE, SEQ_REG(34));
+ osm_w(c, GPLL_SEL, SEQ_REG(17));
+ osm_w(c, PLL_EARLY_SEL, SEQ_REG(82));
+ osm_w(c, PLL_MAIN_SEL, SEQ_REG(83));
+ osm_w(c, RCG_UPDATE_SUCCESS, SEQ_REG(84));
+ osm_w(c, RCG_UPDATE, SEQ_REG(85));
+ wmb();
+}
+
+/*
+ * MEM ACC + APM voltage-crossover sequencer setup. The sequencer consults
+ * these while ramping voltage during a DCVS transition; without them it stalls
+ * after switching the RCGR to the safe source (seen live: RCGR moves but the
+ * PLL never ramps). Because this driver runs every corner at the max CPR
+ * ceiling (see osm_get_lut) the APM always stays on APCC, so the threshold
+ * corner is 0 and the crossover never actually triggers.
+ */
+#define MEM_ACC_APM_READ_MASK 0xff
+#define APM_THRESHOLD_VC 0
+#define APM_CROSSOVER_VC 3
+#define OSM_SEQ_MINUS_ONE 0xff
+
+static void osm_program_mem_acc(struct sdm660_osm_clk *c)
+{
+ osm_w(c, 1, SEQ_REG(51));
+ osm_w(c, 2, SEQ_REG(52));
+ osm_w(c, 3, SEQ_REG(53));
+ osm_w(c, 4, SEQ_REG(54));
+ osm_w(c, MEM_ACC_APM_READ_MASK, SEQ_REG(59));
+ osm_w(c, 0, SEQ_REG(55));
+ osm_w(c, 1, SEQ_REG(56));
+ osm_w(c, 0, SEQ_REG(57));
+ osm_w(c, 1, SEQ_REG(58));
+ osm_w(c, c->phys + SEQ_REG(28), SEQ_REG(49));
+ wmb();
+}
+
+static void osm_program_apm_vc(struct sdm660_osm_clk *c)
+{
+ osm_w(c, APM_THRESHOLD_VC, SEQ_REG(1));
+ osm_w(c, APM_CROSSOVER_VC, SEQ_REG(72));
+ osm_w(c, c->phys + SEQ_REG(1), SEQ_REG(8));
+ osm_w(c, APM_THRESHOLD_VC, SEQ_REG(15));
+ osm_w(c, OSM_SEQ_MINUS_ONE, SEQ_REG(31));
+ osm_w(c, 0x3b | (APM_THRESHOLD_VC << 6), SEQ_REG(73));
+ osm_w(c, 0x39 | (APM_THRESHOLD_VC << 6), SEQ_REG(76));
+ wmb();
+}
+
+static void osm_program_handoff(struct sdm660_osm_clk *c)
+{
+ osm_w(c, c->apcs_itm_present, SEQ_REG(37));
+ osm_w(c, 0, SEQ_REG(38));
+ osm_w(c, c->itm_handoff, SEQ_REG(39));
+ wmb();
+}
+
+static void osm_load_sequencer(struct sdm660_osm_clk *c)
+{
+ int i;
+
+ for (i = 0; i < ARRAY_SIZE(seq_instr); i++)
+ osm_w(c, seq_instr[i], SEQ_MEM_ADDR + i * 4);
+ for (i = 0; i < ARRAY_SIZE(seq_br_instr); i++)
+ osm_w(c, seq_br_instr[i], SEQ_CFG_BR_ADDR + i * 4);
+ wmb();
+}
+
+/* OSM-to-XO cycle counter, needed by the boost/DCVS FSMs for their timers */
+static void osm_setup_cycle_counters(struct sdm660_osm_clk *c)
+{
+ u32 ratio = OSM_CLK_RATE / XO_CLK_RATE;
+ u32 val = BIT(0) | FIELD_PREP(GENMASK(5, 1), ratio - 1) |
+ OSM_CYCLE_COUNTER_USE_XO_EDGE;
+
+ osm_w(c, val, OSM_CYCLE_COUNTER_CTRL_REG);
+ wmb();
+}
+
+/*
+ * Program the boost (frequency up) and safe/DCVS (frequency down) FSMs. These
+ * are what actually carry out a DCVS request: without them the OSM latches the
+ * desired index but never drives the PLL/mux. boost + safe + PS are enabled
+ * (the wfx/pc/droop FSMs are power-collapse/di-dt droop refinements, optional).
+ */
+static void osm_setup_fsms(struct sdm660_osm_clk *c)
+{
+ u32 val;
+
+ /* boost FSM (ramp up) */
+ val = osm_r(c, PDN_FSM_CTRL_REG) | CC_BOOST_EN_MASK;
+ osm_w(c, val, PDN_FSM_CTRL_REG);
+
+ val = osm_r(c, CC_BOOST_TIMER_REG0);
+ val |= FIELD_PREP(GENMASK(15, 0), osm_count_ns(PLL_WAIT_LOCK_TIME_NS));
+ val |= FIELD_PREP(GENMASK(31, 16), osm_count_ns(SAFE_FREQ_WAIT_NS));
+ osm_w(c, val, CC_BOOST_TIMER_REG0);
+
+ val = osm_r(c, CC_BOOST_TIMER_REG1);
+ val |= FIELD_PREP(GENMASK(15, 0), osm_count_ns(PLL_WAIT_LOCK_TIME_NS));
+ val |= FIELD_PREP(GENMASK(31, 16), osm_count_ns(PLL_WAIT_LOCK_TIME_NS));
+ osm_w(c, val, CC_BOOST_TIMER_REG1);
+
+ val = osm_r(c, CC_BOOST_TIMER_REG2);
+ val |= FIELD_PREP(GENMASK(15, 0), osm_count_ns(DEXT_DECREMENT_WAIT_NS));
+ osm_w(c, val, CC_BOOST_TIMER_REG2);
+
+ /* safe / DCVS boost FSM (ramp down) */
+ val = osm_r(c, PDN_FSM_CTRL_REG) | DCVS_BOOST_EN_MASK;
+ osm_w(c, val, PDN_FSM_CTRL_REG);
+
+ val = osm_r(c, DCVS_BOOST_TIMER_REG0);
+ val |= FIELD_PREP(GENMASK(15, 0), osm_count_ns(PLL_WAIT_LOCK_TIME_NS));
+ val |= FIELD_PREP(GENMASK(31, 16), osm_count_ns(SAFE_FREQ_WAIT_NS));
+ osm_w(c, val, DCVS_BOOST_TIMER_REG0);
+
+ val = osm_r(c, DCVS_BOOST_TIMER_REG1);
+ val |= FIELD_PREP(GENMASK(15, 0), osm_count_ns(PLL_WAIT_LOCK_TIME_NS));
+ val |= FIELD_PREP(GENMASK(31, 16), osm_count_ns(PLL_WAIT_LOCK_TIME_NS));
+ osm_w(c, val, DCVS_BOOST_TIMER_REG1);
+
+ val = osm_r(c, DCVS_BOOST_TIMER_REG2);
+ val |= FIELD_PREP(GENMASK(15, 0), osm_count_ns(DEXT_DECREMENT_WAIT_NS));
+ osm_w(c, val, DCVS_BOOST_TIMER_REG2);
+
+ /*
+ * PS (perf-state) FSM. r56: the working downstream enables this too and
+ * it is the FSM that carries out a perf-state (DCVS_PERF_STATE_DESIRED)
+ * transition - without it the OSM latched the desired index but never
+ * drove the PLL/mux (the r49..r55 symptom).
+ */
+ val = osm_r(c, PDN_FSM_CTRL_REG) | PS_BOOST_EN_MASK;
+ osm_w(c, val, PDN_FSM_CTRL_REG);
+
+ val = osm_r(c, PS_BOOST_TIMER_REG0);
+ val |= FIELD_PREP(GENMASK(15, 0), osm_count_ns(PLL_WAIT_LOCK_TIME_NS));
+ val |= FIELD_PREP(GENMASK(31, 16), osm_count_ns(SAFE_FREQ_WAIT_NS));
+ osm_w(c, val, PS_BOOST_TIMER_REG0);
+
+ val = osm_r(c, PS_BOOST_TIMER_REG1);
+ val |= FIELD_PREP(GENMASK(15, 0), osm_count_ns(PLL_WAIT_LOCK_TIME_NS));
+ val |= FIELD_PREP(GENMASK(31, 16), osm_count_ns(PLL_WAIT_LOCK_TIME_NS));
+ osm_w(c, val, PS_BOOST_TIMER_REG1);
+
+ val = osm_r(c, PS_BOOST_TIMER_REG2);
+ val |= FIELD_PREP(GENMASK(15, 0), osm_count_ns(DEXT_DECREMENT_WAIT_NS));
+ osm_w(c, val, PS_BOOST_TIMER_REG2);
+
+ osm_w(c, 0x5, BOOST_PROG_SYNC_DELAY_REG);
+
+ val = osm_r(c, OSM_PLL_SW_OVERRIDE_EN) | PLL_SW_OVERRIDE_DROOP_EN;
+ osm_w(c, val, OSM_PLL_SW_OVERRIDE_EN);
+ wmb();
+}
+
+/* APCS RCGR mux: cmd at +0x0, cfg at +0x4; SRC_SEL is cfg[10:8] */
+#define RCGR_CMD 0x0
+#define RCGR_CFG 0x4
+#define RCGR_UPDATE_BIT BIT(0)
+#define RCGR_SRC_MASK GENMASK(10, 8)
+#define RCGR_SRC_GPLL0 4 /* GPLL0 (safe bypass) */
+
+static void rcgr_do_update(struct sdm660_osm_clk *c)
+{
+ int i;
+
+ writel_relaxed(readl_relaxed(c->rcgr_base + RCGR_CMD) | RCGR_UPDATE_BIT,
+ c->rcgr_base + RCGR_CMD);
+ for (i = 0; i < 200; i++) {
+ if (!(readl_relaxed(c->rcgr_base + RCGR_CMD) & RCGR_UPDATE_BIT))
+ break;
+ udelay(1);
+ }
+}
+
+/*
+ * Reconfigure the cluster HFPLL so the OSM can drive it. Reconfiguring means
+ * briefly powering the PLL down (MODE=0), which hangs the cluster if it is
+ * currently clocked from that PLL - and the little cluster (which runs the
+ * kernel) is. So first switch the cluster's RCGR mux to GPLL0, reconfigure the
+ * PLL, then switch it back. Verified live: without the bypass this hangs.
+ */
+static void __maybe_unused osm_setup_cluster_pll(struct sdm660_osm_clk *c)
+{
+ u32 cfg = readl_relaxed(c->rcgr_base + RCGR_CFG);
+
+ /* park the cluster on GPLL0 */
+ writel_relaxed((cfg & ~RCGR_SRC_MASK) |
+ FIELD_PREP(RCGR_SRC_MASK, RCGR_SRC_GPLL0),
+ c->rcgr_base + RCGR_CFG);
+ rcgr_do_update(c);
+ udelay(1);
+
+ writel_relaxed(0x0, c->pll_base + PLL_MODE);
+ writel_relaxed(PLL_SETUP_L_VAL, c->pll_base + PLL_L_VAL);
+ writel_relaxed(PLL_SETUP_USER_CTRL, c->pll_base + PLL_USER_CTRL);
+ writel_relaxed(PLL_SETUP_CONFIG_CTL, c->pll_base + PLL_CONFIG_CTL_LO);
+ writel_relaxed(0x2, c->pll_base + PLL_MODE);
+ wmb();
+ udelay(PLL_WAIT_LOCK_TIME_US);
+ writel_relaxed(0x6, c->pll_base + PLL_MODE);
+ wmb();
+ usleep_range(50, 75);
+ writel_relaxed(0x7, c->pll_base + PLL_MODE);
+ wmb();
+
+ /* restore the original mux selection */
+ writel_relaxed(cfg, c->rcgr_base + RCGR_CFG);
+ rcgr_do_update(c);
+}
+
+static void __maybe_unused osm_enable(struct sdm660_osm_clk *c)
+{
+ udelay(5);
+ osm_w(c, 1, ENABLE_REG);
+ wmb();
+ udelay(5);
+}
+
+/* --- device tree LUT parsing --- */
+
+static int osm_get_lut(struct device *dev, struct sdm660_osm_clk *c,
+ const char *prop, const u32 *ceil_uv, int ceil_cnt)
+{
+ struct device_node *np = dev->of_node;
+ int len, rows, i, j;
+ u32 vmax = 0;
+
+ len = of_property_count_u32_elems(np, prop);
+ if (len < 0)
+ return dev_err_probe(dev, len, "missing %s\n", prop);
+ rows = len / 5;
+ if (rows > OSM_TABLE_SIZE)
+ rows = OSM_TABLE_SIZE;
+
+ /*
+ * First cut: run every corner at the highest CPR ceiling. The
+ * per-corner virtual-corner -> voltage mapping goes through the CPR3
+ * fuse/fmax tables which this driver does not model; using the max
+ * ceiling for all entries over-volts the low frequencies (wastes a
+ * little power) but guarantees no frequency is ever under-volted.
+ * Proper per-corner open-loop scaling is a later optimisation.
+ */
+ for (j = 0; j < ceil_cnt; j++)
+ if (ceil_uv[j] > vmax)
+ vmax = ceil_uv[j];
+
+ for (i = 0; i < rows; i++) {
+ u32 cell[5];
+
+ for (j = 0; j < 5; j++)
+ of_property_read_u32_index(np, prop, i * 5 + j, &cell[j]);
+ /* [0]freq [1]freq_data [2]override [3]virtual_corner(1-based) [4]spare */
+ c->table[i].frequency = cell[0];
+ c->table[i].freq_data = cell[1];
+ c->table[i].override_data = cell[2];
+ c->table[i].virtual_corner = cell[3] - 1;
+ c->table[i].spare_data = cell[4];
+ c->table[i].open_loop_volt = vmax / 1000;
+ }
+ c->num_entries = rows;
+ return 0;
+}
+
+static struct clk_hw *osm_hws[NUM_CLUSTERS];
+
+static struct clk_hw *osm_of_get(struct of_phandle_args *args, void *data)
+{
+ unsigned int idx = args->args[0];
+
+ return idx < NUM_CLUSTERS ? osm_hws[idx] : ERR_PTR(-EINVAL);
+}
+
+struct cluster_cfg {
+ const char *name;
+ const char *lut_prop;
+ const char *ceil_prop;
+ u32 base_off;
+ u32 pll_phys;
+ u32 l_val_base, pll_user_ctl, cfg_rcgr, cmd_rcgr, itm_present;
+ u32 apm_mode_ctl, apm_ctrl_status, itm_handoff;
+};
+
+/* physical addresses come from the SDM660 APCS layout (fixed for this SoC) */
+static const struct cluster_cfg cluster_cfgs[NUM_CLUSTERS] = {
+ { /* cluster 0: power (little) cpu0-3 */
+ .name = "pwrcl_clk", .base_off = 0,
+ .lut_prop = "qcom,pwrcl-speedbin0-v0",
+ .ceil_prop = "qcom,pwrcl-voltage-ceiling",
+ .pll_phys = 0x17916000,
+ .l_val_base = 0x17916004, .pll_user_ctl = 0x1791600c,
+ .cfg_rcgr = 0x17911054, .cmd_rcgr = 0x17911050,
+ .itm_present = 0x179d143c,
+ .apm_mode_ctl = 0x179d0004, .apm_ctrl_status = 0x179d000c,
+ .itm_handoff = ITM_CL0_DISABLE_CL1_ENABLED,
+ },
+ { /* cluster 1: performance (big) cpu4-7 */
+ .name = "perfcl_clk", .base_off = OSM_CORE_TABLE_SIZE,
+ .lut_prop = "qcom,perfcl-speedbin1-v0",
+ .ceil_prop = "qcom,perfcl-voltage-ceiling",
+ .pll_phys = 0x17816000,
+ .l_val_base = 0x17816004, .pll_user_ctl = 0x1781600c,
+ .cfg_rcgr = 0x17811054, .cmd_rcgr = 0x17811050,
+ .itm_present = 0x179d143c,
+ .apm_mode_ctl = 0x179d0010, .apm_ctrl_status = 0x179d0018,
+ .itm_handoff = ITM_CL0_ENABLED_CL1_DISABLE,
+ },
+};
+
+static int sdm660_osm_probe(struct platform_device *pdev)
+{
+ struct device *dev = &pdev->dev;
+ struct sdm660_osm_clk *cl[NUM_CLUSTERS];
+ void __iomem *osm_base;
+ struct resource *osm_res;
+ struct clk *aux;
+ int i, ret;
+
+ /*
+ * The sequencer setup writes go through the secure monitor
+ * (qcom_scm_io_writel). This clock controller can probe before the SCM
+ * firmware driver is up, in which case those writes would be dropped and
+ * the OSM would enable with an empty sequencer - so defer until SCM is
+ * available.
+ */
+ if (!qcom_scm_is_available())
+ return dev_err_probe(dev, -EPROBE_DEFER, "waiting for qcom_scm\n");
+
+ /* GPLL0/aux feeds the OSM sequencer clock; keep it on */
+ aux = devm_clk_get_enabled(dev, "aux");
+ if (IS_ERR(aux))
+ return dev_err_probe(dev, PTR_ERR(aux), "no aux clock\n");
+
+ osm_res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "osm");
+ osm_base = devm_ioremap_resource(dev, osm_res);
+ if (IS_ERR(osm_base))
+ return PTR_ERR(osm_base);
+
+ for (i = 0; i < NUM_CLUSTERS; i++) {
+ const struct cluster_cfg *cfg = &cluster_cfgs[i];
+ u32 ceil[8];
+ int ceil_cnt;
+
+ cl[i] = devm_kzalloc(dev, sizeof(*cl[i]), GFP_KERNEL);
+ if (!cl[i])
+ return -ENOMEM;
+
+ cl[i]->base = osm_base + cfg->base_off;
+ cl[i]->phys = osm_res->start + cfg->base_off;
+ cl[i]->pll_base = devm_ioremap(dev, cfg->pll_phys, 0x100);
+ if (!cl[i]->pll_base)
+ return -ENOMEM;
+ cl[i]->rcgr_base = devm_ioremap(dev, cfg->cmd_rcgr, 0x10);
+ if (!cl[i]->rcgr_base)
+ return -ENOMEM;
+ cl[i]->l_val_base = cfg->l_val_base;
+ cl[i]->apcs_pll_user_ctl = cfg->pll_user_ctl;
+ cl[i]->apcs_cfg_rcgr = cfg->cfg_rcgr;
+ cl[i]->apcs_cmd_rcgr = cfg->cmd_rcgr;
+ cl[i]->apcs_itm_present = cfg->itm_present;
+ cl[i]->apm_mode_ctl = cfg->apm_mode_ctl;
+ cl[i]->apm_ctrl_status = cfg->apm_ctrl_status;
+ cl[i]->itm_handoff = cfg->itm_handoff;
+
+ ceil_cnt = of_property_read_variable_u32_array(dev->of_node,
+ cfg->ceil_prop, ceil, 1, ARRAY_SIZE(ceil));
+ if (ceil_cnt < 0)
+ ceil_cnt = 0;
+
+ ret = osm_get_lut(dev, cl[i], cfg->lut_prop, ceil, ceil_cnt);
+ if (ret)
+ return ret;
+
+ /* order mirrors the downstream probe (secure_init path) */
+ osm_setup_cycle_counters(cl[i]);
+ osm_setup_lut(cl[i]);
+ osm_setup_fsms(cl[i]);
+ osm_program_config(cl[i]);
+ }
+
+ /* handoff, sequencer microcode and voltage setup (both clusters) */
+ for (i = 0; i < NUM_CLUSTERS; i++) {
+ osm_program_handoff(cl[i]);
+ osm_load_sequencer(cl[i]);
+ osm_program_mem_acc(cl[i]);
+ osm_program_apm_vc(cl[i]);
+ }
+
+ /* prepare the cluster PLLs, enable the OSM and register the clocks */
+ for (i = 0; i < NUM_CLUSTERS; i++) {
+ struct clk_init_data init = {
+ .name = cluster_cfgs[i].name,
+ .ops = &sdm660_osm_ops,
+ };
+
+ /*
+ * r57: OSM enable DISABLED. Exhaustive testing (r49-r56, with
+ * the freq/voltage LUT + FSMs + CPRh all verified byte-correct
+ * against a working downstream device) proved the OSM latches
+ * the perf-state vote (DCVS_PERF_STATE_DESIRED) but never drives
+ * the PLL/mux: the transition needs the sequencer config in the
+ * OSM's <0x1000 region, which is XPU-protected and established
+ * only by the Android secure-boot flow, not reproducible from a
+ * mainline boot. Leaving the OSM disabled keeps the driver inert
+ * (everything is programmed but nothing enabled) and the boot
+ * stable; the CPUs run at the bootloader-set fixed rate. Flip the
+ * two calls below back on to reproduce the experiment.
+ */
+ if (0) {
+ osm_setup_cluster_pll(cl[i]);
+ osm_enable(cl[i]);
+ }
+ cl[i]->hw.init = &init;
+ ret = devm_clk_hw_register(dev, &cl[i]->hw);
+ if (ret)
+ return ret;
+ osm_hws[i] = &cl[i]->hw;
+ }
+
+ /*
+ * r54 decisive test. Since r50 every build wrote the sequencer through
+ * qcom_scm_io_writel (proven a silent no-op in r51); the "plain kernel
+ * writel + read back through the secure monitor" combination was NEVER
+ * tried, so whether a kernel writel to the < 0x1000 region lands is still
+ * genuinely open. VERSION_REG (0x0) is a fixed non-zero HW id in the same
+ * XPU domain and acts as a control: if its SCM read is non-zero, SCM reads
+ * of this region are NOT masked and reg21 is trustworthy - reg21 ==
+ * PLL_MIN_LVAL then means the plain writel LANDED (sequencer loadable,
+ * re-enable the OSM in r55). If SCMver reads 0 as well, SCM reads are
+ * masked and every past "seq0=0" datum (the "sequencer empty" evidence)
+ * was unsound and the sequencer may in fact be programmed.
+ */
+ for (i = 0; i < NUM_CLUSTERS; i++) {
+ u32 scm_seq0 = 0, scm_reg21 = 0, scm_ver = 0;
+ u32 hlos_ver = osm_r(cl[i], 0x0);
+ int r0, r2, rv;
+
+ rv = qcom_scm_io_readl(cl[i]->phys + 0x0, &scm_ver);
+ r0 = qcom_scm_io_readl(cl[i]->phys + SEQ_MEM_ADDR, &scm_seq0);
+ r2 = qcom_scm_io_readl(cl[i]->phys + SEQ_REG(21), &scm_reg21);
+
+ dev_info(dev,
+ "%s: enable=%#x desired=%u | VER hlos=%#x scm(%d)=%#x | SCM(%d/%d) seq0=%#x reg21=%#x(exp %d)\n",
+ cluster_cfgs[i].name,
+ osm_r(cl[i], ENABLE_REG),
+ osm_r(cl[i], DCVS_PERF_STATE_DESIRED_REG),
+ hlos_ver, rv, scm_ver,
+ r0, r2, scm_seq0, scm_reg21, PLL_MIN_LVAL);
+ }
+
+ return devm_of_clk_add_hw_provider(dev, osm_of_get, NULL);
+}
+
+static const struct of_device_id sdm660_osm_match[] = {
+ { .compatible = "qcom,sdm660-osm" },
+ {}
+};
+MODULE_DEVICE_TABLE(of, sdm660_osm_match);
+
+static struct platform_driver sdm660_osm_driver = {
+ .probe = sdm660_osm_probe,
+ .driver = {
+ .name = "sdm660-osm-cpu",
+ .of_match_table = sdm660_osm_match,
+ },
+};
+module_platform_driver(sdm660_osm_driver);
+
+/*
+ * Boot-stage diagnostic. On this SoC the OSM sequencer is meant to be
+ * programmed by the secure world before Linux (secure_init=false model), so it
+ * should already contain microcode when Linux starts. Sample it before this
+ * driver's probe (fs_initcall) and after it (late_initcall): if the pre-probe
+ * read shows the first microcode word (0xc2005000) but the post-probe read
+ * shows 0, this driver's probe is clearing the firmware-programmed sequencer.
+ */
+static void osm_dbg_dump(const char *stage)
+{
+ void __iomem *b = ioremap(0x179c0000, 0x3000);
+ u32 en = 0, hp = 0, hb = 0, sp = 0, sb = 0;
+ int rs = -1;
+
+ if (b) {
+ en = readl_relaxed(b + ENABLE_REG);
+ hp = readl_relaxed(b + SEQ_MEM_ADDR);
+ hb = readl_relaxed(b + OSM_CORE_TABLE_SIZE + SEQ_MEM_ADDR);
+ iounmap(b);
+ }
+ if (qcom_scm_is_available()) {
+ rs = qcom_scm_io_readl(0x179c0000 + SEQ_MEM_ADDR, &sp);
+ qcom_scm_io_readl(0x179c2000 + SEQ_MEM_ADDR, &sb);
+ }
+ pr_info("sdm660-osm DBG[%s]: pwrcl ENABLE=%#x | readl seq0 pwrcl=%#x perfcl=%#x | SCM(ret %d) pwrcl=%#x perfcl=%#x\n",
+ stage, en, hp, hb, rs, sp, sb);
+}
+
+static int __init osm_dbg_fs(void)
+{
+ osm_dbg_dump("fs/pre-probe");
+ return 0;
+}
+fs_initcall(osm_dbg_fs);
+
+static int __init osm_dbg_late(void)
+{
+ osm_dbg_dump("late/post-probe");
+ return 0;
+}
+late_initcall(osm_dbg_late);
+
+MODULE_DESCRIPTION("Qualcomm SDM660 CPU (OSM) clock driver");
+MODULE_LICENSE("GPL");
diff --git a/drivers/clk/qcom/Kconfig b/drivers/clk/qcom/Kconfig
index a284ba0..9e8d43d 100644
--- a/drivers/clk/qcom/Kconfig
+++ b/drivers/clk/qcom/Kconfig
@@ -871,6 +871,15 @@ config SDM_GCC_660
Say Y if you want to use peripheral devices such as UART, SPI,
i2C, USB, UFS, SDDC, PCIe, etc.
+config SDM660_CPU_CLK
+ tristate "SDM660 CPU (OSM) Clock Controller"
+ depends on ARM64 || COMPILE_TEST
+ help
+ Support for the Operating State Manager (OSM) that drives the two
+ Kryo-260 CPU clusters on SDM660. Unlike SDM845 the bootloader does
+ not program the OSM, so this driver loads the frequency/voltage
+ tables and the sequencer microcode itself, enabling cpufreq.
+
config SDM_MMCC_660
tristate "SDM660 Multimedia Clock Controller"
depends on ARM64 || COMPILE_TEST
diff --git a/drivers/clk/qcom/Makefile b/drivers/clk/qcom/Makefile
index 0ac8a90..e7d1ff2 100644
--- a/drivers/clk/qcom/Makefile
+++ b/drivers/clk/qcom/Makefile
@@ -121,6 +121,7 @@ obj-$(CONFIG_SDM_DISPCC_845) += dispcc-sdm845.o
obj-$(CONFIG_SDM_GCC_660) += gcc-sdm660.o
obj-$(CONFIG_SDM_MMCC_660) += mmcc-sdm660.o
obj-$(CONFIG_SDM_GPUCC_660) += gpucc-sdm660.o
+obj-$(CONFIG_SDM660_CPU_CLK) += clk-cpu-sdm660.o
obj-$(CONFIG_SDM_GCC_845) += gcc-sdm845.o
obj-$(CONFIG_SDM_GPUCC_845) += gpucc-sdm845.o
obj-$(CONFIG_SDM_LPASSCC_845) += lpasscc-sdm845.o
@@ -0,0 +1,101 @@
From: Platina local project
Subject: [PATCH] Rebase platina OSM nodes after preceding display/battery patches
Keep upstream OSM data unchanged; the original patch incorrectly expected
the USB block to be at EOF although patch 0001 appends display nodes there.
---
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
@@ -15,6 +15,7 @@
#include <dt-bindings/input/gpio-keys.h>
#include <dt-bindings/leds/common.h>
#include <dt-bindings/pinctrl/qcom,pmic-gpio.h>
+#include <dt-bindings/clock/qcom,gcc-sdm660.h>
/ {
model = "Xiaomi Mi 8 Lite";
@@ -930,3 +931,84 @@
status = "okay";
};
+
+/*
+ * CPU frequency scaling via the OSM (clk-cpu-sdm660 driver). First-cut OPPs
+ * stay within each rail's boot-time voltage corner (little <= 1382 MHz,
+ * big <= 1113 MHz), so nothing is under-volted; raise once the OSM voltage
+ * path is confirmed to move VDD_APCC.
+ */
+&{/} {
+ cpu_osm: clock-controller@179c0000 {
+ compatible = "qcom,sdm660-osm";
+ reg = <0x0 0x179c0000 0x0 0x4000>;
+ reg-names = "osm";
+ clocks = <&gcc HMSS_GPLL0_CLK_SRC>;
+ clock-names = "aux";
+ #clock-cells = <1>;
+
+ /* r56: exact LUT from LineageOS /proc/device-tree (speed bin 1). */
+ qcom,pwrcl-speedbin0-v0 =
+ < 300000000 0x0004000f 0x01200020 0x1 1 >,
+ < 633600000 0x05040021 0x03200020 0x1 2 >,
+ < 902400000 0x0404002f 0x04260026 0x1 3 >,
+ < 1113600000 0x0404003a 0x052e002e 0x2 4 >,
+ < 1401600000 0x04040049 0x073a003a 0x2 5 >,
+ < 1536000000 0x04040050 0x08400040 0x2 6 >,
+ < 1747200000 0x0404005b 0x09480048 0x2 7 >,
+ < 1843200000 0x04040060 0x094c004c 0x3 8 >;
+
+ qcom,perfcl-speedbin1-v0 =
+ < 300000000 0x0004000f 0x01200020 0x1 1 >,
+ < 1113600000 0x0404003a 0x052e002e 0x1 2 >,
+ < 1401600000 0x04040049 0x073a003a 0x2 3 >,
+ < 1747200000 0x0404005b 0x09480048 0x2 4 >,
+ < 1958400000 0x04040066 0x0a510051 0x2 5 >,
+ < 2150400000 0x04040070 0x0b590059 0x2 6 >,
+ < 2208000000 0x04040073 0x0b5c005c 0x3 7 >;
+
+ qcom,pwrcl-voltage-ceiling =
+ < 724000 724000 724000 788000 868000
+ 1068000 1068000 1068000 >;
+ qcom,perfcl-voltage-ceiling =
+ < 724000 724000 788000 868000 988000 988000 1068000 >;
+ };
+
+ /* CPRh: puts the CPU voltage rails in HW closed-loop for the OSM. */
+ cprh_cpu: cpr@179c8000 {
+ compatible = "qcom,sdm660-cprh";
+ clocks = <&gcc GCC_HMSS_RBCPR_CLK>;
+ clock-names = "core_clk";
+ };
+
+ /*
+ * r56: OPP freqs match the real LUT points exactly and stay <= NOM
+ * corner (little <= 1113.6, big <= 1401.6) so the NOM-clamped CPRh never
+ * under-volts. Raise once transitions are confirmed and CPRh TURBO added.
+ */
+ cpu0_opp_table: opp-table-cpu0 {
+ compatible = "operating-points-v2";
+ opp-shared;
+ opp-300000000 { opp-hz = /bits/ 64 <300000000>; };
+ opp-633600000 { opp-hz = /bits/ 64 <633600000>; };
+ opp-902400000 { opp-hz = /bits/ 64 <902400000>; };
+ opp-1113600000 { opp-hz = /bits/ 64 <1113600000>; };
+ };
+
+ cpu4_opp_table: opp-table-cpu4 {
+ compatible = "operating-points-v2";
+ opp-shared;
+ opp-300000000 { opp-hz = /bits/ 64 <300000000>; };
+ opp-1113600000 { opp-hz = /bits/ 64 <1113600000>; };
+ opp-1401600000 { opp-hz = /bits/ 64 <1401600000>; };
+ };
+};
+
+&cpu0 { clocks = <&cpu_osm 0>; operating-points-v2 = <&cpu0_opp_table>; };
+&cpu1 { clocks = <&cpu_osm 0>; operating-points-v2 = <&cpu0_opp_table>; };
+&cpu2 { clocks = <&cpu_osm 0>; operating-points-v2 = <&cpu0_opp_table>; };
+&cpu3 { clocks = <&cpu_osm 0>; operating-points-v2 = <&cpu0_opp_table>; };
+&cpu4 { clocks = <&cpu_osm 1>; operating-points-v2 = <&cpu4_opp_table>; };
+&cpu5 { clocks = <&cpu_osm 1>; operating-points-v2 = <&cpu4_opp_table>; };
+&cpu6 { clocks = <&cpu_osm 1>; operating-points-v2 = <&cpu4_opp_table>; };
+&cpu7 { clocks = <&cpu_osm 1>; operating-points-v2 = <&cpu4_opp_table>; };
@@ -0,0 +1,352 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] clk: qcom: add SDM660 CPRh CPU voltage bring-up driver
Programs the CPRh (CPR hardened) controllers into full HW closed-loop so the
OSM can perform its voltage handshake and raise CPU frequency. Conservative
first cut: all corners clamped at/below the NOM fuse point (no over-volt).
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
diff --git a/drivers/clk/qcom/clk-cprh-sdm660.c b/drivers/clk/qcom/clk-cprh-sdm660.c
new file mode 100644
index 0000000..1111111
--- /dev/null
+++ b/drivers/clk/qcom/clk-cprh-sdm660.c
@@ -0,0 +1,310 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * SDM660 CPRh (CPR hardened) minimal bring-up for mainline Linux.
+ *
+ * The SDM660 CPU clusters get their supply voltage from the CPRh hardware in
+ * "full HW closed-loop" mode. The OSM (cpufreq) cannot raise CPU frequency
+ * until the CPRh is programmed and running, because each OSM frequency
+ * transition performs a voltage handshake with the CPRh. Mainline has no CPRh
+ * driver for SDM660, which is why cpufreq is missing.
+ *
+ * This is a distilled port of the downstream cpr3-regulator + cprh-kbss
+ * drivers, reduced to the one-time hardware setup needed for full HW
+ * closed-loop operation. It uses per-device "golden" fuse-derived values
+ * captured from the downstream kernel (see cprh-golden-platina.md) so it does
+ * not re-implement the fuse read / interpolation math.
+ *
+ * WARNING: this programs the CPU voltage rail. Wrong values can under-volt
+ * (hang) or over-volt (hardware damage). The values below are the fuse-derived
+ * open-loop voltages + CPR target quotients read out of this exact device.
+ *
+ * Status: complete for a conservative first bring-up, UNTESTED on hardware.
+ * The full HW closed-loop init sequence is implemented; all corners are clamped
+ * at/below the NOM fuse point so the worst case is under-volt, never over-volt
+ * (see the corner tables). To use it:
+ * 1. add a DT node:
+ * cprh: cpr@179c8000 {
+ * compatible = "qcom,sdm660-cprh";
+ * reg = <0 0x179c8000 0 0x4000>, <0 0x179c4000 0 0x4000>;
+ * clocks = <&gcc GCC_HMSS_RBCPR_CLK>;
+ * clock-names = "core_clk";
+ * };
+ * (this driver ioremaps the two controller bases from hard-coded phys for
+ * now; a cleaner version would take them from reg.)
+ * 2. cap the OSM OPP table to <= NOM (<=1401 MHz pwrcl / the perfcl NOM freq)
+ * so the OSM never signals a corner above the clamped voltages.
+ * 3. verify the OSM<->CPRh corner index (0- vs 1-based) before extending the
+ * corner table upward or removing the clamp.
+ * Later work: real per-frequency interpolation of corners 1/6/7, TURBO corners
+ * with the APM switch above 872 mV, sensor-ownership programming, and exposing
+ * the controllers as proper regulators.
+ */
+
+#include <linux/clk.h>
+#include <linux/delay.h>
+#include <linux/io.h>
+#include <linux/module.h>
+#include <linux/of.h>
+#include <linux/platform_device.h>
+
+/* --- CPRh controller register offsets (from cpr_ctrl base) --- */
+#define CPR3_REG_CPR_CTL 0x4
+#define CPR3_CPR_CTL_LOOP_EN BIT(0)
+#define CPR3_REG_CPR_STEP_QUOT 0x14
+#define CPR3_REG_GCNT(ro) (0xA0 + 0x4 * (ro))
+#define CPR3_REG_THRESH(thr) (0x808 + 0x440 * (thr))
+#define CPR3_REG_RO_MASK(thr) (0x80C + 0x440 * (thr))
+#define CPR3_RO_MASK_ALL GENMASK(15, 0) /* CPR3_RO_COUNT=16 */
+#define CPR4_REG_MARGIN_ADJ_CTL 0x7F8
+#define CPR4_MARGIN_ADJ_CTL_HW_CL_EN BIT(4)
+#define CPR3_REG_CPR_TIMER_MID_CONT 0x3004
+#define CPRH_REG_CORNER(n) (0x3A00 + 0x4 * (n))
+#define CPRH_REG_CTL 0x3AA0
+#define CPRH_CTL_OSM_ENABLED BIT(0) /* OSM<->CPR interface enable */
+
+/* CPR_CTL fields */
+#define CPR_CTL_IDLE_CLOCKS_SHIFT 1
+#define CPR_CTL_COUNT_MODE_SHIFT 6
+#define CPR_CTL_COUNT_REPEAT_SHIFT 9
+
+/* THRESH fields (per thread) */
+#define THRESH_CONS_DOWN_SHIFT 0
+#define THRESH_CONS_UP_SHIFT 4
+#define THRESH_DOWN_THRESH_SHIFT 8
+#define THRESH_UP_THRESH_SHIFT 13
+
+/* CPRH corner word fields */
+#define CORNER_INIT_VOLT_SHIFT 0
+#define CORNER_FLOOR_VOLT_SHIFT 8
+#define CORNER_QUOT_DELTA_SHIFT 16
+#define CORNER_RO_SEL_SHIFT 25
+
+/* CPRH_REG_CTL fields */
+#define CTL_BASE_VOLTAGE_SHIFT 1
+#define CTL_VOLTAGE_MULTIPLIER_SHIFT 25
+
+/* thread THRESH config (apc0/apc1 thread@0): cons_up0 cons_down2 up2 down2 */
+#define THRESH_CONS_UP 0
+#define THRESH_CONS_DOWN 2
+#define THRESH_UP_THRESHOLD 2
+#define THRESH_DOWN_THRESHOLD 2
+
+/* constants from cprh-kbss / DT */
+#define CPR_CLOCK_RATE 19200000 /* RBCPR core clk */
+#define SENSOR_TIME_NS 1000
+#define LOOP_TIME_NS 5000000
+#define IDLE_CLOCKS 15
+#define COUNT_MODE 0 /* all at once */
+#define COUNT_REPEAT 14
+#define STEP_QUOT_INIT_MIN 12
+#define STEP_QUOT_INIT_MAX 14
+#define VOLTAGE_BASE_UV 400000
+#define VOLTAGE_STEP_UV 4000
+#define DELTA_QUOT_STEP_FACTOR 4
+#define RO_SEL 7
+
+/*
+ * Full 8-corner tables (platina, speed bin 1). The controllers have 8 corners,
+ * one per OSM frequency; the corner the OSM signals indexes CPRH_REG_CORNER(n).
+ *
+ * Values are the fuse-derived golden open-loop voltages + CPR target quotients
+ * captured from the downstream kernel (see cprh-golden-platina.md), with floors
+ * from qcom,cpr-voltage-floor. corner-fmax-map places the fuse points at the
+ * corners marked below; corners between/around them would normally be linearly
+ * interpolated by frequency.
+ *
+ * SAFETY-FIRST first cut: instead of interpolating (and instead of relying on
+ * the exact 0-/1-based OSM<->CPRh corner index, which we cannot validate live),
+ * every corner is clamped at or below the NOM fuse point (<=758 mV pwrcl /
+ * <=788 mV perfcl, all well under the 872 mV APM threshold). Consequence: if
+ * the OSM ever requests a high corner, or if the index is off by one, the worst
+ * case is a mild UNDER-volt (recoverable hang) - never an over-volt. The OSM
+ * OPP table must be capped to <=NOM to match; higher corners are a later step
+ * once real interpolation + index verification are done.
+ */
+struct cprh_corner {
+ u32 open_loop_uv;
+ u32 floor_uv;
+ u32 target_quot; /* RO7 */
+};
+
+struct cprh_ctrl_cfg {
+ const char *name;
+ u32 phys; /* cpr_ctrl base */
+ const struct cprh_corner *corners;
+ int corner_count;
+};
+
+/* pwrcl / little: fmax-map <2 3 4 5 8> = LowSVS SVS SVSPLUS NOM TURBO_L1 */
+static const struct cprh_corner apc0_corners[8] = {
+ { 614000, 588000, 336 }, /* c0 OSM1 LowSVS */
+ { 614000, 588000, 336 }, /* c1 OSM2 LowSVS */
+ { 644000, 588000, 390 }, /* c2 OSM3 SVS */
+ { 688000, 596000, 461 }, /* c3 OSM4 SVSPLUS */
+ { 758000, 652000, 586 }, /* c4 OSM5 NOM */
+ { 758000, 652000, 586 }, /* c5 clamp NOM */
+ { 758000, 652000, 586 }, /* c6 clamp NOM */
+ { 758000, 652000, 586 }, /* c7 clamp NOM */
+};
+
+/* perfcl / big: fmax-map <2 3 4 6 7> = SVS SVSPLUS NOM TURBO TURBO_L2 */
+static const struct cprh_corner apc1_corners[8] = {
+ { 684000, 588000, 575 }, /* c0 OSM1 SVS */
+ { 684000, 588000, 575 }, /* c1 OSM2 SVS */
+ { 718000, 596000, 642 }, /* c2 OSM3 SVSPLUS */
+ { 788000, 652000, 794 }, /* c3 OSM4 NOM */
+ { 788000, 652000, 794 }, /* c4 clamp NOM */
+ { 788000, 652000, 794 }, /* c5 clamp NOM */
+ { 788000, 652000, 794 }, /* c6 clamp NOM */
+ { 788000, 652000, 794 }, /* c7 clamp NOM */
+};
+
+static const struct cprh_ctrl_cfg ctrl_cfgs[] = {
+ { "apc0", 0x179c8000, apc0_corners, ARRAY_SIZE(apc0_corners) },
+ { "apc1", 0x179c4000, apc1_corners, ARRAY_SIZE(apc1_corners) },
+};
+
+#define DIV_RUP(a, b) (((a) + (b) - 1) / (b))
+
+static u32 corner_word(const struct cprh_corner *c, u32 base_quot)
+{
+ u32 iv = DIV_RUP(c->open_loop_uv - VOLTAGE_BASE_UV, VOLTAGE_STEP_UV);
+ u32 fv = DIV_RUP(c->floor_uv - VOLTAGE_BASE_UV, VOLTAGE_STEP_UV);
+ u32 dq = c->target_quot ?
+ DIV_RUP(c->target_quot - base_quot, DELTA_QUOT_STEP_FACTOR) : 0;
+
+ return ((iv & 0xff) << CORNER_INIT_VOLT_SHIFT) |
+ ((fv & 0xff) << CORNER_FLOOR_VOLT_SHIFT) |
+ ((dq & 0x1ff) << CORNER_QUOT_DELTA_SHIFT) |
+ ((RO_SEL & 0xf) << CORNER_RO_SEL_SHIFT);
+}
+
+static u32 calc_gcnt(void)
+{
+ u64 t = (u64)CPR_CLOCK_RATE * SENSOR_TIME_NS;
+
+ return DIV_RUP(t, 1000000000ULL) - 1;
+}
+
+static void cprh_program(void __iomem *base, const struct cprh_ctrl_cfg *cfg)
+{
+ u32 base_quot = U32_MAX, gcnt, val;
+ u64 tmp;
+ int i;
+
+ for (i = 0; i < cfg->corner_count; i++)
+ base_quot = min(base_quot, cfg->corners[i].target_quot);
+
+ /* GCNT for the RO in use */
+ gcnt = calc_gcnt();
+ writel_relaxed(gcnt, base + CPR3_REG_GCNT(RO_SEL));
+
+ /* loop-delay timer (HW closed-loop) */
+ tmp = (u64)CPR_CLOCK_RATE * LOOP_TIME_NS;
+ do_div(tmp, 1000000000ULL);
+ writel_relaxed((u32)tmp, base + CPR3_REG_CPR_TIMER_MID_CONT);
+
+ /* CPR sensor control (loop_en left off until the very end) */
+ val = (IDLE_CLOCKS << CPR_CTL_IDLE_CLOCKS_SHIFT) |
+ (COUNT_MODE << CPR_CTL_COUNT_MODE_SHIFT) |
+ (COUNT_REPEAT << CPR_CTL_COUNT_REPEAT_SHIFT);
+ writel_relaxed(val, base + CPR3_REG_CPR_CTL);
+
+ /* default step quotients */
+ val = (STEP_QUOT_INIT_MIN & 0x3f) | ((STEP_QUOT_INIT_MAX & 0x3f) << 6);
+ writel_relaxed(val, base + CPR3_REG_CPR_STEP_QUOT);
+
+ /* per-thread init: THRESH, then mask all ROs initially */
+ val = (THRESH_CONS_DOWN << THRESH_CONS_DOWN_SHIFT) |
+ (THRESH_CONS_UP << THRESH_CONS_UP_SHIFT) |
+ (THRESH_DOWN_THRESHOLD << THRESH_DOWN_THRESH_SHIFT) |
+ (THRESH_UP_THRESHOLD << THRESH_UP_THRESH_SHIFT);
+ writel_relaxed(val, base + CPR3_REG_THRESH(0));
+ writel_relaxed(CPR3_RO_MASK_ALL, base + CPR3_REG_RO_MASK(0));
+
+ /* corner table */
+ for (i = 0; i < cfg->corner_count; i++)
+ writel_relaxed(corner_word(&cfg->corners[i], base_quot),
+ base + CPRH_REG_CORNER(i));
+
+ /* unmask the RO actually used (set bit = masked, so clear RO_SEL) */
+ writel_relaxed(CPR3_RO_MASK_ALL & ~BIT(RO_SEL),
+ base + CPR3_REG_RO_MASK(0));
+
+ /*
+ * CPRH control: base voltage + step multiplier + OSM interface enable.
+ * OSM_ENABLED is what lets the OSM perform its voltage handshake with
+ * the CPRh - without it the OSM cannot change frequency. init_mode /
+ * mode_switch_delay are left at reset (0); only used with a configured
+ * corner-switch-delay, which platina does not set.
+ */
+ val = (DIV_RUP(VOLTAGE_BASE_UV, VOLTAGE_STEP_UV) << CTL_BASE_VOLTAGE_SHIFT) |
+ (DIV_RUP(VOLTAGE_STEP_UV, 1000) << CTL_VOLTAGE_MULTIPLIER_SHIFT) |
+ CPRH_CTL_OSM_ENABLED;
+ writel_relaxed(val, base + CPRH_REG_CTL);
+ wmb();
+
+ /* enable full HW closed-loop (CPRH type: MARGIN_ADJ_CTL bit4) */
+ val = readl_relaxed(base + CPR4_REG_MARGIN_ADJ_CTL);
+ val |= CPR4_MARGIN_ADJ_CTL_HW_CL_EN;
+ writel_relaxed(val, base + CPR4_REG_MARGIN_ADJ_CTL);
+ wmb();
+
+ /* finally, enable the CPR loop */
+ val = readl_relaxed(base + CPR3_REG_CPR_CTL) | CPR3_CPR_CTL_LOOP_EN;
+ writel_relaxed(val, base + CPR3_REG_CPR_CTL);
+ wmb();
+}
+
+static int sdm660_cprh_probe(struct platform_device *pdev)
+{
+ struct device *dev = &pdev->dev;
+ struct clk *core, *bus, *iface;
+ int i, ret;
+
+ /* CPRh needs core (RBCPR 19.2MHz) + bus + iface clocks on */
+ core = devm_clk_get(dev, "core_clk");
+ if (IS_ERR(core))
+ return dev_err_probe(dev, PTR_ERR(core), "no core_clk\n");
+ clk_set_rate(core, CPR_CLOCK_RATE);
+ ret = clk_prepare_enable(core);
+ if (ret)
+ return ret;
+
+ bus = devm_clk_get_optional(dev, "bus_clk");
+ if (!IS_ERR_OR_NULL(bus))
+ clk_prepare_enable(bus);
+ iface = devm_clk_get_optional(dev, "iface_clk");
+ if (!IS_ERR_OR_NULL(iface))
+ clk_prepare_enable(iface);
+
+ for (i = 0; i < ARRAY_SIZE(ctrl_cfgs); i++) {
+ void __iomem *base = devm_ioremap(dev, ctrl_cfgs[i].phys, 0x4000);
+
+ if (!base)
+ return -ENOMEM;
+ cprh_program(base, &ctrl_cfgs[i]);
+ dev_info(dev, "%s CPRh programmed (%d corners, closed-loop on)\n",
+ ctrl_cfgs[i].name, ctrl_cfgs[i].corner_count);
+ }
+
+ return 0;
+}
+
+static const struct of_device_id sdm660_cprh_match[] = {
+ { .compatible = "qcom,sdm660-cprh" },
+ {}
+};
+MODULE_DEVICE_TABLE(of, sdm660_cprh_match);
+
+static struct platform_driver sdm660_cprh_driver = {
+ .probe = sdm660_cprh_probe,
+ .driver = {
+ .name = "sdm660-cprh",
+ .of_match_table = sdm660_cprh_match,
+ },
+};
+module_platform_driver(sdm660_cprh_driver);
+
+MODULE_DESCRIPTION("Qualcomm SDM660 CPRh minimal closed-loop bring-up");
+MODULE_LICENSE("GPL");
diff --git a/drivers/clk/qcom/Kconfig b/drivers/clk/qcom/Kconfig
--- a/drivers/clk/qcom/Kconfig
+++ b/drivers/clk/qcom/Kconfig
@@ -880,6 +880,14 @@ config SDM660_CPU_CLK
not program the OSM, so this driver loads the frequency/voltage
tables and the sequencer microcode itself, enabling cpufreq.
+config SDM660_CPRH
+ tristate "SDM660 CPRh CPU voltage bring-up"
+ depends on ARM64 || COMPILE_TEST
+ help
+ Programs the CPRh (CPR hardened) controllers into HW closed-loop so
+ the OSM can raise CPU voltage/frequency. Required for cpufreq on the
+ SDM660 CPU clusters.
+
config SDM_MMCC_660
tristate "SDM660 Multimedia Clock Controller"
depends on ARM64 || COMPILE_TEST
diff --git a/drivers/clk/qcom/Makefile b/drivers/clk/qcom/Makefile
--- a/drivers/clk/qcom/Makefile
+++ b/drivers/clk/qcom/Makefile
@@ -124,4 +124,5 @@ obj-$(CONFIG_SDM_GPUCC_660) += gpucc-sdm660.o
obj-$(CONFIG_SDM660_CPU_CLK) += clk-cpu-sdm660.o
obj-$(CONFIG_SDM_GCC_845) += gcc-sdm845.o
+obj-$(CONFIG_SDM660_CPRH) += clk-cprh-sdm660.o
obj-$(CONFIG_SDM_GPUCC_845) += gpucc-sdm845.o
obj-$(CONFIG_SDM_LPASSCC_845) += lpasscc-sdm845.o
@@ -0,0 +1,122 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] arm64: dts: qcom: sdm660: enable internal audio on platina
Wire up the SDM660 internal sound card on the Xiaomi Mi 8 Lite: the PM660L
analog codec + LPASS digital codec driven by the Q6/ADSP (headphones out +
internal mic), including the q6asm/q6afe DAI children the frontends/backends
need. Mirrors sdm660-xiaomi-lavender-common.dtsi.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
@@ -15,6 +15,8 @@
#include <dt-bindings/input/gpio-keys.h>
#include <dt-bindings/leds/common.h>
#include <dt-bindings/pinctrl/qcom,pmic-gpio.h>
+#include <dt-bindings/sound/qcom,q6afe.h>
+#include <dt-bindings/sound/qcom,q6asm.h>
#include <dt-bindings/clock/qcom,gcc-sdm660.h>
/ {
@@ -1012,3 +1014,100 @@
&cpu5 { clocks = <&cpu_osm 1>; operating-points-v2 = <&cpu4_opp_table>; };
&cpu6 { clocks = <&cpu_osm 1>; operating-points-v2 = <&cpu4_opp_table>; };
&cpu7 { clocks = <&cpu_osm 1>; operating-points-v2 = <&cpu4_opp_table>; };
+
+/*
+ * Audio: SDM660 internal sound card (headphones + mic via the PM660L analog
+ * codec + LPASS digital codec, driven by the Q6/ADSP). Mirrors the working
+ * sdm660-xiaomi-lavender-common.dtsi wiring; speaker (NXP TFA98xx) is separate.
+ */
+&q6afedai {
+ dai@81 {
+ reg = <INT0_MI2S_RX>;
+ qcom,sd-lines = <0 1>;
+ };
+
+ dai@88 {
+ reg = <INT3_MI2S_TX>;
+ qcom,sd-lines = <0 1>;
+ };
+};
+
+&q6asmdai {
+ dai@0 {
+ reg = <0>;
+ };
+
+ dai@1 {
+ reg = <1>;
+ };
+};
+
+&lpass_codec {
+ status = "okay";
+};
+
+&pm660l_codec {
+ vdd-cdc-io-supply = <&vreg_s4a_2p04>;
+ vdd-cdc-tx-rx-cx-supply = <&vreg_s4a_2p04>;
+ vdd-micbias-supply = <&vreg_l7b_3p125>;
+
+ qcom,micbias-lvl = <2600>;
+ qcom,micbias1-ext-cap;
+
+ status = "okay";
+};
+
+&sound {
+ compatible = "qcom,sdm660-internal-sndcard";
+ model = "Xiaomi Mi 8 Lite";
+
+ pinctrl-0 = <&cdc_pdm_default>, <&cdc_dmic_default>;
+ pinctrl-names = "default";
+
+ audio-routing = "PDM_RX1", "Digital PDM_RX1",
+ "PDM_RX2", "Digital PDM_RX2",
+ "PDM_RX3", "Digital PDM_RX3",
+ "Digital LPASS_PDM_TX", "PDM_TX",
+ "AMIC1", "MIC BIAS External1",
+ "AMIC2", "MIC BIAS External2";
+
+ mm1-dai-link {
+ link-name = "MultiMedia1";
+ cpu {
+ sound-dai = <&q6asmdai MSM_FRONTEND_DAI_MULTIMEDIA1>;
+ };
+ };
+
+ mm2-dai-link {
+ link-name = "MultiMedia2";
+ cpu {
+ sound-dai = <&q6asmdai MSM_FRONTEND_DAI_MULTIMEDIA2>;
+ };
+ };
+
+ int0-mi2s-dai-link {
+ link-name = "Internal MI2S Playback";
+ cpu {
+ sound-dai = <&q6afedai INT0_MI2S_RX>;
+ };
+ platform {
+ sound-dai = <&q6routing>;
+ };
+ codec {
+ sound-dai = <&pm660l_codec 0>, <&lpass_codec 0>;
+ };
+ };
+
+ int3-mi2s-dai-link {
+ link-name = "Internal MI2S Capture";
+ cpu {
+ sound-dai = <&q6afedai INT3_MI2S_TX>;
+ };
+ platform {
+ sound-dai = <&q6routing>;
+ };
+ codec {
+ sound-dai = <&pm660l_codec 1>, <&lpass_codec 1>;
+ };
+ };
+};
@@ -0,0 +1,323 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] ASoC: codecs: add NXP TFA9894 direct-mode driver
Minimal ASoC driver for the TFA9894 smart speaker amp on the Xiaomi Mi 8 Lite.
Direct mode (I2S/TDM straight to the speaker, no CoolFlux DSP/container),
verified live to pass audio. Register config RE'd from the vendor driver and
captured from a working device.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
diff --git a/sound/soc/codecs/tfa9894.c b/sound/soc/codecs/tfa9894.c
new file mode 100644
--- /dev/null
+++ b/sound/soc/codecs/tfa9894.c
@@ -0,0 +1,273 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * tfa9894.c - minimal ASoC driver for the NXP/Goodix TFA9894 smart speaker amp
+ *
+ * The TFA9894 is a "smart" mono Class-D amp with an on-chip CoolFlux DSP that
+ * Android drives with a proprietary firmware "container" (speaker model, boost,
+ * excursion protection). This driver deliberately does NOT use the DSP: it puts
+ * the amp in DIRECT mode (AMPINSEL = TDM), which is what the vendor driver does
+ * for the raw audio path, so I2S/TDM audio reaches the speaker without loading
+ * any firmware. Without the DSP there is no excursion/thermal protection, so
+ * keep the volume conservative.
+ *
+ * The register map and the per-revision "optimal settings" were reverse
+ * engineered from the vendor tfa98xx driver (tfa_init.c: tfa9894_specific) and
+ * verified against the chip on a Xiaomi Mi 8 Lite (revid 0x1a94, read live over
+ * i2c: reg 0x03 low byte = 0x94).
+ */
+
+#include <linux/bitfield.h>
+#include <linux/delay.h>
+#include <linux/i2c.h>
+#include <linux/module.h>
+#include <linux/regmap.h>
+#include <sound/soc.h>
+#include <sound/soc-dapm.h>
+
+/* registers (8-bit address, 16-bit big-endian values) */
+#define TFA9894_SYS_CTRL0 0x00
+#define SYS_CTRL0_PWDN BIT(0) /* power down */
+#define SYS_CTRL0_I2CR BIT(1) /* I2C reset (auto-clear) */
+#define SYS_CTRL0_CFE BIT(2) /* enable CoolFlux DSP */
+#define SYS_CTRL0_AMPE BIT(3) /* enable amplifier */
+#define SYS_CTRL0_DCA BIT(4) /* enable DCDC boost */
+#define SYS_CTRL0_SBSL BIT(5) /* DSP configured */
+#define SYS_CTRL0_AMPC BIT(6) /* amplifier controlled by DSP */
+#define TFA9894_SYS_CTRL1 0x01
+#define SYS_CTRL1_AMPINSEL GENMASK(1, 0) /* 0 = TDM direct to amp */
+#define SYS_CTRL1_MANSCONF BIT(2) /* device I2C settings configured */
+#define TFA9894_AUDIO_CTRL 0x02
+#define AUDIO_CTRL_AUDFS GENMASK(3, 0) /* audio sample rate */
+#define TFA9894_REVISION 0x03
+#define TFA9894_HIDE_KEY 0x0f
+#define TFA9894_TDM_CFG0 0x20
+#define TDM_CFG0_TDME BIT(0) /* enable TDM interface */
+#define TDM_CFG0_TDMSPKE BIT(1) /* audio channel to sink0 (speaker) */
+#define TFA9894_TDM_SLOT 0x23
+#define TDM_SLOT_TDMSPKS GENMASK(3, 0) /* TDM slot for sink0 */
+#define TFA9894_KEY2 0xa0
+#define TFA9894_MTP_KEY 0xfb
+
+#define TFA9894_REV_ID 0x94 /* low byte of reg 0x03 */
+
+/*
+ * Cold-start register configuration for revid 0x1a94. This is the vendor
+ * "optimal settings" (RE'd from tfa9894_specific()) PLUS the clock/analog/TDM
+ * and speaker-protection registers captured live over i2c from a working
+ * Xiaomi Mi 8 Lite while audio was playing. In DIRECT mode (AMPINSEL = TDM,
+ * no DSP) these i2c registers are all the chip needs - the CoolFlux DSP RAM
+ * is not used. Verified live: flipping a fully-initialised chip to AMPINSEL=0
+ * kept audio playing, so this hardware path works without firmware.
+ * reg 0x00/0x01 (power + input mux) are handled in probe()/DAPM, not here.
+ */
+static const struct reg_sequence tfa9894_init_1a94[] = {
+ { 0x00, 0xa211 }, /* direct mode: no DSP (AMPC/CFE=0), boost on, amp off */
+ { 0x01, 0x15d4 }, /* AMPINSEL=0 (TDM straight to amp), MANSCONF=1 */
+ { 0x02, 0x52c8 }, /* audio ctrl (AUDFS overwritten per-rate) */
+ { 0x10, 0x785e }, /* system/clock control */
+ { 0x11, 0x0006 },
+ { 0x12, 0x004f },
+ { 0x14, 0x0d49 }, /* PLL / analog */
+ { 0x15, 0x029a },
+ { 0x16, 0x0028 },
+ { 0x17, 0x0118 },
+ { 0x20, 0x0747 }, /* TDM interface config */
+ { 0x21, 0x8110 },
+ { 0x22, 0x3c0f },
+ { 0x23, 0x0410 }, /* speaker sink on slot 0 */
+ { 0x24, 0x0410 },
+ { 0x52, 0xbe17 }, /* analog / current-sense / protection */
+ { 0x53, 0x0dbe },
+ { 0x54, 0x00e0 },
+ { 0x55, 0x07ff },
+ { 0x56, 0x05c3 },
+ { 0x57, 0x0344 },
+ { 0x58, 0x0081 },
+ { 0x59, 0x0a9a },
+ { 0x5a, 0x1040 },
+ { 0x5b, 0x0a82 },
+ { 0x5c, 0x00b0 },
+ { 0x5d, 0x0790 },
+ { 0x5e, 0x0005 },
+ { 0x5f, 0x002a },
+ { 0x61, 0x0032 },
+ { 0x71, 0x00cf },
+ { 0x72, 0x34a9 },
+ { 0x73, 0x38c8 },
+ { 0x76, 0x0067 },
+ { 0x81, 0x5799 },
+ { 0x82, 0x0104 },
+ { 0x83, 0x0003 },
+ { 0x88, 0x0004 },
+ { 0x89, 0x0022 },
+ { 0x8a, 0x1470 },
+};
+
+struct tfa9894 {
+ struct regmap *regmap;
+};
+
+static bool tfa9894_volatile_reg(struct device *dev, unsigned int reg)
+{
+ switch (reg) {
+ case TFA9894_SYS_CTRL0: /* status bits auto-update */
+ case TFA9894_REVISION:
+ case TFA9894_MTP_KEY:
+ return true;
+ default:
+ return false;
+ }
+}
+
+static const struct regmap_config tfa9894_regmap = {
+ .reg_bits = 8,
+ .val_bits = 16,
+ .max_register = 0xff,
+ .volatile_reg = tfa9894_volatile_reg,
+ .cache_type = REGCACHE_NONE,
+};
+
+/* map an ALSA rate to the AUDFS field value (matches vendor table) */
+static int tfa9894_audfs(unsigned int rate)
+{
+ switch (rate) {
+ case 8000: return 0;
+ case 11025: return 1;
+ case 12000: return 2;
+ case 16000: return 3;
+ case 22050: return 4;
+ case 24000: return 5;
+ case 32000: return 6;
+ case 44100: return 7;
+ case 48000: return 8;
+ default: return -EINVAL;
+ }
+}
+
+static int tfa9894_hw_params(struct snd_pcm_substream *substream,
+ struct snd_pcm_hw_params *params,
+ struct snd_soc_dai *dai)
+{
+ struct snd_soc_component *comp = dai->component;
+ int fs = tfa9894_audfs(params_rate(params));
+
+ if (fs < 0) {
+ dev_err(comp->dev, "unsupported rate %u\n", params_rate(params));
+ return fs;
+ }
+
+ return snd_soc_component_update_bits(comp, TFA9894_AUDIO_CTRL,
+ AUDIO_CTRL_AUDFS,
+ FIELD_PREP(AUDIO_CTRL_AUDFS, fs));
+}
+
+static const struct snd_soc_dai_ops tfa9894_dai_ops = {
+ .hw_params = tfa9894_hw_params,
+};
+
+static struct snd_soc_dai_driver tfa9894_dai = {
+ .name = "tfa9894-hifi",
+ .playback = {
+ .stream_name = "HiFi Playback",
+ .formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE,
+ .rates = SNDRV_PCM_RATE_8000_48000,
+ .rate_min = 8000,
+ .rate_max = 48000,
+ .channels_min = 1,
+ .channels_max = 2,
+ },
+ .ops = &tfa9894_dai_ops,
+};
+
+/*
+ * DAPM: the "OUT" -> AMPE -> POWER chain enables the amp when the stream runs.
+ * POWER clears PWDN (invert), AMPE sets the amp-enable bit; DCA (boost) rides
+ * along with AMPE via the supply. AMPC is left 0 so the amp follows AMPE
+ * directly instead of waiting for the (unused) DSP.
+ */
+static const struct snd_soc_dapm_widget tfa9894_widgets[] = {
+ SND_SOC_DAPM_AIF_IN("AIF IN", "HiFi Playback", 0, SND_SOC_NOPM, 0, 0),
+ SND_SOC_DAPM_SUPPLY("POWER", TFA9894_SYS_CTRL0, 0 /* PWDN */, 1, NULL, 0),
+ SND_SOC_DAPM_OUT_DRV("AMPE", TFA9894_SYS_CTRL0, 3 /* AMPE */, 0, NULL, 0),
+ SND_SOC_DAPM_OUTPUT("OUT"),
+};
+
+static const struct snd_soc_dapm_route tfa9894_routes[] = {
+ { "AMPE", NULL, "AIF IN" },
+ { "AMPE", NULL, "POWER" },
+ { "OUT", NULL, "AMPE" },
+};
+
+static int tfa9894_probe(struct snd_soc_component *comp)
+{
+ struct tfa9894 *tfa = snd_soc_component_get_drvdata(comp);
+ unsigned int rev, key;
+ int ret;
+
+ ret = regmap_read(tfa->regmap, TFA9894_REVISION, &rev);
+ if (ret)
+ return ret;
+ if ((rev & 0xff) != TFA9894_REV_ID)
+ dev_warn(comp->dev, "unexpected revid %#x (want low byte %#x)\n",
+ rev, TFA9894_REV_ID);
+
+ /* unlock protected registers (vendor tfa9894_specific sequence) */
+ regmap_write(tfa->regmap, TFA9894_HIDE_KEY, 0x5a6b);
+ regmap_read(tfa->regmap, TFA9894_MTP_KEY, &key);
+ regmap_write(tfa->regmap, TFA9894_KEY2, (key ^ 0x005a) & 0xffff);
+
+ /*
+ * Apply the full cold-start config (direct/TDM mode, no DSP). After
+ * this the chip is configured with the amp powered down; the DAPM
+ * "POWER"/"AMPE" widgets clear PWDN and enable the amplifier when a
+ * stream starts. TDM interface + speaker sink are set in the sequence.
+ */
+ return regmap_multi_reg_write(tfa->regmap, tfa9894_init_1a94,
+ ARRAY_SIZE(tfa9894_init_1a94));
+}
+
+static const struct snd_soc_component_driver tfa9894_component = {
+ .probe = tfa9894_probe,
+ .dapm_widgets = tfa9894_widgets,
+ .num_dapm_widgets = ARRAY_SIZE(tfa9894_widgets),
+ .dapm_routes = tfa9894_routes,
+ .num_dapm_routes = ARRAY_SIZE(tfa9894_routes),
+ .idle_bias_on = 1,
+ .endianness = 1,
+};
+
+static int tfa9894_i2c_probe(struct i2c_client *i2c)
+{
+ struct tfa9894 *tfa;
+
+ tfa = devm_kzalloc(&i2c->dev, sizeof(*tfa), GFP_KERNEL);
+ if (!tfa)
+ return -ENOMEM;
+
+ tfa->regmap = devm_regmap_init_i2c(i2c, &tfa9894_regmap);
+ if (IS_ERR(tfa->regmap))
+ return PTR_ERR(tfa->regmap);
+
+ i2c_set_clientdata(i2c, tfa);
+
+ return devm_snd_soc_register_component(&i2c->dev, &tfa9894_component,
+ &tfa9894_dai, 1);
+}
+
+static const struct of_device_id tfa9894_of_match[] = {
+ { .compatible = "nxp,tfa9894" },
+ { }
+};
+MODULE_DEVICE_TABLE(of, tfa9894_of_match);
+
+static struct i2c_driver tfa9894_i2c_driver = {
+ .driver = {
+ .name = "tfa9894",
+ .of_match_table = tfa9894_of_match,
+ },
+ .probe = tfa9894_i2c_probe,
+};
+module_i2c_driver(tfa9894_i2c_driver);
+
+MODULE_DESCRIPTION("ASoC NXP TFA9894 direct-mode driver");
+MODULE_LICENSE("GPL");
--- a/sound/soc/codecs/Kconfig
+++ b/sound/soc/codecs/Kconfig
@@ -2209,6 +2209,14 @@
Note that the driver currently bypasses the built-in "CoolFlux DSP"
and does not support (hardware) volume control.
+config SND_SOC_TFA9894
+ tristate "NXP/Goodix TFA9894 speaker amplifier (direct mode)"
+ depends on I2C
+ select REGMAP_I2C
+ help
+ Enable support for the NXP/Goodix TFA9894 smart speaker amplifier in
+ direct (DSP-bypass) mode, routing I2S/TDM straight to the speaker.
+
config SND_SOC_TLV320ADC3XXX
tristate "Texas Instruments TLV320ADC3001/3101 audio ADC"
depends on I2C
--- a/sound/soc/codecs/Makefile
+++ b/sound/soc/codecs/Makefile
@@ -324,6 +324,7 @@
snd-soc-tas2783-sdw-y := tas2783-sdw.o
snd-soc-tfa9879-y := tfa9879.o
snd-soc-tfa989x-y := tfa989x.o
+snd-soc-tfa9894-y := tfa9894.o
snd-soc-tlv320adc3xxx-y := tlv320adc3xxx.o
snd-soc-tlv320aic23-y := tlv320aic23.o
snd-soc-tlv320aic23-i2c-y := tlv320aic23-i2c.o
@@ -758,6 +759,7 @@
obj-$(CONFIG_SND_SOC_TAS2770) += snd-soc-tas2770.o
obj-$(CONFIG_SND_SOC_TFA9879) += snd-soc-tfa9879.o
obj-$(CONFIG_SND_SOC_TFA989X) += snd-soc-tfa989x.o
+obj-$(CONFIG_SND_SOC_TFA9894) += snd-soc-tfa9894.o
obj-$(CONFIG_SND_SOC_TLV320ADC3XXX) += snd-soc-tlv320adc3xxx.o
obj-$(CONFIG_SND_SOC_TLV320AIC23) += snd-soc-tlv320aic23.o
obj-$(CONFIG_SND_SOC_TLV320AIC23_I2C) += snd-soc-tlv320aic23-i2c.o
@@ -0,0 +1,47 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] arm64: dts: qcom: sdm660: wire TFA9894 speaker on platina
Add the TFA9894 speaker amp on blsp_i2c2 and a Secondary MI2S DAI link so the
Q6/ADSP feeds it, giving speaker output on the Xiaomi Mi 8 Lite.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
@@ -1111,3 +1111,36 @@
};
};
};
+
+/* Speaker: NXP TFA9894 smart amp on blsp_i2c2, fed by Secondary MI2S from the
+ * Q6/ADSP. Driven in direct (DSP-bypass) mode by the tfa9894 driver. */
+&blsp_i2c2 {
+ tfa9894: audio-codec@34 {
+ compatible = "nxp,tfa9894";
+ reg = <0x34>;
+ #sound-dai-cells = <0>;
+ sound-name-prefix = "Speaker";
+ };
+};
+
+&q6afedai {
+ dai@18 {
+ reg = <SECONDARY_MI2S_RX>;
+ qcom,sd-lines = <0>;
+ };
+};
+
+&sound {
+ sec-mi2s-dai-link {
+ link-name = "Secondary MI2S Playback";
+ cpu {
+ sound-dai = <&q6afedai SECONDARY_MI2S_RX>;
+ };
+ platform {
+ sound-dai = <&q6routing>;
+ };
+ codec {
+ sound-dai = <&tfa9894>;
+ };
+ };
+};
@@ -0,0 +1,46 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] arm64: dts: qcom: sdm660-xiaomi-platina: enable WCN3990 Bluetooth
Enable the WCN3990 Bluetooth (hci_qca serdev on the BLSP2 UART1 4-wire
port). It is the same combo die as the already-working WiFi; the four
VDD rails are shared with &wifi and ref-counted by the regulator core.
This mirrors the known-working sdm660-xiaomi-lavender BT config, and
adds the serial1 alias lavender uses for the BT UART.
Split out of the old 0022-platina-bt-vibrator so BT and the vibrator can
be validated (and, if needed, bisected) independently on the device.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts 2026-07-15 15:35:10.645379298 -0500
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts 2026-07-15 15:35:10.670546665 -0500
@@ -26,6 +26,7 @@
aliases {
serial0 = &blsp1_uart2;
+ serial1 = &blsp2_uart1; /* Bluetooth UART */
};
chosen {
@@ -1159,3 +1160,22 @@
&sound {
pinctrl-0 = <&cdc_pdm_default>, <&cdc_dmic_default>, <&sec_mi2s_default>;
};
+
+/*
+ * Bluetooth: WCN3990 combo chip (shares the die with the WiFi) on the
+ * BLSP2 UART1 4-wire port via hci_qca. The four VDD rails are the same
+ * ones the WiFi (&wifi) votes for the shared chip; the regulator core
+ * ref-counts them. Mirrors the known-working sdm660-xiaomi-lavender BT.
+ */
+&blsp2_uart1 {
+ status = "okay";
+
+ bluetooth {
+ compatible = "qcom,wcn3990-bt";
+ vddxo-supply = <&vreg_l9a_1p8>;
+ vddrf-supply = <&vreg_l6a_1p3>;
+ vddch0-supply = <&vreg_l19a_3p3>;
+ vddio-supply = <&vreg_l13a_1p8>;
+ max-speed = <3200000>;
+ };
+};
@@ -0,0 +1,30 @@
From: pmOS Mi8Lite <macosmojave2@gmail.com>
Subject: [PATCH] arm64: dts: qcom: sdm660: mux Secondary MI2S pins on platina
The TFA9894 speaker is fed by Secondary MI2S; without muxing gpio24-27 to the
sec_mi2s function the amp receives no bit clock and stays silent. Add the pin
state and apply it via the sound card.
Signed-off-by: pmOS Mi8Lite <macosmojave2@gmail.com>
---
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
@@ -1144,3 +1144,18 @@
};
};
};
+
+/* Secondary MI2S pins (SCK/WS/SD) to the TFA9894 speaker amp. Without this the
+ * amp gets no bit clock (NOCLK) and stays silent. */
+&tlmm {
+ sec_mi2s_default: sec-mi2s-default-state {
+ pins = "gpio24", "gpio25", "gpio26", "gpio27";
+ function = "sec_mi2s";
+ drive-strength = <8>;
+ bias-disable;
+ };
+};
+
+&sound {
+ pinctrl-0 = <&cdc_pdm_default>, <&cdc_dmic_default>, <&sec_mi2s_default>;
+};
@@ -0,0 +1,17 @@
From: Platina local project
Subject: [PATCH] Rebase unchanged PM660 haptics node after Bluetooth
The previous Bluetooth patch appends nodes after the original sound context.
Keep the haptics setting unchanged and append it after those nodes.
---
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
@@ -1179,3 +1179,8 @@
max-speed = <3200000>;
};
};
+
+/* Vibrator: PM660 SPMI haptics (LRA). Proven on jasmine/whyred/lavender. */
+&pm660_haptics {
+ status = "okay";
+};
@@ -0,0 +1,56 @@
--- a/drivers/net/wireless/ath/ath10k/wmi-tlv.c
+++ b/drivers/net/wireless/ath/ath10k/wmi-tlv.c
@@ -16,6 +16,30 @@
#include "testmode.h"
#include "txrx.h"
#include <linux/bitfield.h>
+
+/* Debug knobs (Xiaomi platina, WLAN.HL.1.0.1.c6 scan crash bring-up):
+ * let the WMI scan command be altered at runtime through
+ * /sys/module/ath10k_core/parameters/ so firmware behavior can be
+ * bisected without rebuilding. Defaults keep mainline behavior.
+ * scan_flags_clr/set operate on scan_ctrl_flags AFTER the TLV
+ * FILTER_PROBE_REQ inversion: PASSIVE=0x1 BCAST_PROBE=0x2 CCK=0x4
+ * OFDM=0x8 CHAN_STAT=0x10 FILTER_PROBE=0x20 CONT_ON_ERR=0x80.
+ */
+static unsigned int ath10k_tlv_scan_flags_clr;
+module_param_named(scan_flags_clr, ath10k_tlv_scan_flags_clr, uint, 0644);
+MODULE_PARM_DESC(scan_flags_clr, "bits to clear in WMI scan_ctrl_flags");
+static unsigned int ath10k_tlv_scan_flags_set;
+module_param_named(scan_flags_set, ath10k_tlv_scan_flags_set, uint, 0644);
+MODULE_PARM_DESC(scan_flags_set, "bits to set in WMI scan_ctrl_flags");
+static unsigned int ath10k_tlv_scan_dwell_active;
+module_param_named(scan_dwell_active, ath10k_tlv_scan_dwell_active, uint, 0644);
+MODULE_PARM_DESC(scan_dwell_active, "override active dwell time ms (0=default)");
+static unsigned int ath10k_tlv_scan_dwell_passive;
+module_param_named(scan_dwell_passive, ath10k_tlv_scan_dwell_passive, uint, 0644);
+MODULE_PARM_DESC(scan_dwell_passive, "override passive dwell time ms (0=default)");
+static unsigned int ath10k_tlv_scan_num_probes = 3;
+module_param_named(scan_num_probes, ath10k_tlv_scan_num_probes, uint, 0644);
+MODULE_PARM_DESC(scan_num_probes, "num_probes in WMI start scan (default 3)");
/***************/
/* TLV helpers */
@@ -2019,7 +2043,7 @@
cmd->num_ssids = __cpu_to_le32(arg->n_ssids);
cmd->num_bssids = __cpu_to_le32(arg->n_bssids);
cmd->ie_len = __cpu_to_le32(arg->ie_len);
- cmd->num_probes = __cpu_to_le32(3);
+ cmd->num_probes = __cpu_to_le32(ath10k_tlv_scan_num_probes);
ether_addr_copy(cmd->mac_addr.addr, arg->mac_addr.addr);
ether_addr_copy(cmd->mac_mask.addr, arg->mac_mask.addr);
@@ -2027,6 +2051,13 @@
* e.g. WMI-TLV inverts the logic behind the following flag.
*/
cmd->common.scan_ctrl_flags ^= __cpu_to_le32(WMI_SCAN_FILTER_PROBE_REQ);
+
+ cmd->common.scan_ctrl_flags &= __cpu_to_le32(~ath10k_tlv_scan_flags_clr);
+ cmd->common.scan_ctrl_flags |= __cpu_to_le32(ath10k_tlv_scan_flags_set);
+ if (ath10k_tlv_scan_dwell_active)
+ cmd->common.dwell_time_active = __cpu_to_le32(ath10k_tlv_scan_dwell_active);
+ if (ath10k_tlv_scan_dwell_passive)
+ cmd->common.dwell_time_passive = __cpu_to_le32(ath10k_tlv_scan_dwell_passive);
ptr += sizeof(*tlv);
ptr += sizeof(*cmd);
@@ -0,0 +1,44 @@
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
@@ -1023,12 +1023,12 @@
*/
&q6afedai {
dai@81 {
- reg = <INT0_MI2S_RX>;
+ reg = <LPI_MI2S_RX_0>;
qcom,sd-lines = <0 1>;
};
dai@88 {
- reg = <INT3_MI2S_TX>;
+ reg = <LPI_MI2S_TX_3>;
qcom,sd-lines = <0 1>;
};
};
@@ -1059,7 +1059,7 @@
};
&sound {
- compatible = "qcom,sdm660-internal-sndcard";
+ compatible = "qcom,sdm660-sndcard";
model = "Xiaomi Mi 8 Lite";
pinctrl-0 = <&cdc_pdm_default>, <&cdc_dmic_default>;
@@ -1089,7 +1089,7 @@
int0-mi2s-dai-link {
link-name = "Internal MI2S Playback";
cpu {
- sound-dai = <&q6afedai INT0_MI2S_RX>;
+ sound-dai = <&q6afedai LPI_MI2S_RX_0>;
};
platform {
sound-dai = <&q6routing>;
@@ -1102,7 +1102,7 @@
int3-mi2s-dai-link {
link-name = "Internal MI2S Capture";
cpu {
- sound-dai = <&q6afedai INT3_MI2S_TX>;
+ sound-dai = <&q6afedai LPI_MI2S_TX_3>;
};
platform {
sound-dai = <&q6routing>;
@@ -0,0 +1,33 @@
--- a/drivers/input/touchscreen/synaptics-tcm-i2c.c
+++ b/drivers/input/touchscreen/synaptics-tcm-i2c.c
@@ -582,6 +582,19 @@
/* ---- probe ---- */
+static void syna_release_regulator(void *data)
+{
+ struct syna_tcm *ts = data;
+
+ /* Balance this consumer's enable on probe failure or driver removal.
+ * Normal panel stop still leaves the shared rail enabled.
+ */
+ if (ts->powered) {
+ regulator_disable(ts->vdd);
+ ts->powered = false;
+ }
+}
+
static int syna_probe(struct i2c_client *client)
{
struct device *dev = &client->dev;
@@ -604,6 +617,10 @@
if (IS_ERR(ts->vdd))
return dev_err_probe(dev, PTR_ERR(ts->vdd),
"failed to get vdd regulator\n");
+
+ ret = devm_add_action_or_reset(dev, syna_release_regulator, ts);
+ if (ret)
+ return ret;
ts->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH);
if (IS_ERR(ts->reset_gpio))
@@ -0,0 +1,11 @@
--- a/drivers/clk/qcom/mmcc-sdm660.c
+++ b/drivers/clk/qcom/mmcc-sdm660.c
@@ -970,7 +970,7 @@
.name = "mdp_clk_src",
.parent_data = mmcc_xo_mmpll0_mmpll5_mmpll7_gpll0_gpll0_div,
.num_parents = ARRAY_SIZE(mmcc_xo_mmpll0_mmpll5_mmpll7_gpll0_gpll0_div),
- .ops = &clk_rcg2_ops,
+ .ops = &clk_rcg2_shared_no_init_park_ops,
},
};
@@ -0,0 +1,329 @@
From: Platina local project
Subject: [PATCH] drm/panel: integrate Platina Tianma NT36672A power and init
Hardware candidate; full boot and repeated power cycles await physical testing.
Stock evidence: project/display/tianma-reference.json.
--- a/drivers/gpu/drm/panel/panel-novatek-nt36672a.c
+++ b/drivers/gpu/drm/panel/panel-novatek-nt36672a.c
@@ -50,6 +50,7 @@
unsigned long mode_flags;
enum mipi_dsi_pixel_format format;
unsigned int lanes;
+ bool reset_pulse;
void (*send_init_cmds)(struct mipi_dsi_multi_context *dsi_ctx);
void (*send_deinit_cmds)(struct mipi_dsi_multi_context *dsi_ctx);
@@ -117,6 +118,17 @@
ret = regulator_bulk_enable(ARRAY_SIZE(pinfo->supplies), pinfo->supplies);
if (ret < 0)
return ret;
+
+ if (pinfo->desc->reset_pulse) {
+ /* Platina downstream: physical high 1ms, low 1ms, high 10ms. */
+ gpiod_set_value(pinfo->reset_gpio, 0);
+ usleep_range(1000, 2000);
+ gpiod_set_value(pinfo->reset_gpio, 1);
+ usleep_range(1000, 2000);
+ gpiod_set_value(pinfo->reset_gpio, 0);
+ msleep(10);
+ return 0;
+ }
/*
* As per downstream kernel, Reset sequence of Tianma FHD panel requires the panel to
@@ -138,13 +150,15 @@
struct mipi_dsi_multi_context dsi_ctx = { .dsi = pinfo->link };
dsi_ctx.accum_err = nt36672a_panel_power_on(pinfo);
+ if (dsi_ctx.accum_err < 0)
+ return dsi_ctx.accum_err;
/* send init cmds */
if (pinfo->desc->send_init_cmds)
pinfo->desc->send_init_cmds(&dsi_ctx);
if (dsi_ctx.accum_err < 0)
- gpiod_set_value(pinfo->reset_gpio, 0);
+ nt36672a_panel_power_off(panel);
return dsi_ctx.accum_err;
}
@@ -912,7 +926,9 @@
if (ret < 0)
return dev_err_probe(dev, ret, "failed to get regulators\n");
- pinfo->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_LOW);
+ pinfo->reset_gpio = devm_gpiod_get(dev, "reset",
+ pinfo->desc->reset_pulse ?
+ GPIOD_OUT_HIGH : GPIOD_OUT_LOW);
if (IS_ERR(pinfo->reset_gpio))
return dev_err_probe(dev, PTR_ERR(pinfo->reset_gpio),
"failed to get reset gpio from DT\n");
@@ -974,7 +990,235 @@
drm_panel_remove(&pinfo->base);
}
+/* Xiaomi platina Tianma variant; use its own stock sequence and timings.
+ * Reference: MiCode platina-o-oss, dsi-panel-tianma-fhd-nt36672a-video.dtsi
+ * (GPL-2.0-only), with CABC/ESD values from the retained original stock boot.
+ * Do not use the same-resolution tulip or bootloader-only BOE descriptor.
+ */
+static void platina_tianma_init_cmds(struct mipi_dsi_multi_context *dsi_ctx)
+{
+ dsi_ctx->dsi->mode_flags |= MIPI_DSI_MODE_LPM;
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xff, 0x22);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xfb, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x00, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x01, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x02, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x03, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x04, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x05, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x06, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x07, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x08, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x09, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x0a, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x0b, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x0c, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x0d, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x0e, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x0f, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x10, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x11, 0x50);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x12, 0x60);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x13, 0x70);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x14, 0x58);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x15, 0x68);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x16, 0x78);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x17, 0x77);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x18, 0x3e);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x19, 0x36);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x1a, 0x30);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x1b, 0x28);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x1c, 0x25);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x1d, 0x23);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x1e, 0x26);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x1f, 0x2a);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x20, 0x30);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x21, 0x36);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x22, 0x3c);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x23, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x24, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x25, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x26, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x27, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x28, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x53, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x54, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x55, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x56, 0x76);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x58, 0xc8);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x59, 0xca);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5a, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5b, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5c, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5d, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5e, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5f, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x60, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x61, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x62, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x63, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x64, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x65, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x66, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x67, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x68, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x69, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x6a, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x6b, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x6c, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x6d, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x6e, 0x48);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x6f, 0xc8);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x70, 0x03);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x71, 0x00);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x72, 0x80);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x73, 0x00);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x74, 0x06);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x75, 0x0c);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x76, 0x03);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x77, 0x09);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x78, 0x0f);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x79, 0x68);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x7a, 0x8b);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x7c, 0x80);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x7d, 0x80);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x7e, 0x80);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x7f, 0x00);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x80, 0x00);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x81, 0x00);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x83, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x84, 0x00);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x85, 0x80);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x86, 0x80);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x87, 0x80);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x88, 0x40);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x89, 0x83);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x8a, 0x86);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xb7, 0x76);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xb8, 0x76);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xff, 0x23);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xfb, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x00, 0x60);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x07, 0x00);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x08, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x09, 0x00);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x11, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x12, 0x80);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x15, 0x6d);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x16, 0x0b);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x29, 0x0a);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x30, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x31, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x32, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x33, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x34, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x35, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x36, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x37, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x38, 0xfc);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x39, 0xf9);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x3a, 0xf5);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x3b, 0xf1);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x3d, 0xee);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x3f, 0xeb);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x40, 0xe9);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x41, 0xe5);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x2a, 0x13);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x45, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x46, 0xf5);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x47, 0xea);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x48, 0xdf);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x49, 0xd5);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x4a, 0xca);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x4b, 0xc0);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x4c, 0xb6);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x4d, 0xac);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x4e, 0xa2);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x4f, 0x98);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x50, 0x8e);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x51, 0x84);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x52, 0x7a);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x53, 0x70);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x54, 0x66);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x2b, 0x0e);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x58, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x59, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5a, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5b, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5c, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5d, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5e, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x5f, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x60, 0xf6);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x61, 0xec);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x62, 0xe3);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x63, 0xd9);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x64, 0xd0);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x65, 0xc7);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x66, 0xbd);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x67, 0xb3);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x01, 0x84);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x06, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x05, 0x2d);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x04, 0x05);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xff, 0x25);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xfb, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x05, 0x04);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xff, 0x10);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xfb, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x35, 0x00);
+ mipi_dsi_generic_write_seq_multi(dsi_ctx, 0x51, 0x07, 0xff);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x53, 0x24);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x55, 0x00);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x29);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0x11);
+ mipi_dsi_msleep(dsi_ctx, 70);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xff, 0x24);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xfb, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xc3, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xc4, 0x54);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xc2, 0x8e);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xff, 0x10);
+}
+
+static void platina_tianma_deinit_cmds(struct mipi_dsi_multi_context *dsi_ctx)
+{
+ /* Stock disables ESD before display-off/sleep; these are sent by unprepare. */
+ dsi_ctx->dsi->mode_flags &= ~MIPI_DSI_MODE_LPM;
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xff, 0x24);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xfb, 0x01);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xc3, 0x00);
+ mipi_dsi_dcs_write_seq_multi(dsi_ctx, 0xff, 0x10);
+}
+
+static const struct drm_display_mode platina_tianma_mode = {
+ .clock = (1080 + 92 + 20 + 140) * (2280 + 16 + 2 + 10) * 60 / 1000,
+ .hdisplay = 1080,
+ .hsync_start = 1080 + 92,
+ .hsync_end = 1080 + 92 + 20,
+ .htotal = 1080 + 92 + 20 + 140,
+ .vdisplay = 2280,
+ .vsync_start = 2280 + 16,
+ .vsync_end = 2280 + 16 + 2,
+ .vtotal = 2280 + 16 + 2 + 10,
+ .type = DRM_MODE_TYPE_DRIVER | DRM_MODE_TYPE_PREFERRED,
+};
+
+static const struct nt36672a_panel_desc platina_tianma_panel_desc = {
+ .display_mode = &platina_tianma_mode,
+ .width_mm = 68,
+ .height_mm = 144,
+ .mode_flags = MIPI_DSI_MODE_VIDEO | MIPI_DSI_MODE_VIDEO_BURST |
+ MIPI_DSI_MODE_VIDEO_HSE | MIPI_DSI_MODE_LPM,
+ .format = MIPI_DSI_FMT_RGB888,
+ .lanes = 4,
+ .reset_pulse = true,
+ .send_init_cmds = platina_tianma_init_cmds,
+ .send_deinit_cmds = platina_tianma_deinit_cmds,
+};
+
static const struct of_device_id panel_nt36672a_match[] = {
+ { .compatible = "xiaomi,platina-tianma-nt36672a", .data = &platina_tianma_panel_desc },
{ .compatible = "shenchao,fhdplus-video", .data = &shenchao_lavender_panel_desc },
{ .compatible = "tianma,fhd-video", .data = &tianma_fhd_video_panel_desc },
{ .compatible = "tianma,tl060fvxs16-00", .data = &tianma_jasmine_panel_desc },
--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
@@ -842,12 +842,12 @@
vdda-supply = <&vreg_l1a_1p225>;
panel: panel@0 {
- compatible = "xiaomi,platina-td4320", "boe,td4320";
+ compatible = "xiaomi,platina-tianma-nt36672a", "novatek,nt36672a";
reg = <0>;
- iovcc-supply = <&vreg_l11a_1p8>;
- vsp-supply = <&panel_vsp>;
- vsn-supply = <&panel_vsn>;
+ vddio-supply = <&vreg_l11a_1p8>;
+ vddpos-supply = <&panel_vsp>;
+ vddneg-supply = <&panel_vsn>;
reset-gpios = <&tlmm 53 GPIO_ACTIVE_LOW>;
--- a/Documentation/devicetree/bindings/display/panel/novatek,nt36672a.yaml
+++ b/Documentation/devicetree/bindings/display/panel/novatek,nt36672a.yaml
@@ -23,7 +23,8 @@
items:
- enum:
- shenchao,fhdplus-video
- - tianma,fhd-video
+ - xiaomi,platina-tianma-nt36672a
+ - tianma,fhd-video
- tianma,tl060fvxs16-00
- tianma,tl063fvmca01-00
- tianma,tl063fvmc43-02
@@ -0,0 +1,155 @@
# Kernel config based on: arch/arm64/configs/sdm660_defconfig
maintainer="Alexey Minnekhanov <alexeymin@minlexx.ru>"
_flavor="postmarketos-qcom-sdm660"
pkgname=linux-$_flavor
pkgver=7.2.12
pkgrel=1
pkgdesc="Close to mainline linux kernel for Qualcomm Snapdragon 660 SoC"
arch="aarch64"
url="https://kernel.org/"
license="GPL-2.0-only"
options="!strip !check !tracedeps
pmb:cross-native
pmb:kconfigcheck-community
"
makedepends="
bison
clang
findutils
flex
lld
llvm
openssl-dev
perl
postmarketos-installkernel
python3
zstd
pahole
linux-headers
elfutils-dev
"
_commit="dd1ed52c8ceef4f16715118ed0252fe75adbe71d"
source="
linux-$_commit.tar.gz::https://codeload.github.com/sdm660-mainline/linux/tar.gz/$_commit
config-$_flavor.aarch64
0001-platina-enable-display.patch
0002-panel-simple-td4320.patch
0004-synaptics-tcm-driver.patch
0006-platina-battery.patch
0007-platina-wifi.patch
0010-ath10k-wcn3990-no-psmode.patch
0011-ath10k-wcn3990-chanlist-qcacld.patch
0012-ath10k-wcn3990-scan-trailing-tlvs.patch
0014-ath10k-wcn3990-no-scan-chan-stat.patch
0015-clk-qcom-sdm660-cpu-osm-driver.patch
0016-arm64-dts-sdm660-platina-osm-cpufreq.patch
0017-clk-qcom-sdm660-cprh-driver.patch
0018-platina-audio.patch
0020-tfa9894-codec.patch
0021-platina-speaker.patch
0024-platina-sec-mi2s-pinctrl.patch
0022-platina-bluetooth.patch
0025-platina-vibrator.patch
0026-platina-7.2-wifi-debug.patch
0027-platina-7.2-audio-machine.patch
0028-platina-touch-regulator-cleanup.patch
0029-sdm660-mdp-clock-safe-rate-change.patch
0030-platina-tianma-panel.patch
stable-7.2.3-4.patch
stable-7.2.4-5.patch
stable-7.2.5-6.patch
stable-7.2.6-7.patch
stable-7.2.7-8.patch
stable-7.2.8-9.patch
stable-7.2.9-10.patch
stable-7.2.10-11.patch
stable-7.2.11-12.patch
"
_carch="arm64"
# for some reason, the directory inside .tar.gz does not match tag name: leading
# "v" is missing, so we can't use $_tag here
builddir="$srcdir/linux-$_commit"
prepare() {
default_prepare
cp -v "$srcdir/config-$_flavor.$CARCH" "$builddir"/.config
}
build() {
unset LDFLAGS
make ARCH="$_carch" LLVM=1 \
KBUILD_BUILD_VERSION="$((pkgrel + 1 ))-$_flavor" all Image.gz
}
package() {
mkdir -p "$pkgdir"/boot
make modules_install dtbs_install \
ARCH="$_carch" \
LLVM=1 \
INSTALL_PATH="$pkgdir"/boot \
INSTALL_MOD_PATH="$pkgdir"/usr \
INSTALL_MOD_STRIP=1 \
INSTALL_DTBS_PATH="$pkgdir/boot/dtbs-tmp"
install -D "$builddir/arch/arm64/boot/vmlinuz.efi" \
"$pkgdir/boot/vmlinuz.efi"
install -D "$builddir/arch/arm64/boot/Image.gz" \
"$pkgdir/boot/vmlinuz"
# Reduce package size, install only qcom SDM630/636/660 dtbs.
# This reduces .apk size from ~46 Mb to ~30 Mb.
mkdir -p "$pkgdir"/boot/dtbs/qcom
cp -r "$pkgdir"/boot/dtbs-tmp/qcom/sda660* "$pkgdir"/boot/dtbs/qcom
cp -r "$pkgdir"/boot/dtbs-tmp/qcom/sdm630* "$pkgdir"/boot/dtbs/qcom
cp -r "$pkgdir"/boot/dtbs-tmp/qcom/sdm636* "$pkgdir"/boot/dtbs/qcom
cp -r "$pkgdir"/boot/dtbs-tmp/qcom/sdm660* "$pkgdir"/boot/dtbs/qcom
rm -r "$pkgdir"/boot/dtbs-tmp
rm -f "$pkgdir"/lib/modules/*/build "$pkgdir"/lib/modules/*/source
install -D "$builddir/include/config/kernel.release" \
"$pkgdir/usr/share/kernel/$_flavor/kernel.release"
}
sha512sums="
b56636f4d7429e971a70c1b7237fda4d5795fbe422c01f6fc6038220c2e831bf4479bd411b5e04e4db45de4fb8ec15a9e0e312b6479e2067709062af3dfd6997 linux-dd1ed52c8ceef4f16715118ed0252fe75adbe71d.tar.gz
2a21ce86163c1f33d2fc8bf1d84823c4c6221f67abdcb32e7a11f27325eb5dc7ffc968bc56d15b469aa5aa4b8381ba077e6abe018bd69a69049124e331228304 config-postmarketos-qcom-sdm660.aarch64
0ed47ad2e1cf773a49ab542b4f6ccc2baf61a4186e51cda8f70bacce6c30c687305f8c7f327cdd9b3919358ca18eaac28c7c9b82bfec73e5fe492663afdec825 0001-platina-enable-display.patch
83b9efa9b1a46499d1936f9e3f90b832458ace687a5ad3892ae1787a09997491efb9cc1bb0db44007adda97900ae2e3ce1b7dafa28ecb4cd84a95ade8667f05b 0002-panel-simple-td4320.patch
2ff1034abfbaf3c5bf56233b46a6c5a066015a982d4e55e5fd34c5d908d145305c7a99fd7731057b8fd5b9afc3e595b60856f6e0a0af921cfbff068eb744757b 0004-synaptics-tcm-driver.patch
727180fca4f9846de890f73cc8636e3a1eccb8a05b0ad60613407e967857b377356c8380d2fa27b453cf4bc63b71d8be45b09b0039396794ba16259dcc9d5901 0006-platina-battery.patch
c7d469c265fcae3280a008a3114cd516bb0a90dfe25ad5357bd09ba48175bf79ce589c661fec71ff83e48887d90b9b1e987a04ad5de03130e9e1212f0f470966 0007-platina-wifi.patch
f7a8b7272ccb70b6a3a0049006ec608960fd876bf43ebf2c5880c92d1e55e7953a31dff37a2b219756f39e5baac4e8d6beee1407094fd07e812d513e9cd8397c 0010-ath10k-wcn3990-no-psmode.patch
e8a8b9382cdb3543b9ed73d309bfc37d41be96852b92ba46beed78b880186e71e3d73a151acb9893f8f13764e9265bf5a50865b2c2329feeb064039b70721091 0011-ath10k-wcn3990-chanlist-qcacld.patch
a60a9faec11342f4ac0388b612edbbbe132269d2fd68bbbd2709fa0af068f1c9d27b57d5ebf0c6fc99792609eee0d715572ec160e41698bf0ae11a5c5cab7cf1 0012-ath10k-wcn3990-scan-trailing-tlvs.patch
ae81f328100b9a6f756c68f5fcda2618ea866349c2ce291703f5f817b42d3a0954c772ed6f063d8132f522837e3eaa2978c61564cd19536f4442eb381e636680 0014-ath10k-wcn3990-no-scan-chan-stat.patch
f8a47c452ec42a4c9278bd7e40e83ecea1d18c6eb76099e8e5526788275e2afac24bc2b415c22e1e41a3fda14ce07dc968e3e7e95b91122226a1fb098b027305 0015-clk-qcom-sdm660-cpu-osm-driver.patch
36aef2306a6bb302e69891bf6619cfdfa81bc2e09cd2e4a2a15371f39af5755cf1045e061a1561d7375d8cfd8659dd2d81cab0296c62d90f7b256894fa28ea14 0016-arm64-dts-sdm660-platina-osm-cpufreq.patch
71cd673724dda58e0af4c50d428d3739114eb32640da84823c84ffb8342ab1106f361cc5c780d58827bbc854285f06acdce17ffa486d3a4d14b786c1c415e318 0017-clk-qcom-sdm660-cprh-driver.patch
110ad7640090163637a29fa61d5901b7424a2516be9f3131094fbecdb0ce69d705b3584a49ce27ae1d7c3319eefac974912e78fa65ede2baadd4135f724fc20b 0018-platina-audio.patch
49e5d4ffac1120cade440bc5df28995686a074699b36874e52cf49c33cf2b3e74012c819cd1d0040738af153bf3273635702c9b8a955f1984b2cc6bd541e85de 0020-tfa9894-codec.patch
93d75da385d8b8fd93bfc038a182ddecab8dd1367a7b0c937c3a73160699749c78154454d957cb740d16d6ad1b2afa72ab453581138f78ec4e884787c3997fac 0021-platina-speaker.patch
af6e09b560c497300e57b5b74ce5e8f59740091045a9dcd0dc8299018d9ff88b958c6476a5c1fc00060d649118e34011bd5481261aa52f1b56d1d522618bbf76 0024-platina-sec-mi2s-pinctrl.patch
ae97edcc2302b088a3d83539139199e9f5a19c3a11f66a3512b979b93673755f300b6458f7ddfaaa769b9f735e9d99f7abcbca37951e6cb767a6239e245cdf8b 0022-platina-bluetooth.patch
73eb732191f8ea7ce41a0810b390f407e525a4cecf317e7ead8ce42b1b7fd0b249c37619b0164e1c9241dbe53a605f7d6681ce589dc506a36f1a40b891db328d 0025-platina-vibrator.patch
1bb9b6f31c3e8c5847bd41dd5e2ad1971842bde316d027bd5a5f262febc53566a1542027d8ee726a83947f2b9a5f6e0c76bee138771cdef3368601d99fd071b9 0026-platina-7.2-wifi-debug.patch
81bb48b72a639df602deb7447dcb7c28e56daa14e5d86b76a49f8ac7b2cea10f8c38cabdeee61448408097ac765596539245fec9e3f3f3379fe7451438f8108f 0027-platina-7.2-audio-machine.patch
c04261993d81ae94ae8f6e86df93e6e37390fd8b7746f8d54eaf957e818cdf92691fdeb8b9a5adae220fcd199189aea268c837b6482e13a70a9de9aeaafaacc5 0028-platina-touch-regulator-cleanup.patch
07f552abed2177d7c0a4fd731692c934d54f8ad4d117ecad3e1eab4ceedd546b07c6fc01c693dae65a09fc1581b987db4bb7f3cdffa4488b20919a32a1790621 0029-sdm660-mdp-clock-safe-rate-change.patch
e845d83a8bb8e7bb7cc59bb309b78b920460f4d31b9c962e00119321e3f01a65bfcc2cc3185d609a0b99a73c9deed5d705d58afdf06d8dac2e409ad15f821d68 0030-platina-tianma-panel.patch
1a7f9cf2443c0f059ac64a78dddee77fca584288edeea943aa45db05fb5e3b7b2930dab595f6c0911671bf5517bd64550a65b097f47d5179cc7454ec90db56cd stable-7.2.3-4.patch
303d4a717c67d5dbb5d17c37882b3ef1b6b44b3cf9b17723a611efe1f028019d5ef53c0e3595ed79f5468a46ede2d640171b9dd97ce2dd99b487d0406ef79f16 stable-7.2.4-5.patch
b09a94d0eb3c0382ad8998843019ea0d52ae5a89ad7ba54072b21eeea2c7ee602c57a32a0d9b99a2c5ae1f581dadc4d4395096e905b54678affc18125d9b8cba stable-7.2.5-6.patch
4b527cf54dd581408cbb44ace82ea975baa656cf12c9cd35356ce6c4e05901c27d498c3b3a956f84dcf5f5ac436da39cb37cd535353f024c7877e315f455062e stable-7.2.6-7.patch
526e8061f3906876bcd9db2f7c82a31c438c2d2c56701208041edb932bd66473ff8f221b22af24b687f14e85852dbbb1d8058cdc63f29ca30f14bb1590216733 stable-7.2.7-8.patch
e34cc3b376501b8db887eeb79950adb84906641062ef0e60a9bdbedb3b43e956dd5c56f1967df8ad274454c3d9df03867c37dcf62cdb5d80a9a59eddfa831776 stable-7.2.8-9.patch
be7770c858be5b7b559b959fc6f50ca6d94a7f518ee67c8e675e01ab583fc043c10cbeb6971079a13394a981f8153906839cdf409fef6f4279709ecc93495eff stable-7.2.9-10.patch
d2449e4c02bf11835d20bd9c841a3b0db78ba14ebe2effaec04d98db63ea4dc41a552d23db8ae72e10d2675d1b20570f06a250c790dc773f95f0be4a14c706e9 stable-7.2.10-11.patch
eb3b89ac99648776f193ee3c9d96d257f7d2e6ba5200a526e63c97e7dc4982e4b2985f15481aa4314dc54ca5f0bafb395b4f4fc375ed4fba2b8d9ca23124cd31 stable-7.2.11-12.patch
"
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,790 @@
diff --git a/Makefile b/Makefile
index 4b60c83ab75c17..a550506403fe15 100644
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: GPL-2.0
VERSION = 7
PATCHLEVEL = 2
-SUBLEVEL = 11
+SUBLEVEL = 12
EXTRAVERSION =
NAME = Baby Opossum Posse
diff --git a/arch/x86/kvm/x86.h b/arch/x86/kvm/x86.h
index 9973f905955a78..ded77a4c8069ac 100644
--- a/arch/x86/kvm/x86.h
+++ b/arch/x86/kvm/x86.h
@@ -313,7 +313,7 @@ static inline bool is_noncanonical_invlpg_address(u64 la, struct kvm_vcpu *vcpu)
static inline void vcpu_cache_mmio_info(struct kvm_vcpu *vcpu,
gva_t gva, gfn_t gfn, unsigned access)
{
- u64 gen = kvm_memslots(vcpu->kvm)->generation;
+ u64 gen = kvm_vcpu_memslots(vcpu)->generation;
if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
return;
@@ -330,7 +330,7 @@ static inline void vcpu_cache_mmio_info(struct kvm_vcpu *vcpu,
static inline bool vcpu_match_mmio_gen(struct kvm_vcpu *vcpu)
{
- return vcpu->arch.mmio_gen == kvm_memslots(vcpu->kvm)->generation;
+ return vcpu->arch.mmio_gen == kvm_vcpu_memslots(vcpu)->generation;
}
/*
diff --git a/drivers/md/dm-integrity.c b/drivers/md/dm-integrity.c
index 4bda7b5dba1a64..3b36f4b8ec67b3 100644
--- a/drivers/md/dm-integrity.c
+++ b/drivers/md/dm-integrity.c
@@ -180,6 +180,7 @@ struct dm_integrity_c {
struct dm_bufio_client *bufio;
struct workqueue_struct *metadata_wq;
struct superblock *sb;
+ struct superblock *sb_copy;
unsigned int journal_pages;
unsigned int n_bitmap_blocks;
@@ -3857,6 +3858,35 @@ static void dm_integrity_postsuspend(struct dm_target *ti)
ic->journal_uptodate = true;
}
+/*
+ * The superblock is re-read from the device on every resume, so that we pick
+ * up the flags and the recalculate position. The geometry described by the
+ * superblock must not change though - the in-memory structures (and the
+ * journal in particular) were sized according to the superblock that was
+ * validated in the constructor. Reject a superblock that was modified behind
+ * our back.
+ *
+ * Only the fields that the driver never rewrites may be tested here. In
+ * particular, "version" is recalculated by sb_set_version on every superblock
+ * write and it depends on SB_FLAG_RECALCULATING and SB_FLAG_DIRTY_BITMAP, and
+ * SB_FLAG_DISCARD_KEYED may be set by dm_integrity_resume itself.
+ */
+static bool superblock_changed(struct dm_integrity_c *ic)
+{
+ const __le32 immutable_flags = cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC |
+ SB_FLAG_FIXED_PADDING |
+ SB_FLAG_FIXED_HMAC |
+ SB_FLAG_INLINE);
+
+ return memcmp(ic->sb->magic, ic->sb_copy->magic, sizeof(ic->sb->magic)) != 0 ||
+ ic->sb->log2_interleave_sectors != ic->sb_copy->log2_interleave_sectors ||
+ ic->sb->integrity_tag_size != ic->sb_copy->integrity_tag_size ||
+ ic->sb->journal_sections != ic->sb_copy->journal_sections ||
+ ic->sb->log2_sectors_per_block != ic->sb_copy->log2_sectors_per_block ||
+ ((ic->sb->flags ^ ic->sb_copy->flags) & immutable_flags) != 0 ||
+ memcmp(ic->sb->salt, ic->sb_copy->salt, SALT_SIZE) != 0;
+}
+
static void dm_integrity_resume(struct dm_target *ti)
{
struct dm_integrity_c *ic = ti->private;
@@ -3874,6 +3904,22 @@ static void dm_integrity_resume(struct dm_target *ti)
r = sync_rw_sb(ic, REQ_OP_READ);
if (r)
dm_integrity_io_error(ic, "reading superblock", r);
+
+ if (unlikely(superblock_changed(ic))) {
+ /*
+ * Restore the superblock that we validated in the constructor,
+ * so that the rest of the driver doesn't operate on values
+ * that don't match the in-memory structures.
+ */
+ memcpy(ic->sb, ic->sb_copy, sizeof(struct superblock));
+ DMERR("The superblock was changed while the device was suspended");
+ dm_integrity_io_error(ic, "superblock check", -EINVAL);
+ goto skip_writes;
+ }
+
+ if (ic->mode == 'R')
+ goto skip_writes;
+
if ((ic->sb->flags & flags) != flags) {
ic->sb->flags |= flags;
r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
@@ -3983,6 +4029,7 @@ static void dm_integrity_resume(struct dm_target *ti)
}
}
+skip_writes:
ic->reboot_notifier.notifier_call = dm_integrity_reboot;
ic->reboot_notifier.next = NULL;
ic->reboot_notifier.priority = INT_MAX - 1; /* be notified after md and before hardware drivers */
@@ -5416,6 +5463,13 @@ try_smaller_buffer:
ic->just_formatted = true;
}
+ ic->sb_copy = kmemdup(ic->sb, sizeof(struct superblock), GFP_KERNEL);
+ if (!ic->sb_copy) {
+ ti->error = "Cannot allocate superblock copy";
+ r = -ENOMEM;
+ goto bad;
+ }
+
if (!ic->meta_dev && ic->mode != 'I') {
r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
if (r)
@@ -5514,6 +5568,7 @@ static void dm_integrity_dtr(struct dm_target *ti)
kvfree(ic->journal_tree);
if (ic->sb)
free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
+ kfree(ic->sb_copy);
if (ic->internal_shash)
crypto_free_shash(ic->internal_shash);
diff --git a/drivers/net/ethernet/microsoft/mana/mana_bpf.c b/drivers/net/ethernet/microsoft/mana/mana_bpf.c
index 5c9961ee9747ab..b27fd9b8c4f6d8 100644
--- a/drivers/net/ethernet/microsoft/mana/mana_bpf.c
+++ b/drivers/net/ethernet/microsoft/mana/mana_bpf.c
@@ -91,7 +91,7 @@ u32 mana_run_xdp(struct net_device *ndev, struct mana_rxq *rxq,
goto out;
xdp_init_buff(xdp, PAGE_SIZE, &rxq->xdp_rxq);
- xdp_prepare_buff(xdp, buf_va, XDP_PACKET_HEADROOM, pkt_len, true);
+ xdp_prepare_buff(xdp, buf_va, rxq->headroom, pkt_len, true);
act = bpf_prog_run_xdp(prog, xdp);
@@ -183,9 +183,9 @@ static int mana_xdp_set(struct net_device *ndev, struct bpf_prog *prog,
if (!old_prog && !prog)
return 0;
- if (prog && ndev->mtu > MANA_XDP_MTU_MAX) {
+ if (prog && ndev->mtu > MANA_XDP_MTU_MAX(ndev)) {
netdev_err(ndev, "XDP: mtu:%u too large, mtu_max:%lu\n",
- ndev->mtu, MANA_XDP_MTU_MAX);
+ ndev->mtu, MANA_XDP_MTU_MAX(ndev));
NL_SET_ERR_MSG_MOD(extack, "XDP: mtu too large");
return -EOPNOTSUPP;
@@ -238,7 +238,7 @@ static int mana_xdp_set(struct net_device *ndev, struct bpf_prog *prog,
bpf_prog_put(old_prog);
if (prog)
- ndev->max_mtu = min_t(unsigned int, MANA_XDP_MTU_MAX,
+ ndev->max_mtu = min_t(unsigned int, MANA_XDP_MTU_MAX(ndev),
gc->adapter_mtu - ETH_HLEN);
else
ndev->max_mtu = gc->adapter_mtu - ETH_HLEN;
diff --git a/drivers/net/ethernet/microsoft/mana/mana_en.c b/drivers/net/ethernet/microsoft/mana/mana_en.c
index 8fb29dcddf8e2e..af5d4a4f56f165 100644
--- a/drivers/net/ethernet/microsoft/mana/mana_en.c
+++ b/drivers/net/ethernet/microsoft/mana/mana_en.c
@@ -755,26 +755,62 @@ static void *mana_get_rxbuf_pre(struct mana_rxq *rxq, dma_addr_t *da)
return va;
}
-/* Get RX buffer's data size, alloc size, XDP headroom based on MTU */
+/* Reserve enough headroom to satisfy the skb_cow() in ip_forward() and avoid
+ * reallocation: the TX path keeps the SGE DMA mappings in struct mana_skb_head
+ * at skb->head, so the port advertises ndev->needed_headroom = MANA_HEADROOM.
+ */
+static u32 mana_get_rxbuf_headroom(struct mana_port_context *apc)
+{
+ if (mana_xdp_get(apc))
+ return mana_xdp_headroom(apc->ndev);
+
+ return LL_RESERVED_SPACE(apc->ndev);
+}
+
+static u32 mana_get_rxbuf_size(struct mana_port_context *apc, u32 mtu)
+{
+ u32 len = SKB_DATA_ALIGN(mtu + MANA_RXBUF_PAD +
+ mana_get_rxbuf_headroom(apc));
+
+ return ALIGN(len, MANA_RX_FRAG_ALIGNMENT);
+}
+
+/* Returns true when one RX buffer per page is already required by XDP or by
+ * the buffer size implied by the MTU, i.e. regardless of the
+ * MANA_PRIV_FLAG_USE_FULL_PAGE_RXBUF private flag.
+ */
+bool mana_single_rxbuf_per_page_forced(struct mana_port_context *apc, u32 mtu)
+{
+ /* For xdp make sure only one packet fits per page. */
+ if (mana_xdp_get(apc))
+ return true;
+
+ /* Only use the page_pool fragment path when at least two buffers,
+ * including the headroom each of them has to reserve, actually fit
+ * into one page. Otherwise the fragment path degenerates into one
+ * buffer per page while still paying the fragment accounting cost.
+ */
+ return PAGE_SIZE / mana_get_rxbuf_size(apc, mtu) < 2;
+}
+
+/* Get RX buffer's data size, alloc size, headroom and frag count based on MTU */
static void mana_get_rxbuf_cfg(struct mana_port_context *apc,
int mtu, u32 *datasize, u32 *alloc_size,
u32 *headroom, u32 *frag_count)
{
- u32 len, buf_size;
+ u32 buf_size;
/* Calculate datasize first (consistent across all cases) */
*datasize = mtu + ETH_HLEN;
- /* For xdp and jumbo frames make sure only one packet fits per page */
- if (mtu + MANA_RXBUF_PAD > PAGE_SIZE / 2 || mana_xdp_get(apc)) {
- if (mana_xdp_get(apc)) {
- *headroom = XDP_PACKET_HEADROOM;
+ *headroom = mana_get_rxbuf_headroom(apc);
+
+ if (mana_single_rxbuf_per_page_forced(apc, mtu)) {
+ if (mana_xdp_get(apc))
*alloc_size = PAGE_SIZE;
- } else {
- *headroom = 0; /* no support for XDP */
+ else
*alloc_size = SKB_DATA_ALIGN(mtu + MANA_RXBUF_PAD +
*headroom);
- }
*frag_count = 1;
@@ -788,11 +824,7 @@ static void mana_get_rxbuf_cfg(struct mana_port_context *apc,
}
/* Standard MTU case - optimize for multiple packets per page */
- *headroom = 0;
-
- /* Calculate base buffer size needed */
- len = SKB_DATA_ALIGN(mtu + MANA_RXBUF_PAD + *headroom);
- buf_size = ALIGN(len, MANA_RX_FRAG_ALIGNMENT);
+ buf_size = mana_get_rxbuf_size(apc, mtu);
/* Calculate how many packets can fit in a page */
*frag_count = PAGE_SIZE / buf_size;
diff --git a/drivers/net/ethernet/microsoft/mana/mana_ethtool.c b/drivers/net/ethernet/microsoft/mana/mana_ethtool.c
index 881df597d7f9c7..3531abfdaf4338 100644
--- a/drivers/net/ethernet/microsoft/mana/mana_ethtool.c
+++ b/drivers/net/ethernet/microsoft/mana/mana_ethtool.c
@@ -138,53 +138,70 @@ static int mana_get_sset_count(struct net_device *ndev, int stringset)
struct mana_port_context *apc = netdev_priv(ndev);
unsigned int num_queues = apc->num_queues;
- if (stringset != ETH_SS_STATS)
+ switch (stringset) {
+ case ETH_SS_STATS:
+ return ARRAY_SIZE(mana_eth_stats) +
+ ARRAY_SIZE(mana_phy_stats) +
+ ARRAY_SIZE(mana_hc_stats) +
+ num_queues * (MANA_STATS_RX_COUNT + MANA_STATS_TX_COUNT);
+ default:
return -EINVAL;
-
- return ARRAY_SIZE(mana_eth_stats) + ARRAY_SIZE(mana_phy_stats) + ARRAY_SIZE(mana_hc_stats) +
- num_queues * (MANA_STATS_RX_COUNT + MANA_STATS_TX_COUNT);
+ }
}
-static void mana_get_strings(struct net_device *ndev, u32 stringset, u8 *data)
+static void mana_get_strings_stats(struct mana_port_context *apc, u8 **data)
{
- struct mana_port_context *apc = netdev_priv(ndev);
unsigned int num_queues = apc->num_queues;
int i, j;
- if (stringset != ETH_SS_STATS)
- return;
for (i = 0; i < ARRAY_SIZE(mana_eth_stats); i++)
- ethtool_puts(&data, mana_eth_stats[i].name);
+ ethtool_puts(data, mana_eth_stats[i].name);
for (i = 0; i < ARRAY_SIZE(mana_hc_stats); i++)
- ethtool_puts(&data, mana_hc_stats[i].name);
+ ethtool_puts(data, mana_hc_stats[i].name);
for (i = 0; i < ARRAY_SIZE(mana_phy_stats); i++)
- ethtool_puts(&data, mana_phy_stats[i].name);
+ ethtool_puts(data, mana_phy_stats[i].name);
for (i = 0; i < num_queues; i++) {
- ethtool_sprintf(&data, "rx_%d_packets", i);
- ethtool_sprintf(&data, "rx_%d_bytes", i);
- ethtool_sprintf(&data, "rx_%d_xdp_drop", i);
- ethtool_sprintf(&data, "rx_%d_xdp_tx", i);
- ethtool_sprintf(&data, "rx_%d_xdp_redirect", i);
- ethtool_sprintf(&data, "rx_%d_pkt_len0_err", i);
+ ethtool_sprintf(data, "rx_%d_packets", i);
+ ethtool_sprintf(data, "rx_%d_bytes", i);
+ ethtool_sprintf(data, "rx_%d_xdp_drop", i);
+ ethtool_sprintf(data, "rx_%d_xdp_tx", i);
+ ethtool_sprintf(data, "rx_%d_xdp_redirect", i);
+ ethtool_sprintf(data, "rx_%d_pkt_len0_err", i);
for (j = 0; j < MANA_RXCOMP_OOB_NUM_PPI - 1; j++)
- ethtool_sprintf(&data, "rx_%d_coalesced_cqe_%d", i, j + 2);
+ ethtool_sprintf(data,
+ "rx_%d_coalesced_cqe_%d",
+ i,
+ j + 2);
}
for (i = 0; i < num_queues; i++) {
- ethtool_sprintf(&data, "tx_%d_packets", i);
- ethtool_sprintf(&data, "tx_%d_bytes", i);
- ethtool_sprintf(&data, "tx_%d_xdp_xmit", i);
- ethtool_sprintf(&data, "tx_%d_tso_packets", i);
- ethtool_sprintf(&data, "tx_%d_tso_bytes", i);
- ethtool_sprintf(&data, "tx_%d_tso_inner_packets", i);
- ethtool_sprintf(&data, "tx_%d_tso_inner_bytes", i);
- ethtool_sprintf(&data, "tx_%d_long_pkt_fmt", i);
- ethtool_sprintf(&data, "tx_%d_short_pkt_fmt", i);
- ethtool_sprintf(&data, "tx_%d_csum_partial", i);
- ethtool_sprintf(&data, "tx_%d_mana_map_err", i);
+ ethtool_sprintf(data, "tx_%d_packets", i);
+ ethtool_sprintf(data, "tx_%d_bytes", i);
+ ethtool_sprintf(data, "tx_%d_xdp_xmit", i);
+ ethtool_sprintf(data, "tx_%d_tso_packets", i);
+ ethtool_sprintf(data, "tx_%d_tso_bytes", i);
+ ethtool_sprintf(data, "tx_%d_tso_inner_packets", i);
+ ethtool_sprintf(data, "tx_%d_tso_inner_bytes", i);
+ ethtool_sprintf(data, "tx_%d_long_pkt_fmt", i);
+ ethtool_sprintf(data, "tx_%d_short_pkt_fmt", i);
+ ethtool_sprintf(data, "tx_%d_csum_partial", i);
+ ethtool_sprintf(data, "tx_%d_mana_map_err", i);
+ }
+}
+
+static void mana_get_strings(struct net_device *ndev, u32 stringset, u8 *data)
+{
+ struct mana_port_context *apc = netdev_priv(ndev);
+
+ switch (stringset) {
+ case ETH_SS_STATS:
+ mana_get_strings_stats(apc, &data);
+ break;
+ default:
+ break;
}
}
diff --git a/drivers/net/wireless/ath/ath9k/wmi.c b/drivers/net/wireless/ath/ath9k/wmi.c
index 4a08babb6d9d67..44e91815a15943 100644
--- a/drivers/net/wireless/ath/ath9k/wmi.c
+++ b/drivers/net/wireless/ath/ath9k/wmi.c
@@ -206,16 +206,9 @@ static void ath9k_wmi_rsp_callback(struct wmi *wmi, struct sk_buff *skb)
{
skb_pull(skb, sizeof(struct wmi_cmd_hdr));
- if (wmi->cmd_rsp_buf && wmi->cmd_rsp_len) {
- if (skb->len < wmi->cmd_rsp_len) {
- wmi->cmd_rsp_status = -EMSGSIZE;
- goto complete;
- }
+ if (wmi->cmd_rsp_buf != NULL && wmi->cmd_rsp_len != 0)
memcpy(wmi->cmd_rsp_buf, skb->data, wmi->cmd_rsp_len);
- }
- wmi->cmd_rsp_status = 0;
-complete:
complete(&wmi->cmd_wait);
}
@@ -307,7 +300,6 @@ static int ath9k_wmi_cmd_issue(struct wmi *wmi,
/* record the rsp buffer and length */
wmi->cmd_rsp_buf = rsp_buf;
wmi->cmd_rsp_len = rsp_len;
- wmi->cmd_rsp_status = 0;
wmi->last_seq_id = wmi->tx_seq_id;
spin_unlock_irqrestore(&wmi->wmi_lock, flags);
@@ -364,13 +356,9 @@ int ath9k_wmi_cmd(struct wmi *wmi, enum wmi_cmd_id cmd_id,
return -ETIMEDOUT;
}
- spin_lock_irqsave(&wmi->wmi_lock, flags);
- ret = wmi->cmd_rsp_status;
- spin_unlock_irqrestore(&wmi->wmi_lock, flags);
-
mutex_unlock(&wmi->op_mutex);
- return ret;
+ return 0;
out:
ath_dbg(common, WMI, "WMI failure for: %s\n", wmi_cmd_to_name(cmd_id));
diff --git a/drivers/net/wireless/ath/ath9k/wmi.h b/drivers/net/wireless/ath/ath9k/wmi.h
index 0bb9d31f1a1cc4..5c3b710b8f3190 100644
--- a/drivers/net/wireless/ath/ath9k/wmi.h
+++ b/drivers/net/wireless/ath/ath9k/wmi.h
@@ -157,7 +157,6 @@ struct wmi {
u16 tx_seq_id;
u8 *cmd_rsp_buf;
u32 cmd_rsp_len;
- int cmd_rsp_status;
bool stopped;
struct list_head pending_tx_events;
diff --git a/fs/nfsd/nfs4proc.c b/fs/nfsd/nfs4proc.c
index 939749709e416d..7c29557962b0e6 100644
--- a/fs/nfsd/nfs4proc.c
+++ b/fs/nfsd/nfs4proc.c
@@ -2243,6 +2243,8 @@ nfsd4_copy(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
goto out_dec_async_copy_err;
memcpy(&result->cb_stateid, &async_copy->cp_stateid.cs_stid,
sizeof(result->cb_stateid));
+ memcpy(&async_copy->cp_res.cb_stateid, &async_copy->cp_stateid.cs_stid,
+ sizeof(async_copy->cp_res.cb_stateid));
if ((READ_ONCE(copy->nf_dst->nf_file->f_mode) &
FMODE_NOCMTIME) != 0)
async_copy->attr_update = true;
diff --git a/fs/nullfs.c b/fs/nullfs.c
index 20d3aa627a47de..c89181daf208c2 100644
--- a/fs/nullfs.c
+++ b/fs/nullfs.c
@@ -8,6 +8,35 @@ static const struct super_operations nullfs_super_operations = {
.statfs = simple_statfs,
};
+static loff_t nullfs_dir_llseek(struct file *file, loff_t offset, int whence)
+{
+ /* an empty directory has two entries . and .. at offsets 0 and 1 */
+ return generic_file_llseek_size(file, offset, whence, 2, 2);
+}
+
+static int nullfs_dir_readdir(struct file *file, struct dir_context *ctx)
+{
+ dir_emit_dots(file, ctx);
+ return 0;
+}
+
+/* the one inode of nullfs is shared by every holder, so no locks on it */
+static int nullfs_nolock(struct file *file, int cmd, struct file_lock *fl)
+{
+ return -ENOLCK;
+}
+
+/* what libfs gives an empty directory, plus the refusal of file locks */
+static const struct file_operations nullfs_dir_operations = {
+ .llseek = nullfs_dir_llseek,
+ .read = generic_read_dir,
+ .iterate_shared = nullfs_dir_readdir,
+ .fsync = noop_fsync,
+ .lock = nullfs_nolock,
+ .flock = nullfs_nolock,
+ .fop_flags = FOP_IMMUTABLE,
+};
+
static int nullfs_fs_fill_super(struct super_block *s, struct fs_context *fc)
{
struct inode *inode;
@@ -28,6 +57,7 @@ static int nullfs_fs_fill_super(struct super_block *s, struct fs_context *fc)
/* nullfs is permanently empty... */
make_empty_dir_inode(inode);
+ inode->i_fop = &nullfs_dir_operations;
simple_inode_init_ts(inode);
inode->i_ino = 1;
/* ... and immutable, reading it leaves no trace either. */
diff --git a/fs/readdir.c b/fs/readdir.c
index 76bb1ae3a45041..f2288841337ad1 100644
--- a/fs/readdir.c
+++ b/fs/readdir.c
@@ -87,6 +87,8 @@ EXPORT_SYMBOL(wrap_directory_iterator);
int iterate_dir(struct file *file, struct dir_context *ctx)
{
struct inode *inode = file_inode(file);
+ /* never an entry, never removed: nothing for the lock to keep still */
+ bool locked = !(file->f_op->fop_flags & FOP_IMMUTABLE);
int res = -ENOTDIR;
if (!file->f_op->iterate_shared)
@@ -100,9 +102,11 @@ int iterate_dir(struct file *file, struct dir_context *ctx)
if (res)
goto out;
- res = down_read_killable(&inode->i_rwsem);
- if (res)
- goto out;
+ if (locked) {
+ res = down_read_killable(&inode->i_rwsem);
+ if (res)
+ goto out;
+ }
res = -ENOENT;
if (!IS_DEADDIR(inode)) {
@@ -112,7 +116,8 @@ int iterate_dir(struct file *file, struct dir_context *ctx)
fsnotify_access(file);
file_accessed(file);
}
- inode_unlock_shared(inode);
+ if (locked)
+ inode_unlock_shared(inode);
out:
return res;
}
diff --git a/fs/smb/server/smb2pdu.c b/fs/smb/server/smb2pdu.c
index 07de36aac0bffc..5f82dcd9a0b559 100644
--- a/fs/smb/server/smb2pdu.c
+++ b/fs/smb/server/smb2pdu.c
@@ -2098,7 +2098,7 @@ static int krb5_authenticate(struct ksmbd_work *work,
in_len = le16_to_cpu(req->SecurityBufferLength);
out_blob = (char *)&rsp->hdr.ProtocolId +
le16_to_cpu(rsp->SecurityBufferOffset);
- out_len = work->response_sz -
+ out_len = work->response_sz - work->next_smb2_rsp_hdr_off -
(le16_to_cpu(rsp->SecurityBufferOffset) + 4);
retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
diff --git a/include/linux/fs.h b/include/linux/fs.h
index 09de7bf6f1d28e..a07031fd4ae242 100644
--- a/include/linux/fs.h
+++ b/include/linux/fs.h
@@ -1980,6 +1980,8 @@ struct file_operations {
#define FOP_ASYNC_LOCK ((__force fop_flags_t)(1 << 6))
/* File system supports uncached read/write buffered IO */
#define FOP_DONTCACHE ((__force fop_flags_t)(1 << 7))
+/* Never changes and is never removed, readdir of a directory takes no lock */
+#define FOP_IMMUTABLE ((__force fop_flags_t)(1 << 8))
/* Wrap a directory iterator that needs exclusive inode access */
int wrap_directory_iterator(struct file *, struct dir_context *,
diff --git a/include/net/mana/mana.h b/include/net/mana/mana.h
index 04acb6791dbd97..cd44856fa474c8 100644
--- a/include/net/mana/mana.h
+++ b/include/net/mana/mana.h
@@ -328,7 +328,18 @@ struct mana_recv_buf_oob {
#define MANA_RXBUF_PAD (SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) \
+ ETH_HLEN)
-#define MANA_XDP_MTU_MAX (PAGE_SIZE - MANA_RXBUF_PAD - XDP_PACKET_HEADROOM)
+/* Headroom an RX buffer has to reserve while XDP is attached: the XDP program
+ * needs XDP_PACKET_HEADROOM, and the TX path needs LL_RESERVED_SPACE() (see
+ * mana_get_rxbuf_headroom()). LL_RESERVED_SPACE() grows with MAX_SKB_FRAGS and
+ * exceeds XDP_PACKET_HEADROOM once CONFIG_MAX_SKB_FRAGS is 19 or more.
+ */
+static inline u32 mana_xdp_headroom(struct net_device *ndev)
+{
+ return max_t(u32, LL_RESERVED_SPACE(ndev), XDP_PACKET_HEADROOM);
+}
+
+#define MANA_XDP_MTU_MAX(ndev) \
+ (PAGE_SIZE - MANA_RXBUF_PAD - mana_xdp_headroom(ndev))
struct mana_rxq {
struct gdma_queue *gdma_rq;
@@ -625,6 +636,7 @@ int mana_query_link_cfg(struct mana_port_context *apc);
int mana_set_bw_clamp(struct mana_port_context *apc, u32 speed,
int enable_clamping);
void mana_query_phy_stats(struct mana_port_context *apc);
+bool mana_single_rxbuf_per_page_forced(struct mana_port_context *apc, u32 mtu);
int mana_pre_alloc_rxbufs(struct mana_port_context *apc, int mtu, int num_queues);
void mana_pre_dealloc_rxbufs(struct mana_port_context *apc);
void mana_unmap_skb(struct sk_buff *skb, struct mana_port_context *apc);
diff --git a/include/sound/cs35l56.h b/include/sound/cs35l56.h
index 2490b72c0a7a8c..07434e644b89d5 100644
--- a/include/sound/cs35l56.h
+++ b/include/sound/cs35l56.h
@@ -312,6 +312,7 @@ struct snd_ctl_elem_value;
#define CS35L56_SDW1_PLAYBACK_PORT 1
#define CS35L56_SDW1_CAPTURE_PORT 3
+#define CS35L56_OT25_CAPTURE_PORT 4
#define CS35L56_NUM_BULK_SUPPLIES 3
#define CS35L56_NUM_DSP_REGIONS 5
diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c
index a9f33e2b17aceb..8d4992e7e01208 100644
--- a/kernel/sched/ext/ext.c
+++ b/kernel/sched/ext/ext.c
@@ -2031,8 +2031,8 @@ static void set_task_runnable(struct rq *rq, struct task_struct *p)
}
/*
- * list_add_tail() must be used. scx_bypass() depends on tasks being
- * appended to the runnable_list.
+ * list_add_tail() must be used. scx_bypass() and rq_offline_scx()
+ * depend on tasks being appended to the runnable_list.
*/
list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list);
}
@@ -2868,7 +2868,13 @@ scx_dispatch_sched(struct scx_sched *sch, struct rq *rq,
#endif /* CONFIG_EXT_SUB_SCHED */
}
- if (unlikely(!SCX_HAS_OP(sch, dispatch)) || !scx_rq_online(rq))
+ /*
+ * scx_rq_online() can't be used. Its cpu_active() test goes false
+ * before CPU hotplug waits for an RCU grace period, and
+ * rq_offline_scx() moves this CPU's tasks to the local DSQ only after
+ * the wait. The grace period can depend on those tasks running.
+ */
+ if (unlikely(!SCX_HAS_OP(sch, dispatch)) || !(rq->scx.flags & SCX_RQ_ONLINE))
return SCX_DSP_NONE;
dspc->rq = rq;
@@ -3608,7 +3614,24 @@ static void rq_online_scx(struct rq *rq)
static void rq_offline_scx(struct rq *rq)
{
+ struct task_struct *p, *n;
+
rq->scx.flags &= ~SCX_RQ_ONLINE;
+
+ /* sched domain rebuilds call rq_offline with the CPU staying alive */
+ if (cpu_active(cpu_of(rq)))
+ return;
+
+ /*
+ * An offline CPU no longer calls ops.dispatch(). Re-enqueue its tasks
+ * onto the local DSQ so that they run here and balance_push() moves
+ * them off.
+ */
+ list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list, scx.runnable_node) {
+ if (p->scx.dsq == &rq->scx.local_dsq)
+ continue;
+ guard(sched_change)(p, DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK);
+ }
}
static bool check_rq_for_timeouts(struct rq *rq)
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index a6c6f8165eecc8..d25defb116caae 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -4185,8 +4185,9 @@ extern void balance_callbacks(struct rq *rq, struct balance_callback *head);
* after which it is enqueued again.
*
* Typically this must be called while holding task_rq_lock, since most/all
- * properties are serialized under those locks. There is currently one
- * exception to this rule in sched/ext which only holds rq->lock.
+ * properties are serialized under those locks. There are currently two
+ * exceptions to this rule in sched/ext which only hold rq->lock: scx_bypass()
+ * and rq_offline_scx().
*/
/*
diff --git a/sound/soc/codecs/cs35l56-sdw.c b/sound/soc/codecs/cs35l56-sdw.c
index a3812ab4c02271..d52209111fe2ea 100644
--- a/sound/soc/codecs/cs35l56-sdw.c
+++ b/sound/soc/codecs/cs35l56-sdw.c
@@ -295,11 +295,11 @@ static int cs35l56_sdw_read_prop(struct sdw_slave *peripheral)
if (ret == 0)
prop->clk_stop_mode1 = !!clock_stop_1;
- ports = devm_kcalloc(cs35l56->base.dev, 2, sizeof(*ports), GFP_KERNEL);
+ ports = devm_kcalloc(cs35l56->base.dev, 3, sizeof(*ports), GFP_KERNEL);
if (!ports)
return -ENOMEM;
- prop->source_ports = BIT(CS35L56_SDW1_CAPTURE_PORT);
+ prop->source_ports = BIT(CS35L56_SDW1_CAPTURE_PORT) | BIT(CS35L56_OT25_CAPTURE_PORT);
prop->sink_ports = BIT(CS35L56_SDW1_PLAYBACK_PORT);
prop->paging_support = true;
prop->quirks = SDW_SLAVE_QUIRKS_INVALID_INITIAL_PARITY;
@@ -315,6 +315,11 @@ static int cs35l56_sdw_read_prop(struct sdw_slave *peripheral)
ports[1].num = CS35L56_SDW1_CAPTURE_PORT;
ports[1].type = SDW_DPN_FULL;
ports[1].ch_prep_timeout = 10;
+
+ /* DP4 - capture */
+ ports[2].num = CS35L56_OT25_CAPTURE_PORT;
+ ports[2].type = SDW_DPN_FULL;
+ ports[2].ch_prep_timeout = 10;
prop->src_dpn_prop = &ports[1];
dev_dbg(&peripheral->dev, "clock stop mode 1 supported: %s\n",
diff --git a/sound/soc/codecs/cs35l56.c b/sound/soc/codecs/cs35l56.c
index 8beef93ac4676b..79f0a39d12b96c 100644
--- a/sound/soc/codecs/cs35l56.c
+++ b/sound/soc/codecs/cs35l56.c
@@ -32,6 +32,7 @@
#include <sound/cs-amp-lib.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
+#include <sound/sdw.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/tlv.h>
@@ -323,6 +324,7 @@ static const struct snd_soc_dapm_widget cs35l56_dapm_widgets[] = {
SND_SOC_DAPM_SIGGEN("VDDBMON ADC"),
SND_SOC_DAPM_SIGGEN("VBSTMON ADC"),
SND_SOC_DAPM_SIGGEN("TEMPMON ADC"),
+ SND_SOC_DAPM_SIGGEN("OT25 Reference"),
SND_SOC_DAPM_INPUT("Calibrate"),
};
@@ -387,6 +389,8 @@ static const struct snd_soc_dapm_route cs35l56_audio_map[] = {
{ "SDW1 Capture", NULL, "SDW1 TX2 Source" },
{ "SDW1 Capture", NULL, "SDW1 TX3 Source" },
{ "SDW1 Capture", NULL, "SDW1 TX4 Source" },
+
+ { "OT25", NULL, "OT25 Reference" },
};
static int cs35l56_dsp_event(struct snd_soc_dapm_widget *w,
@@ -711,6 +715,37 @@ static int cs35l56_sdw_dai_set_stream(struct snd_soc_dai *dai,
return 0;
}
+static int cs35l56_ot25_dai_hw_params(struct snd_pcm_substream *substream,
+ struct snd_pcm_hw_params *params,
+ struct snd_soc_dai *dai)
+{
+ struct cs35l56_private *cs35l56 = snd_soc_component_get_drvdata(dai->component);
+ struct sdw_stream_runtime *sdw_stream = snd_soc_dai_get_dma_data(dai, substream);
+ struct sdw_stream_config sconfig = { };
+ struct sdw_port_config pconfig = { };
+ int ret;
+
+ dev_dbg(cs35l56->base.dev, "%s: rate %d\n", __func__, params_rate(params));
+
+ if (!cs35l56->base.init_done)
+ return -ENODEV;
+
+ if (!sdw_stream)
+ return -EINVAL;
+
+ snd_sdw_params_to_config(substream, params, &sconfig, &pconfig);
+ pconfig.num = CS35L56_OT25_CAPTURE_PORT;
+
+ ret = sdw_stream_add_slave(cs35l56->sdw_peripheral, &sconfig, &pconfig,
+ 1, sdw_stream);
+ if (ret) {
+ dev_err(dai->dev, "Failed to add OT25 stream: %d\n", ret);
+ return ret;
+ }
+
+ return 0;
+}
+
static const struct snd_soc_dai_ops cs35l56_sdw_dai_ops = {
.set_tdm_slot = cs35l56_sdw_dai_set_tdm_slot,
.shutdown = cs35l56_sdw_dai_shutdown,
@@ -719,6 +754,13 @@ static const struct snd_soc_dai_ops cs35l56_sdw_dai_ops = {
.set_stream = cs35l56_sdw_dai_set_stream,
};
+static const struct snd_soc_dai_ops cs35l56_ot25_dai_ops = {
+ .shutdown = cs35l56_sdw_dai_shutdown,
+ .hw_params = cs35l56_ot25_dai_hw_params,
+ .hw_free = cs35l56_sdw_dai_hw_free,
+ .set_stream = cs35l56_sdw_dai_set_stream,
+};
+
static struct snd_soc_dai_driver cs35l56_dai[] = {
{
.name = "cs35l56-asp1",
@@ -767,6 +809,18 @@ static struct snd_soc_dai_driver cs35l56_dai[] = {
.symmetric_rate = 1,
.ops = &cs35l56_sdw_dai_ops,
},
+ {
+ .name = "cs35l56-ot25",
+ .id = 3,
+ .capture = {
+ .stream_name = "OT25",
+ .channels_min = 1,
+ .channels_max = 2,
+ .rates = CS35L56_RATES,
+ .formats = CS35L56_TX_FORMATS,
+ },
+ .ops = &cs35l56_ot25_dai_ops,
+ },
};
static int cs35l56_write_cal(struct cs35l56_private *cs35l56)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 616 KiB

+7
View File
@@ -0,0 +1,7 @@
{
"generator": "built-in image_gen.imagegen",
"date": "2026-10-22",
"asset": "platina-linux-logo.png",
"sha256": "84e7559014037e14f0952a7c928e3a08876220b65024323cfc41713fab1a7493",
"version_is_separate": true
}
+92
View File
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: GPL-2.0-only
/* Bounded Platina LCD diagnostics, without detaching or replacing DRM. */
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/regulator/consumer.h>
#include <drm/drm_mipi_dsi.h>
static bool wake;
static bool enable_iovcc;
static bool own_enable;
static struct regulator *iovcc;
module_param(wake, bool, 0400);
module_param(enable_iovcc, bool, 0400);
MODULE_PARM_DESC(wake, "Send standard DCS sleep-out/display-on after reading status");
static int read_result, wake_result;
static int io_enabled;
static unsigned char power_before, power_after;
module_param(read_result, int, 0444);
module_param(io_enabled, int, 0444);
module_param(wake_result, int, 0444);
module_param(power_before, byte, 0444);
module_param(power_after, byte, 0444);
static int __init platina_panel_dcs_init(void)
{
struct device_node *node;
struct mipi_dsi_device *dsi;
unsigned long flags;
if (!of_machine_is_compatible("xiaomi,platina"))
return -ENODEV;
node = of_find_node_by_path("/soc@0/display-subsystem@c900000/dsi@c994000/panel@0");
if (!node)
return -ENODEV;
dsi = of_find_mipi_dsi_device_by_node(node);
of_node_put(node);
if (!dsi)
return -ENODEV;
iovcc = regulator_get_optional(&dsi->dev, "iovcc");
if (IS_ERR(iovcc)) {
io_enabled = PTR_ERR(iovcc);
iovcc = NULL;
read_result = -EHOSTDOWN;
goto done;
}
io_enabled = regulator_is_enabled(iovcc);
if (!io_enabled && enable_iovcc) {
wake_result = regulator_enable(iovcc);
if (!wake_result) {
own_enable = true;
io_enabled = regulator_is_enabled(iovcc);
}
}
if (io_enabled <= 0) {
read_result = -EHOSTDOWN;
goto done;
}
flags = dsi->mode_flags;
dsi->mode_flags |= MIPI_DSI_MODE_LPM;
read_result = mipi_dsi_dcs_read(dsi, 0x0a, &power_before, 1);
if (wake && read_result == 1) {
wake_result = mipi_dsi_dcs_exit_sleep_mode(dsi);
if (!wake_result) {
msleep(120);
wake_result = mipi_dsi_dcs_set_display_on(dsi);
msleep(20);
}
if (!wake_result)
read_result = mipi_dsi_dcs_read(dsi, 0x0a, &power_after, 1);
}
dsi->mode_flags = flags;
done:
put_device(&dsi->dev);
pr_info("platina-panel-dcs: iovcc=%d read=%d power_before=0x%02x power_after=0x%02x wake=%d\n",
io_enabled, read_result, power_before, power_after, wake_result);
return 0;
}
static void __exit platina_panel_dcs_exit(void)
{
if (own_enable)
regulator_disable(iovcc);
if (iovcc)
regulator_put(iovcc);
}
module_init(platina_panel_dcs_init);
module_exit(platina_panel_dcs_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Platina read-only DCS status and optional standard LCD wake test");
+10
View File
@@ -0,0 +1,10 @@
{
"schema": 1,
"source_url": "https://github.com/MiCode/Xiaomi_Kernel_OpenSource/blob/0bb2780bccb9c7e05f0edf5db8860e779179b5f9/arch/arm/boot/dts/qcom/dsi-panel-tianma-fhd-nt36672a-video.dtsi",
"source_sha256": "8b8314421455305d4750366a327f09278729c6fe17889cc1348dcbfc967238fd",
"stock_boot_sha256": "8ef6f1d9b937eb8aa571957f69629a6d7be40eef412f585647f29b9ddf243d86",
"stock_fdt_offset": 19640617,
"stock_fdt_sha256": "549885ab06856cd63c4717b85f77bf08eab1544f6898924a158905ebd273a9ad",
"on_command_hex": "15010000000002ff2215000000000002fb01150000000000020040150000000000020140150000000000020240150000000000020340150000000000020440150000000000020540150000000000020640150000000000020740150000000000020840150000000000020940150000000000020a40150000000000020b40150000000000020c40150000000000020d40150000000000020e40150100000000020f4015000000000002104015000000000002115015000000000002126015000000000002137015000000000002145815000000000002156815000000000002167815000000000002177715000000000002183e150000000000021936150000000000021a30150000000000021b28150000000000021c25150000000000021d23150000000000021e26150100000000021f2a15000000000002203015000000000002213615000000000002223c1500000000000223401500000000000224401500000000000225401500000000000226401500000000000227401500000000000228401500000000000253011500000000000254011500000000000255ff1500000000000256761500000000000258c81500000000000259ca150000000000025a48150000000000025b48150000000000025c48150000000000025d48150000000000025e48150100000000025f48150000000000026048150000000000026148150000000000026248150000000000026348150000000000026448150000000000026548150000000000026648150000000000026748150000000000026848150000000000026948150000000000026a48150000000000026b48150000000000026c48150000000000026d48150000000000026e48150100000000026fc815000000000002700315000000000002710015000000000002728015000000000002730015000000000002740615000000000002750c15000000000002760315000000000002770915000000000002780f150000000000027968150000000000027a8b150000000000027c80150000000000027d80150000000000027e80150100000000027f00150000000000028000150000000000028100150000000000028301150000000000028400150000000000028580150000000000028680150000000000028780150000000000028840150000000000028983150000000000028a8615000000000002b77615010000000002b87615010000000002ff2315000000000002fb0115000000000002006015000000000002070015000000000002080115010000000002090015000000000002110115000000000002128015000000000002156d15010000000002160b15000000000002290a1500000000000230ff1500000000000231ff1500000000000232ff1500000000000233ff1500000000000234ff1500000000000235ff1500000000000236ff1500000000000237ff1500000000000238fc1500000000000239f9150000000000023af5150000000000023bf1150000000000023dee150000000000023feb1500000000000240e91501000000000241e5150000000000022a131500000000000245ff1500000000000246f51500000000000247ea1500000000000248df1500000000000249d5150000000000024aca150000000000024bc0150000000000024cb6150000000000024dac150000000000024ea2150000000000024f9815000000000002508e15000000000002518415000000000002527a150000000000025370150100000000025466150000000000022b0e1500000000000258ff1500000000000259ff150000000000025aff150000000000025bff150000000000025cff150000000000025dff150000000000025eff150000000000025fff1500000000000260f61500000000000261ec1500000000000262e31500000000000263d91500000000000264d01500000000000265c71500000000000266bd1501000000000267b315000000000002018415010000000002060115000000000002052d15000000000002040515010000000002ff2515000000000002fb0115010000000002050415010000000002ff1015000000000002fb01150000000000023500290000000000035107ff15000000000002532415010000000002550005010000000002290005010000460002110015010000000002ff2415000000000002fb0115000000000002c30115000000000002c45415010000000002c28e15010000000002ff10",
"off_command_hex": "15010000000002ff2415000000000002fb0115010000000002c30015010000000002ff10050100000000022800050100003c00021000"
}
+7
View File
@@ -0,0 +1,7 @@
{
"schema": 1,
"name": "Platina Linux",
"version": "0.1.1",
"channel": "development",
"released": "2026-10-22"
}
+29
View File
@@ -0,0 +1,29 @@
{
"schema": 1,
"repositories": {
"pmbootstrap": {
"url": "https://gitlab.postmarketos.org/postmarketOS/pmbootstrap.git",
"commit": "7d23010a125ca7386fec4e390d14128b6c24d266",
"path": "tools/pmbootstrap"
},
"pmaports": {
"url": "https://gitlab.postmarketos.org/postmarketOS/pmaports.git",
"commit": "1c36715c14a2712bf3746a26dccb0ba5e93a0b2a",
"channels_commit": "02b84c93abb1d510de752ebb2143d83fc55f68cd"
}
},
"profiles": {
"candidate": {
"ports": "ports/candidate",
"kernel": "7.2.12",
"kernel_package": "7.2.12-r1",
"device_package": "5-r31",
"firmware_package": "2-r5"
}
},
"local_firmware": [
"a512_zap.elf",
"firmware-xiaomi-platina-bdwlan.tar.gz",
"firmware-xiaomi-platina-modem.tar.gz"
]
}
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
set -eu
test -f /usr/share/deviceinfo/deviceinfo
grep -q xiaomi-platina /usr/share/deviceinfo/deviceinfo
test -s /home/server/.ssh/authorized_keys
ssh-keygen -lf /home/server/.ssh/authorized_keys
awk -F: '$1 == "server" { if (substr($2,1,1) != "!") exit 1; print "server password locked"; found=1 } END { if (!found) exit 1 }' /etc/shadow
test ! -e /tmp/platina-audit-host-key
ssh-keygen -q -t ed25519 -N '' -f /tmp/platina-audit-host-key
trap 'rm -f /tmp/platina-audit-host-key /tmp/platina-audit-host-key.pub' EXIT
sshd_settings=$(/usr/sbin/sshd.pam -T -h /tmp/platina-audit-host-key)
for expected in 'passwordauthentication no' 'kbdinteractiveauthentication no' 'permitrootlogin no' 'pubkeyauthentication yes' 'usepam yes'; do
printf '%s\n' "$sshd_settings" | grep -Fx "$expected"
done
grep -q '^SSHD_BINARY="/usr/sbin/sshd.pam"' /etc/conf.d/sshd
visudo -c
test -f /usr/lib/security/pam_rundir.so
test -x /usr/sbin/avahi-daemon
test -x /usr/sbin/NetworkManager
test -x /usr/sbin/usb_moded
test -x /usr/sbin/chronyd
test -d /home/server/.config/rc/runlevels/default
test -s /etc/NetworkManager/system-connections/platina-usb.nmconnection
test "$(stat -c '%a:%u:%g' /etc/NetworkManager/system-connections/platina-usb.nmconnection)" = '600:0:0'
test -z "$(find /etc/NetworkManager/system-connections -type f -name '*.nmconnection' ! -name platina-usb.nmconnection -print)"
test -z "$(find /home -type f -name 'id_*' -print)"
grep -q '^wifi.scan-rand-mac-address=no$' /etc/NetworkManager/conf.d/30-platina-wifi.conf
grep -q '^nameserver 1.1.1.1$' /etc/resolv.conf
grep -q '^https://mirror.nura.eco/postmarketos/v26.06$' /etc/apk/repositories
for package in device-xiaomi-platina firmware-xiaomi-platina linux-postmarketos-qcom-sdm660; do
grep -q "^$package=" /etc/apk/world
done
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon; do
test -L "/etc/runlevels/default/$service"
done
for key in /etc/ssh/ssh_host_*_key; do
if [ -f "$key" ]; then
echo 'Build-time SSH host key found; needs removal before final export.'
exit 1
fi
done
echo 'Offline image audit passed; runtime networking and boot still need testing.'
+65
View File
@@ -0,0 +1,65 @@
#!/bin/sh
# Runs only inside the newly created phone image, never on MiniPC's host OS.
set -eu
test -f /usr/share/deviceinfo/deviceinfo
grep -q xiaomi-platina /usr/share/deviceinfo/deviceinfo
test "$(id -u)" = 0
test -s /home/server/.ssh/authorized_keys
command -v sudo >/dev/null
test -x /usr/sbin/sshd.pam
if ! grep -q '^SSHD_BINARY=' /etc/conf.d/sshd; then
printf '\nSSHD_BINARY="/usr/sbin/sshd.pam"\n' >> /etc/conf.d/sshd
fi
install -d -m755 /etc/ssh/sshd_config.d /etc/sudoers.d
cat > /etc/ssh/sshd_config.d/00-platina-server.conf <<'EOF'
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
UsePAM yes
EOF
if ! grep -q '^Include /etc/ssh/sshd_config.d/' /etc/ssh/sshd_config; then
sed -i '1i Include /etc/ssh/sshd_config.d/*.conf' /etc/ssh/sshd_config
fi
printf 'server ALL=(ALL) NOPASSWD: ALL\n' > /etc/sudoers.d/90-platina-server
chmod 440 /etc/sudoers.d/90-platina-server
chmod 440 /etc/sudoers
visudo -c
if ! awk -F: '$1 == "server" && substr($2,1,1) == "!" { found=1 } END { exit !found }' /etc/shadow; then
passwd -l server
fi
chmod 700 /home/server/.ssh
chmod 600 /home/server/.ssh/authorized_keys
chown -R server:server /home/server/.ssh
install -d -m700 -o server -g server /home/server/.config/rc/runlevels/default
test -f /usr/lib/security/pam_rundir.so
cat > /etc/resolv.conf <<'EOF'
nameserver 1.1.1.1
nameserver 1.0.0.1
EOF
cat > /etc/apk/repositories <<'EOF'
https://mirror.nura.eco/postmarketos/v26.06
https://cdn.alpinelinux.org/alpine/v3.24/main
https://cdn.alpinelinux.org/alpine/v3.24/community
EOF
chmod 644 /etc/resolv.conf /etc/apk/repositories
cat > /etc/local.d/platina-headless.start <<'EOF'
#!/bin/sh
for path in /sys/class/backlight/*/brightness; do
[ -w "$path" ] && printf '0\n' > "$path"
done
exit 0
EOF
chmod 755 /etc/local.d/platina-headless.start
# Hold the exact locally built boot-related packages during normal upgrades.
set --
for package in device-xiaomi-platina firmware-xiaomi-platina linux-postmarketos-qcom-sdm660; do
version=$(awk -v package="$package" '$0 == "P:" package { found=1; next } found && /^V:/ { print substr($0,3); exit }' /lib/apk/db/installed)
test -n "$version"
set -- "$@" "$package=$version"
done
apk add --no-network "$@"
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon; do
rc-update add "$service" default
done
printf 'Image configured for SSH keys and passwordless sudo for the dedicated administrator.\n'
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Check exported boot/rootfs consistency and early module dependencies, read-only."""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
import re
import struct
import subprocess
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'artifacts/candidate-7.2'
def cpio_files(data):
files = {}
offset = 0
while offset + 110 <= len(data):
header = data[offset:offset + 110]
assert header[:6] in (b'070701', b'070702'), 'Unsupported CPIO format'
size = int(header[54:62], 16)
namesize = int(header[94:102], 16)
name = data[offset + 110:offset + 110 + namesize - 1].decode()
offset = (offset + 110 + namesize + 3) & ~3
if name == 'TRAILER!!!':
break
files[name.removeprefix('./').lstrip('/')] = data[offset:offset + size]
offset = (offset + size + 3) & ~3
return files
def main():
global OUT
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--directory', type=Path, default=OUT)
args = parser.parse_args()
OUT = args.directory.resolve()
boot = (OUT / 'boot.img').read_bytes()
assert boot[:8] == b'ANDROID!'
kernel_size, _, ramdisk_size = struct.unpack_from('<III', boot, 8)
pagesize = struct.unpack_from('<I', boot, 36)[0]
header_version = struct.unpack_from('<I', boot, 40)[0]
assert header_version <= 2 and pagesize == 4096
assert len(boot) <= 0x3FFC000, 'Exceeds verified boot partition size'
cmdline = (boot[64:576].split(b'\0')[0] + b' ' + boot[608:1632].split(b'\0')[0]).decode().strip()
uuid = re.search(r'pmos_root_uuid=([0-9a-f-]+)', cmdline).group(1)
metadata = subprocess.check_output(['blkid', '-p', '-o', 'export',
str(OUT / 'xiaomi-platina.img')], text=True)
assert f'UUID={uuid}\n' in metadata and 'TYPE=ext4\n' in metadata
def root_file(path):
return subprocess.check_output(['debugfs', '-R', 'cat ' + path,
str(OUT / 'xiaomi-platina.img')],
stderr=subprocess.DEVNULL, text=True)
assert root_file('/etc/resolv.conf').splitlines() == ['nameserver 1.1.1.1', 'nameserver 1.0.0.1']
assert root_file('/etc/apk/repositories').splitlines() == [
'https://mirror.nura.eco/postmarketos/v26.06',
'https://cdn.alpinelinux.org/alpine/v3.24/main',
'https://cdn.alpinelinux.org/alpine/v3.24/community']
start = pagesize + ((kernel_size + pagesize - 1) // pagesize) * pagesize
ramdisk = boot[start:start + ramdisk_size]
assert ramdisk == (OUT / 'initramfs').read_bytes(), 'Boot/export initramfs mismatch'
files = cpio_files(gzip.decompress(ramdisk))
release = json.loads((OUT / 'manifest.json').read_text())['kernel']
assert re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+-sdm660', release), 'Invalid declared kernel release'
prefix = f'usr/lib/modules/{release}/'
# Some distributions use /lib instead of /usr/lib inside initramfs.
if not any(name.startswith(prefix) for name in files):
prefix = f'lib/modules/{release}/'
depfile = prefix + 'modules.dep'
assert depfile in files, 'Missing module dependency metadata'
dependencies = dict(line.split(':', 1) for line in files[depfile].decode().splitlines())
included = {name[len(prefix):] for name in files if name.startswith(prefix) and '.ko' in name}
missing = sorted({dependency for module in included
for dependency in dependencies.get(module, '').split()
if prefix + dependency not in files})
assert not missing, f'Initramfs modules have missing dependencies: {missing}'
required = ('qcom_pil_info', 'ath10k_core', 'snd_soc_core',
'qcom_vadc_common', 'snd_soc_qcom_common', 'btqca')
normal = {Path(name).name.split('.ko')[0].replace('-', '_') for name in included}
assert set(required) <= normal, 'Missing early-boot module'
for firmware in ('regulatory.db', 'regulatory.db.p7s'):
assert any(name.endswith('/firmware/' + firmware) for name in files), firmware
assert not any(name.endswith(('.nmconnection', 'id_ed25519', 'id_rsa')) for name in files)
report = {'passed': True, 'hardware_tested': False, 'flashed': False,
'boot_bytes': len(boot), 'boot_limit_bytes': 0x3FFC000,
'kernel': release, 'rootfs_uuid': uuid, 'cmdline': cmdline,
'initramfs_modules': len(included), 'missing_module_dependencies': missing,
'initramfs_sha256': hashlib.sha256(ramdisk).hexdigest()}
(ROOT / 'reports' / (OUT.name + '-artifact-audit.json')).write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report, indent=2))
if __name__ == '__main__':
main()
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""Build and audit isolated candidate images locally; never writes to a phone."""
import argparse
import configparser
import datetime
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
ROOT = Path(__file__).resolve().parents[1]
WORK = ROOT / 'work/pmbootstrap-candidate-7.2'
OUTPUT = ROOT / 'artifacts/candidate-7.2'
KERNEL_RELEASE = '7.2.12-sdm660'
STATUS = ROOT / 'logs/candidate-image-status.json'
PMB = ['nice', '-n', '10', 'python3', str(ROOT / 'tools/pmbootstrap/pmbootstrap.py'),
'-c', str(ROOT / 'config/pmbootstrap-candidate-7.2.cfg'), '-j', '2']
def provenance(config_path, config):
def revision(directory):
result = subprocess.run(['git', '-C', str(directory), 'rev-parse', 'HEAD'],
capture_output=True, text=True)
return result.stdout.strip() if result.returncode == 0 else None
recipes = Path(config['pmbootstrap']['aports']) / 'device/testing'
inputs = {}
for package in ('device-xiaomi-platina', 'firmware-xiaomi-platina',
'linux-postmarketos-qcom-sdm660'):
for path in sorted((recipes / package).iterdir()):
if path.is_file():
with path.open('rb') as stream:
inputs[str(path.relative_to(recipes))] = hashlib.file_digest(stream, 'sha256').hexdigest()
dirty = subprocess.run(['git', '-C', str(ROOT), 'status', '--porcelain'],
capture_output=True, text=True)
return {'project_commit': revision(ROOT),
'project_dirty': bool(dirty.stdout.strip()) if dirty.returncode == 0 else None,
'pmaports_commit': revision(recipes.parents[1]),
'pmbootstrap_commit': revision(ROOT / 'tools/pmbootstrap'),
'config_sha256': hashlib.sha256(config_path.read_bytes()).hexdigest(),
'recipe_inputs_sha256': inputs}
def record(phase, **details):
row = {'time': datetime.datetime.now().astimezone().isoformat(),
'phase': phase, 'flashed': False, **details}
STATUS.write_text(json.dumps(row, indent=2) + '\n')
print(phase, flush=True)
def run(*args, script=None):
if script:
with (ROOT / 'scripts' / script).open() as stream:
subprocess.run(PMB + list(args), cwd=ROOT, stdin=stream, check=True)
else:
subprocess.run(PMB + list(args), cwd=ROOT, check=True)
def main():
global OUTPUT, WORK, PMB, KERNEL_RELEASE
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--config', type=Path, default=ROOT / 'config/pmbootstrap-candidate-7.2.cfg',
help='Absolute project pmbootstrap config; work is derived from it')
parser.add_argument('--resume-image', action='store_true',
help='Resume hardening/audit of the already created candidate image')
parser.add_argument('--output-name', default='candidate-7.2',
help='New candidate-* directory under artifacts; existing output is preserved')
args = parser.parse_args()
config_path = args.config.resolve()
config = configparser.ConfigParser()
if not config.read(config_path):
raise ValueError('Missing pmbootstrap config')
WORK = Path(config['pmbootstrap']['work'])
if not WORK.is_absolute() or not WORK.resolve().is_relative_to(ROOT / 'work'):
raise ValueError('Build work must be an absolute path inside project work/')
PMB = ['nice', '-n', '10', 'python3', str(ROOT / 'tools/pmbootstrap/pmbootstrap.py'),
'-c', str(config_path), '-j', '2']
(ROOT / 'logs').mkdir(exist_ok=True)
(ROOT / 'artifacts').mkdir(exist_ok=True)
if not re.fullmatch(r'candidate-[A-Za-z0-9][A-Za-z0-9._-]*', args.output_name):
raise ValueError('Output name must be a simple candidate-* directory name')
OUTPUT = ROOT / 'artifacts' / args.output_name
if OUTPUT.exists():
raise RuntimeError('Preserve existing candidate artifacts; use a new output directory')
build_sources = provenance(config_path, config)
recipe = Path(config['pmbootstrap']['aports']) / 'device/testing/linux-postmarketos-qcom-sdm660/APKBUILD'
recipe_text = recipe.read_text()
version = re.search(r'^pkgver=([0-9][0-9.]*)$', recipe_text, re.M)
release = re.search(r'^pkgrel=([0-9]+)$', recipe_text, re.M)
if not version or not release:
raise ValueError('Cannot determine kernel version from APKBUILD')
KERNEL_RELEASE = version[1] + '-sdm660'
apk_version = version[1] + '-r' + release[1]
packages = list((WORK / 'packages').glob('**/linux-postmarketos-qcom-sdm660-' + apk_version + '.apk'))
if not packages:
raise RuntimeError('Kernel APK must finish successfully before building images')
if args.resume_image:
assert (WORK / 'chroot_native/home/pmos/rootfs/xiaomi-platina.img').is_file()
else:
record('building-device-and-firmware')
run('build', '--lax', '--arch', 'aarch64',
'firmware-xiaomi-platina', 'device-xiaomi-platina')
record('creating-rootfs')
# Disposable, public build placeholder; the account is locked before export.
run('install', '--single-partition', '--no-sparse', '--no-recommends',
'--password', 'locked-before-export',
'--add', 'python3,iw,iperf3,mmc-utils,avahi-tools')
record('hardening-and-auditing-image')
# Each pmbootstrap chroot entry restores build DNS/repositories. Configure
# and audit in one entry, then export without entering the image again.
scripts = '\n'.join((ROOT / 'scripts' / name).read_text()
for name in ('Harden-Server-Image.sh', 'Audit-Server-Image.sh'))
subprocess.run(PMB + ['chroot', '--image', '--', 'sh', '-s'],
cwd=ROOT, input=scripts, text=True, check=True)
record('exporting')
links = ROOT / 'artifacts' / (OUTPUT.name + '-links')
run('export', '--no-install', str(links))
# Stop all mounts before copying/hashing the mutable filesystem image.
run('shutdown')
OUTPUT.mkdir()
files = []
for source in sorted(links.rglob('*')):
if not source.is_file():
continue
target = OUTPUT / source.relative_to(links)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
with target.open('rb') as stream:
digest = hashlib.file_digest(stream, 'sha256').hexdigest()
files.append({'file': str(target.relative_to(OUTPUT)),
'bytes': target.stat().st_size, 'sha256': digest})
assert {'boot.img', 'xiaomi-platina.img', 'initramfs', 'vmlinuz'} <= {f['file'] for f in files}
if provenance(config_path, config) != build_sources:
raise RuntimeError('Build sources changed during the build; review before publishing artifacts')
manifest = {'kernel': KERNEL_RELEASE, 'hardware_tested': False,
'build_sources': build_sources,
'flashed': False, 'files': files}
(OUTPUT / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
record('exported-offline-audit-passed-hardware-test-pending', files=len(files))
if __name__ == '__main__':
try:
main()
except Exception as exc:
record('failed-needs-review', error=type(exc).__name__,
returncode=getattr(exc, 'returncode', None))
raise SystemExit(1)
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Fail public CI when private files or host-specific data enter the Git index."""
import re
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def check(root=ROOT):
paths = subprocess.check_output(['git', 'ls-files', '-z'], cwd=root).decode().split('\0')
blocked = {'config', 'backups', 'artifacts', 'work', 'sources', 'tools', 'logs', 'reports', 'archive'}
patterns = [rb'-----BEGIN (?:OPENSSH |RSA |EC |DSA )?PRIVATE KEY-----',
rb'(?im)^\s*(?:psk|password|TELEGRAM_BOT_TOKEN|api_key)\s*=\s*["\']?[^\s"\'\n]{6,}',
rb'(?:ghp_|github_pat_|sk-proj-)[A-Za-z0-9_]{20,}',
rb'192\.168\.\d{1,3}\.\d{1,3}', rb'/home/(?!server/|pmos/)[A-Za-z0-9_.-]+/',
rb'C:\\Users\\']
for name in filter(None, paths):
path = Path(name)
lower = name.lower()
if (path.parts[0] in blocked or path.name.lower().startswith('agents.') or
path.suffix.lower() in ('.txt', '.env', '.key', '.pem', '.img', '.apk', '.bin', '.elf', '.zip') or
any(word in lower for word in ('private', 'secret', 'handoff'))):
raise ValueError('Private or generated path in public index: ' + name)
file = root / path
if file.is_symlink():
if not file.resolve().is_relative_to(root.resolve()):
raise ValueError('External symlink: ' + name)
data = file.read_bytes()
if path.suffix.lower() == '.png':
continue
if any(re.search(pattern, data) for pattern in patterns):
raise ValueError('Possible private data in public file (value suppressed): ' + name)
print('OK: public index excludes private files, credentials and maintainer host data')
if __name__ == '__main__':
check()
+39
View File
@@ -0,0 +1,39 @@
#!/bin/sh
# Read-only runtime inspection after Linux is installed. No package/service changes.
set -u
date -Is
uname -a
cat /etc/os-release
uptime
free -m
df -h
ip address show
ip route
ss -lnt 2>/dev/null || true
rc-status 2>/dev/null || true
printf '\nCPU frequency policies (kHz)\n'
for d in /sys/devices/system/cpu/cpufreq/policy*; do
[ -d "$d" ] || continue
for n in scaling_driver scaling_governor scaling_cur_freq scaling_min_freq scaling_max_freq; do
[ -r "$d/$n" ] && printf '%s: %s\n' "$d/$n" "$(cat "$d/$n")"
done
done
printf '\nThermal zones (normally millidegrees C)\n'
for d in /sys/class/thermal/thermal_zone*; do
[ -r "$d/temp" ] || continue
printf '%s %s: %s\n' "$d" "$(cat "$d/type")" "$(cat "$d/temp")"
done
printf '\nPower supplies: values are driver reports, not wall-power measurements\n'
for d in /sys/class/power_supply/*; do
[ -d "$d" ] || continue
for n in type status online capacity temp voltage_now current_now; do
[ -r "$d/$n" ] && printf '%s: %s\n' "$d/$n" "$(cat "$d/$n")"
done
done
printf '\nBacklight\n'
for d in /sys/class/backlight/*; do
[ -d "$d" ] || continue
for n in brightness actual_brightness max_brightness bl_power; do
[ -r "$d/$n" ] && printf '%s: %s\n' "$d/$n" "$(cat "$d/$n")"
done
done
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Temporary LCD power/wake session for the verified Platina 7.2.12 port.
No DRM detach, DT mutation or boot write. A matching, checksum-pinned module
must have been explicitly installed. A later proper panel port replaces this.
"""
import fcntl
import hashlib
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
BASE = Path('/usr/local/lib/platina/display')
PARAMS = Path('/sys/module/platina_panel_dcs/parameters')
def validate(base=BASE):
identity = json.loads((base / 'module.json').read_text())
if identity['kernel'] != os.uname().release:
raise ValueError('LCD helper requires its exact build kernel; rebuild after upgrade')
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
raise ValueError('Not a Platina phone')
if 'mdss_dsi_tianma_fhd_nt36672a_video' not in Path('/proc/cmdline').read_text():
raise ValueError('Not the verified Tianma panel')
driver = Path('/sys/bus/mipi-dsi/devices/c994000.dsi.0/driver').resolve(strict=True).name
if driver != 'panel-simple-dsi':
raise ValueError('LCD workaround requires the original panel-simple driver')
module = base / 'platina_panel_dcs.ko'
if hashlib.sha256(module.read_bytes()).hexdigest() != identity['sha256']:
raise ValueError('LCD module checksum mismatch')
return module
def check_panel(params=PARAMS):
values = {name: int((params / name).read_text()) for name in
('io_enabled', 'read_result', 'wake_result', 'power_after')}
if (values['io_enabled'] != 1 or values['read_result'] != 1 or
values['wake_result'] != 0 or values['power_after'] & 0x14 != 0x14):
raise ValueError('LCD did not acknowledge sleep-out/display-on: ' + str(values))
return values
def session(arguments):
# Own the whole power/render/cleanup sequence, including manual invocations.
with Path('/run/platina-display-session.lock').open('w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
module = validate()
owned = False
try:
if not PARAMS.exists():
# Mark ownership before insmod so a signal also cleans up a
# module whose init completed just before the signal arrived.
owned = True
subprocess.run(['insmod', str(module), 'enable_iovcc=1', 'wake=1'], check=True)
print(json.dumps({'panel_ready': check_panel()}), flush=True)
renderer = subprocess.Popen(['/usr/local/sbin/platina-splash', *arguments])
try:
return renderer.wait()
finally:
if renderer.poll() is None:
renderer.terminate()
try:
renderer.wait(timeout=3)
except subprocess.TimeoutExpired:
renderer.kill()
renderer.wait()
finally:
if owned and PARAMS.exists():
# Brightness is cleared even if the renderer failed or timed out.
Path('/sys/class/backlight/backlight/brightness').write_text('0\n')
subprocess.run(['rmmod', 'platina_panel_dcs'], check=True)
if __name__ == '__main__':
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
try:
raise SystemExit(session(sys.argv[1:]))
except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:
print('platina-display-session:', error, file=sys.stderr)
raise SystemExit(1)
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Control the integrated Platina panel through fbdev/backlight; no module tricks."""
import argparse
from contextlib import contextmanager
import fcntl
import json
import mmap
import os
from pathlib import Path
import runpy
import signal
import struct
import sys
import time
BACKLIGHT = Path('/sys/class/backlight/backlight')
DRIVER = Path('/sys/bus/mipi-dsi/devices/c994000.dsi.0/driver')
PANEL = b'xiaomi,platina-tianma-nt36672a'
FBIOBLANK = 0x4611
def validate():
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
raise ValueError('This command requires Platina')
if DRIVER.resolve(strict=True).name != 'panel-novatek-nt36672a':
raise ValueError('Integrated Tianma driver required; keep using the 0.1.1 session on the old boot')
# Follow the bound device's OF node instead of depending on the DT directory layout.
compatible = (DRIVER.parent / 'of_node/compatible').read_bytes().split(b'\0')
if PANEL not in compatible:
raise ValueError('Unexpected panel variant')
if Path('/sys/module/platina_panel_dcs').exists():
raise ValueError('Temporary LCD module is loaded; do not mix display owners')
def status():
result = {'kernel': os.uname().release,
'driver': DRIVER.resolve().name if DRIVER.exists() else None,
'temporary_module_loaded': Path('/sys/module/platina_panel_dcs').exists()}
for name in ('brightness', 'actual_brightness', 'max_brightness', 'bl_power'):
path = BACKLIGHT / name
result[name] = int(path.read_text()) if path.exists() else None
blank = Path('/sys/class/graphics/fb0/blank')
result['fb_blank'] = int(blank.read_text()) if blank.exists() else None
# Brightness zero alone does not establish that the panel rails are off.
return result
def brightness(percent):
if not 0 <= percent <= 100:
raise ValueError('Brightness must be 0–100 percent')
maximum = int((BACKLIGHT / 'max_brightness').read_text())
level = max(1, maximum * percent // 100) if percent else 0
(BACKLIGHT / 'brightness').write_text(str(level) + '\n')
def off(fb):
brightness(0)
fcntl.ioctl(fb, FBIOBLANK, 4) # FB_BLANK_POWERDOWN: DRM calls panel unprepare.
def on(fb, percent):
fcntl.ioctl(fb, FBIOBLANK, 0)
(BACKLIGHT / 'bl_power').write_text('0\n')
brightness(percent)
@contextmanager
def device():
if os.geteuid() != 0:
raise ValueError('Run display changes on the phone as root')
validate()
# Shares the existing splash lock: two renderers must not own fb0 together.
with Path('/run/platina-splash.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
fb = os.open('/dev/fb0', os.O_RDWR | os.O_CLOEXEC)
try:
yield fb
finally:
os.close(fb)
def show(fb, directory, seconds, percent, boot=False):
helper = runpy.run_path('/usr/local/sbin/platina-splash', run_name='display_helpers')
manifest, raw = helper['load_frame'](directory)
boot_id = Path('/proc/sys/kernel/random/boot_id').read_text().strip()
done = Path('/run/platina-splash.done')
if boot and done.exists() and done.read_text().strip() == boot_id:
return
tty, previous = None, None
try:
variable, fixed = bytearray(160), bytearray(80)
fcntl.ioctl(fb, 0x4600, variable, True)
fcntl.ioctl(fb, 0x4602, fixed, True)
layout = helper['geometry'](variable, fixed)
tty = os.open('/dev/tty0', os.O_RDWR | os.O_CLOEXEC)
mode = bytearray(4)
fcntl.ioctl(tty, 0x4B3B, mode, True)
previous = struct.unpack('=i', mode)[0]
fcntl.ioctl(tty, 0x4B3A, 1) # KD_GRAPHICS: don't interleave console text.
with mmap.mmap(fb, layout[4], access=mmap.ACCESS_WRITE) as screen:
# Prepare pixels while dark, then unblank the integrated panel.
brightness(0)
helper['paint'](screen, raw, layout)
on(fb, percent)
print(json.dumps({'framebuffer_written': manifest['version'], 'seconds': seconds,
'backend': 'integrated-tianma'}), flush=True)
time.sleep(seconds)
brightness(0)
screen[:] = b'\0' * layout[4]
if boot:
done.write_text(boot_id + '\n')
finally:
try:
if tty is not None:
try:
if previous is not None:
fcntl.ioctl(tty, 0x4B3A, previous)
finally:
os.close(tty)
finally:
# Restoring KD_TEXT can wake fbcon: power down after restoring it.
off(fb)
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('status', help='Read sysfs only; does not open or wake the display')
sub.add_parser('off', help='Backlight zero, then DRM panel powerdown')
for name in ('on', 'brightness', 'show'):
cmd = sub.add_parser(name)
cmd.add_argument('--brightness', type=int, default=25)
if name == 'show':
cmd.add_argument('--directory', type=Path, default=Path('/usr/local/share/platina/current'))
cmd.add_argument('--seconds', type=float, default=7)
cmd.add_argument('--boot', action='store_true')
args = parser.parse_args()
if not 0 <= getattr(args, 'brightness', 25) <= 100:
parser.error('Brightness must be 0–100 percent')
if args.command == 'show' and not 0 < args.seconds <= 3600:
parser.error('Choose a display duration above zero and at most 3600 seconds')
if args.command == 'status':
print(json.dumps(status(), indent=2))
return
with device() as fb:
if args.command == 'off':
off(fb)
elif args.command == 'on':
try:
on(fb, args.brightness)
except BaseException:
off(fb)
raise
elif args.command == 'brightness':
brightness(args.brightness)
else:
show(fb, args.directory, args.seconds, args.brightness, args.boot)
if __name__ == '__main__':
signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
try:
main()
except (OSError, ValueError, KeyError) as error:
print('platina-display:', error, file=sys.stderr)
raise SystemExit(1)
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
# Always start dark. Display the installed release briefly in the background.
for path in /sys/class/backlight/*/brightness; do
[ -w "$path" ] && printf '0\n' > "$path"
done
if [ -x /usr/local/sbin/platina-splash ] && [ -r /usr/local/share/platina/current/release.json ]; then
umask 027
(
driver=$(readlink -f /sys/bus/mipi-dsi/devices/c994000.dsi.0/driver 2>/dev/null || true)
if [ "${driver##*/}" = panel-novatek-nt36672a ]; then
timeout -s TERM -k 3 15 /usr/local/sbin/platina-display show --boot --seconds 7
elif [ -r /usr/local/lib/platina/display/module.json ]; then
timeout -s TERM -k 3 15 /usr/local/sbin/platina-display-session --boot --seconds 7
else
timeout -s TERM -k 3 12 /usr/local/sbin/platina-splash --boot --seconds 7
fi
# Recover full panel powerdown even after the outer timeout killed a renderer.
if [ "${driver##*/}" = panel-novatek-nt36672a ]; then
/usr/local/sbin/platina-display off
fi
# Also recover brightness if timeout had to stop the renderer.
for path in /sys/class/backlight/*/brightness; do
[ -w "$path" ] && printf '0\n' > "$path"
done
) >> /var/log/platina-splash.log 2>&1 &
fi
exit 0
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""Show the installed Platina release on fbdev briefly, then turn backlight off."""
import argparse
import fcntl
import gzip
import hashlib
import json
import mmap
import os
from pathlib import Path
import signal
import struct
import sys
import time
CURRENT = Path('/usr/local/share/platina/current')
def load_frame(directory):
# Pin the immutable release before reading several files across a deploy.
directory = directory.resolve(strict=True)
manifest = json.loads((directory / 'release.json').read_text())
if manifest.get('schema') != 1 or manifest.get('name') != 'Platina Linux':
raise ValueError('Unrecognized release manifest')
display = manifest['display']
if (display['width'], display['height'], display['format']) != (1080, 2280, 'BGRX8888'):
raise ValueError('Unsupported release display layout')
if display['frame'] != 'frame.bgrx.gz' or display['raw_bytes'] != 1080 * 2280 * 4:
raise ValueError('Invalid frame manifest')
frame_path = directory / display['frame']
if frame_path.stat().st_size > 12_000_000:
raise ValueError('Oversized compressed frame')
compressed = frame_path.read_bytes()
if hashlib.sha256(compressed).hexdigest() != display['compressed_sha256']:
raise ValueError('Frame checksum mismatch')
with gzip.open(frame_path, 'rb') as source:
raw = source.read(display['raw_bytes'] + 1)
if len(raw) != display['raw_bytes'] or hashlib.sha256(raw).hexdigest() != display['raw_sha256']:
raise ValueError('Decoded frame checksum/length mismatch')
return manifest, raw
def geometry(variable, fixed):
v = struct.unpack_from('=40I', variable)
memory = struct.unpack_from('=I', fixed, 24)[0]
stride = struct.unpack_from('=I', fixed, 48)[0]
width, height, virtual_width, virtual_height, xoff, yoff, bpp = v[:7]
if (width, height, bpp) != (1080, 2280, 32):
raise ValueError('Framebuffer resolution/pixel depth differs from release')
if (v[8:10], v[11:13], v[14:16]) != ((16, 8), (8, 8), (0, 8)):
raise ValueError('Framebuffer does not use BGRX byte order')
if xoff + width > virtual_width or yoff + height > virtual_height:
raise ValueError('Framebuffer viewport exceeds virtual dimensions')
if stride < (xoff + width) * 4 or not 0 < memory <= 64_000_000:
raise ValueError('Invalid framebuffer memory layout')
offset = yoff * stride + xoff * 4
if offset + (height - 1) * stride + width * 4 > memory:
raise ValueError('Framebuffer viewport exceeds mapped memory')
return width, height, stride, offset, memory
def paint(target, raw, layout):
width, height, stride, offset, _ = layout
row = width * 4
for y in range(height):
start = offset + y * stride
target[start:start + row] = raw[y * row:(y + 1) * row]
def show(directory, seconds, brightness, boot):
if os.geteuid() != 0:
raise ValueError('Run on the phone as root')
with Path('/run/platina-splash.lock').open('w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
boot_id = Path('/proc/sys/kernel/random/boot_id').read_text().strip()
done = Path('/run/platina-splash.done')
if boot and done.exists() and done.read_text().strip() == boot_id:
return
manifest, raw = load_frame(directory)
backlight = Path('/sys/class/backlight/backlight')
power = backlight / 'bl_power'
previous_power = power.read_text()
level = max(1, int((backlight / 'max_brightness').read_text()) * brightness // 100)
fb = os.open('/dev/fb0', os.O_RDWR | os.O_CLOEXEC)
tty, previous = None, None
try:
var, fixed = bytearray(160), bytearray(80)
fcntl.ioctl(fb, 0x4600, var, True) # FBIOGET_VSCREENINFO
fcntl.ioctl(fb, 0x4602, fixed, True) # FBIOGET_FSCREENINFO
layout = geometry(var, fixed)
tty = os.open('/dev/tty0', os.O_RDWR | os.O_CLOEXEC)
mode = bytearray(4)
fcntl.ioctl(tty, 0x4B3B, mode, True) # KDGETMODE
previous = struct.unpack('=i', mode)[0]
fcntl.ioctl(tty, 0x4B3A, 1) # KD_GRAPHICS: console does not overwrite logo.
fcntl.ioctl(fb, 0x4611, 0) # FBIOBLANK / UNBLANK after the VT mode change.
with mmap.mmap(fb, layout[4], access=mmap.ACCESS_WRITE) as screen:
paint(screen, raw, layout)
# FBIOBLANK can leave the backlight's independent power state off.
power.write_text('0\n')
(backlight / 'brightness').write_text(str(level) + '\n')
# This confirms a memory write, not physical panel illumination.
print(json.dumps({'framebuffer_written': manifest['version'], 'seconds': seconds,
'brightness': level, 'boot_id': boot_id}), flush=True)
time.sleep(seconds)
(backlight / 'brightness').write_text('0\n')
screen[:] = b'\0' * layout[4]
if boot:
done.write_text(boot_id + '\n')
finally:
(backlight / 'brightness').write_text('0\n')
power.write_text(previous_power)
if tty is not None:
try:
if previous is not None:
fcntl.ioctl(tty, 0x4B3A, previous)
finally:
os.close(tty)
os.close(fb)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--directory', type=Path, default=CURRENT)
parser.add_argument('--seconds', type=float, default=7)
parser.add_argument('--brightness', type=int, default=25)
parser.add_argument('--boot', action='store_true')
parser.add_argument('--check', action='store_true', help='Validate installed assets without touching display')
args = parser.parse_args()
if not 1 <= args.seconds <= 10 or not 1 <= args.brightness <= 50:
parser.error('Require 1–10 seconds and 1–50 percent brightness')
if args.check:
manifest, _ = load_frame(args.directory)
print(manifest['name'], manifest['version'])
return
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
show(args.directory, args.seconds, args.brightness, args.boot)
if __name__ == '__main__':
try:
main()
except (OSError, ValueError, KeyError) as error:
print('platina-splash:', str(error), file=sys.stderr)
raise SystemExit(1)
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Single source of the project version and local splash/release bundle builder."""
import argparse
import datetime
import gzip
import hashlib
import json
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[1]
RELEASE = ROOT / 'project/release.json'
def version_tuple(value):
if not re.fullmatch(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)', value):
raise ValueError('Expected an explicit major.minor.patch version')
return tuple(map(int, value.split('.')))
def load_release(path=RELEASE):
data = json.loads(path.read_text())
if data['schema'] != 1 or data['name'] != 'Platina Linux':
raise ValueError('Unknown project release identity')
version_tuple(data['version'])
return data
def next_version(value, part):
major, minor, patch = version_tuple(value)
return {'major': f'{major + 1}.0.0', 'minor': f'{major}.{minor + 1}.0',
'patch': f'{major}.{minor}.{patch + 1}'}[part]
def build(output, release=None):
# Pillow is needed only on the build host. The phone uses the standard library.
from PIL import Image, ImageDraw, ImageFont
release = release or load_release()
if output.exists():
raise ValueError('Preserve existing release bundles; choose a new output path')
logo_path = ROOT / 'project/branding/platina-linux-logo.png'
provenance = json.loads((logo_path.parent / 'provenance.json').read_text())
if hashlib.sha256(logo_path.read_bytes()).hexdigest() != provenance['sha256']:
raise ValueError('Logo differs from its recorded provenance')
width, height = 1080, 2280
screen = Image.new('RGB', (width, height), '#000000')
# Render the reusable generated logo as a UI asset; its source is unchanged.
with Image.open(logo_path) as source:
logo = source.convert('RGB')
logo.thumbnail((960, 960), Image.Resampling.LANCZOS)
screen.paste(logo, ((width - logo.width) // 2, 410))
draw = ImageDraw.Draw(screen)
font_path = Path('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf')
font = ImageFont.truetype(str(font_path), 44)
label = 'v' + release['version']
box = draw.textbbox((0, 0), label, font=font)
text_width, text_height = box[2] - box[0], box[3] - box[1]
center_y = 1485
draw.rounded_rectangle((width // 2 - text_width // 2 - 36, center_y - 44,
width // 2 + text_width // 2 + 36, center_y + 44),
radius=36, fill='#090f13', outline='#24353e', width=2)
draw.text(((width - text_width) // 2 - box[0], center_y - text_height // 2 - box[1]),
label, font=font, fill='#d7e3eb')
output.mkdir(parents=True)
screen.save(output / 'preview.png')
raw = screen.tobytes('raw', 'BGRX')
frame = gzip.compress(raw, compresslevel=9, mtime=0)
(output / 'frame.bgrx.gz').write_bytes(frame)
(output / 'version').write_text(release['name'] + ' ' + release['version'] + '\n')
manifest = dict(release, display={
'width': width, 'height': height, 'format': 'BGRX8888', 'seconds': 7,
'brightness_percent': 25, 'frame': 'frame.bgrx.gz',
'raw_bytes': len(raw), 'raw_sha256': hashlib.sha256(raw).hexdigest(),
'compressed_sha256': hashlib.sha256(frame).hexdigest(),
}, logo_sha256=provenance['sha256'],
renderer_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
font_sha256=hashlib.sha256(font_path.read_bytes()).hexdigest())
(output / 'release.json').write_text(json.dumps(manifest, indent=2) + '\n')
print('Built locally:', output, '(not deployed)')
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('show')
bump = sub.add_parser('bump', help='Advance the local project version; never deploy')
bump.add_argument('part', choices=('major', 'minor', 'patch'))
command = sub.add_parser('build', help='Build a local versioned screen; never deploy')
command.add_argument('--output', type=Path)
args = parser.parse_args()
release = load_release()
if args.command == 'show':
print(release['version'])
elif args.command == 'bump':
release['version'] = next_version(release['version'], args.part)
release['released'] = datetime.date.today().isoformat()
RELEASE.write_text(json.dumps(release, indent=2) + '\n')
print('Local version:', release['version'], '; rebuild and deploy with the approved update')
else:
build(args.output or ROOT / ('artifacts/platina-linux-' + release['version']), release)
if __name__ == '__main__':
main()
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
project=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
exec "$project/tools/pmbootstrap/pmbootstrap.py" -c "$project/config/pmbootstrap-managed-candidate.cfg" "$@"
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Prepare an image for Platina locally; Pillow is required only on the build host."""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
from PIL import Image, ImageOps
ROOT = Path(__file__).resolve().parents[1]
def build(source, output):
if output.exists():
raise ValueError('Choose a new frame directory; existing bundles are immutable')
with Image.open(source) as image:
frame = ImageOps.pad(ImageOps.exif_transpose(image).convert('RGB'), (1080, 2280),
color='black', method=Image.Resampling.LANCZOS)
raw = frame.tobytes('raw', 'BGRX')
compressed = gzip.compress(raw, compresslevel=9, mtime=0)
manifest = json.loads((ROOT / 'project/release.json').read_text())
manifest.update(purpose='custom-display-frame', display={
'width': 1080, 'height': 2280, 'format': 'BGRX8888',
'frame': 'frame.bgrx.gz', 'raw_bytes': len(raw),
'raw_sha256': hashlib.sha256(raw).hexdigest(),
'compressed_sha256': hashlib.sha256(compressed).hexdigest(),
})
output.mkdir(parents=True)
frame.save(output / 'preview.png')
(output / 'frame.bgrx.gz').write_bytes(compressed)
(output / 'release.json').write_text(json.dumps(manifest, indent=2) + '\n')
return output
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('image', type=Path)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
print('Prepared locally:', build(args.image, args.output), '; no phone connection')
if __name__ == '__main__':
main()
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
"""Package user-owned stock firmware locally, verifying the pinned recipe hashes."""
import argparse
import gzip
import hashlib
import importlib.util
import io
from pathlib import Path
import shutil
import subprocess
import tarfile
import tempfile
ROOT = Path(__file__).resolve().parents[1]
def archive_files(directory, group):
output = io.BytesIO()
with gzip.GzipFile(fileobj=output, mode='wb', filename='', mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode='w') as archive:
for source in sorted(directory.iterdir()):
if not source.is_file() or source.is_symlink():
raise ValueError('Unexpected firmware input')
member = tarfile.TarInfo(group + '/' + source.name)
member.mode, member.size = 0o644, source.stat().st_size
with source.open('rb') as stream:
archive.addfile(member, stream)
return output.getvalue()
def prepare(modem, gpu, output, recipe):
if output.exists():
raise ValueError('Preserve existing firmware; choose a new output directory')
if not shutil.which('mcopy'):
raise ValueError('Install mtools on the build host first')
spec = importlib.util.spec_from_file_location('project_workflow', ROOT / 'scripts/project.py')
workflow = importlib.util.module_from_spec(spec)
spec.loader.exec_module(workflow)
checksums = workflow.checksums(recipe)
with tempfile.TemporaryDirectory(prefix='platina-firmware-') as temp:
staging = Path(temp)
for group, patterns in {
'bdwlan': ('bdwlan.*', 'wlanmdsp.mbn'),
'modem': ('mba.mbn', 'modem.mdt', 'modem.b*'),
}.items():
target = staging / group
target.mkdir()
for pattern in patterns:
subprocess.run(['mcopy', '-i', str(modem.resolve()), '::/image/' + pattern, str(target)], check=True)
files = {'a512_zap.elf': gpu.read_bytes()}
for group in ('bdwlan', 'modem'):
files['firmware-xiaomi-platina-' + group + '.tar.gz'] = archive_files(staging / group, group)
for name, data in files.items():
if hashlib.sha512(data).hexdigest() != checksums[name]:
raise ValueError('Firmware differs from the pinned reference: ' + name)
output.mkdir(parents=True)
for name, data in files.items():
(output / name).write_bytes(data)
print('Prepared checksum-verified local firmware; no phone access or redistribution')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--modem-image', type=Path, required=True, help='NON-HLOS.bin from your matching stock ROM')
parser.add_argument('--gpu-firmware', type=Path, required=True, help='Matching a512_zap.elf from your own vendor firmware')
parser.add_argument('--output', type=Path, default=ROOT / 'config/firmware')
parser.add_argument('--recipe', type=Path, default=ROOT / 'ports/candidate/firmware-xiaomi-platina/APKBUILD')
args = parser.parse_args()
prepare(args.modem_image, args.gpu_firmware, args.output, args.recipe)
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
project=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
export PYTHONDONTWRITEBYTECODE=1
exec python3 "$project/scripts/project.py" "$@"
+373
View File
@@ -0,0 +1,373 @@
#!/usr/bin/env python3
"""Local project workflow: checks, pinned builds and offline audits; no deployment."""
import argparse
import configparser
from contextlib import contextmanager
import fcntl
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
ROOT = Path(__file__).resolve().parents[1]
RECIPES = ('device-xiaomi-platina', 'firmware-xiaomi-platina', 'linux-postmarketos-qcom-sdm660')
ARCHIVES = {'linux-v6.19.10-sdm660.tar.gz',
'linux-dd1ed52c8ceef4f16715118ed0252fe75adbe71d.tar.gz'}
def run(command, **kwargs):
return subprocess.run(command, cwd=ROOT, check=True, **kwargs)
def lock():
data = json.loads((ROOT / 'project/sources.lock.json').read_text())
if data['schema'] != 1:
raise ValueError('Unsupported source lock schema')
return data
def digest(path, algorithm='sha256'):
with path.open('rb') as stream:
return hashlib.file_digest(stream, algorithm).hexdigest()
def child(directory, name):
relative = Path(name)
if not name or relative.is_absolute() or '..' in relative.parts:
raise ValueError('Unsafe manifest path')
target = directory / relative
if not target.resolve().is_relative_to(directory.resolve()):
raise ValueError('Manifest path escapes bundle')
if any((directory / Path(*relative.parts[:i])).is_symlink()
for i in range(1, len(relative.parts) + 1)):
raise ValueError('Manifest symlinks are not accepted')
if not target.is_file():
raise ValueError('Missing manifest file: ' + name)
return target
def verify(directory):
directory = directory.resolve()
files = json.loads((directory / 'manifest.json').read_text())['files']
if not isinstance(files, list) or not files:
raise ValueError('Manifest needs a nonempty files list')
seen = set()
for row in files:
name = row['file']
target = child(directory, name)
canonical = str(target.relative_to(directory))
if canonical in seen:
raise ValueError('Duplicate manifest file')
seen.add(canonical)
if not re.fullmatch(r'[a-f0-9]{64}', row['sha256']):
raise ValueError('Invalid SHA256')
if target.stat().st_size != row['bytes'] or digest(target) != row['sha256']:
raise ValueError('Artifact verification failed: ' + name)
print(f'OK: {len(files)} artifact hashes and lengths; hardware status unchanged')
def checksums(recipe):
rows = re.findall(r'^([a-f0-9]{128})[ \t]+([^\r\n]+)$', recipe.read_text(), re.M)
if not rows:
raise ValueError('No recipe checksums: ' + recipe.parent.name)
return {name.strip(): value for value, name in rows}
def recipe_checks(directory, external):
# Parse only: never evaluate arbitrary APKBUILD shell code on the host.
for name in RECIPES:
recipe = directory / name / 'APKBUILD'
for filename, expected in checksums(recipe).items():
if filename in external:
continue
if '/' in filename or filename in ('.', '..'):
raise ValueError('Unsafe recipe source path')
source = recipe.parent / filename
if not source.is_file() or source.is_symlink() or digest(source, 'sha512') != expected:
raise ValueError('Recipe input missing or changed: ' + name + '/' + filename)
install = re.search(r'^install="\$pkgname([^"\n]+)"$', recipe.read_text(), re.M)
if install and not (recipe.parent / (name + install[1])).is_file():
raise ValueError('Missing package install hook: ' + name)
def check():
# Explicit roots avoid traversing build mounts, private files and external repos.
candidates = [ROOT / name for name in
('README.md', 'AGENTS.md', 'CONTRIBUTING.md', 'CHANGELOG.md',
'Makefile', '.gitignore', '.gitattributes', 'LICENSE', 'NOTICE')
if (ROOT / name).is_file()]
for name in ('scripts', 'tests', 'ports', 'project', '.github', 'docs', 'LICENSES'):
candidates += [p for p in (ROOT / name).rglob('*')
if p.is_file() and '__pycache__' not in p.parts]
private_key = re.compile(rb'-----BEGIN (?:OPENSSH |RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----')
credential = re.compile(rb'(?im)^\s*(?:psk|password|TELEGRAM_BOT_TOKEN|api_key)\s*=\s*["\']?[^\s"\'\n]{6,}')
for path in candidates:
if path.is_symlink():
if not path.resolve().is_relative_to(ROOT) or not path.exists():
raise ValueError('Broken or external project symlink: ' + str(path.relative_to(ROOT)))
continue
data = path.read_bytes()
if private_key.search(data) or credential.search(data):
raise ValueError('Possible secret in project file (value suppressed): ' + str(path.relative_to(ROOT)))
if path.suffix == '.py':
compile(data, str(path), 'exec')
elif path.suffix in ('.sh', '.start', '.post-install') or path.name == 'APKBUILD' or data.startswith((b'#!/bin/sh', b'#!/sbin/openrc-run')):
run(['sh', '-n', str(path)], stdout=subprocess.DEVNULL)
release = json.loads((ROOT / 'project/release.json').read_text())
if (release.get('schema') != 1 or release.get('name') != 'Platina Linux'
or not re.fullmatch(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)', release.get('version', ''))):
raise ValueError('Invalid Platina project version')
branding = ROOT / 'project/branding'
provenance = json.loads((branding / 'provenance.json').read_text())
if digest(branding / 'platina-linux-logo.png') != provenance['sha256']:
raise ValueError('Logo changed without updating provenance')
data = lock()
for profile in data['profiles'].values():
recipe_checks(ROOT / profile['ports'], set(data['local_firmware']) | ARCHIVES)
for package, field in zip(RECIPES, ('device_package', 'firmware_package', 'kernel_package')):
text = (ROOT / profile['ports'] / package / 'APKBUILD').read_text()
version = re.search(r'^pkgver=(\S+)$', text, re.M)[1]
release = re.search(r'^pkgrel=(\d+)$', text, re.M)[1]
if version + '-r' + release != profile[field]:
raise ValueError('Profile version differs from recipe: ' + package)
if (ROOT / '.git').is_dir():
tracked = subprocess.check_output(['git', 'ls-files', '-z'], cwd=ROOT).decode().split('\0')
allowed = {str(p.relative_to(ROOT)) for p in candidates} | {'PLAN.md'}
if any(name and name not in allowed for name in tracked):
raise ValueError('Unexpected tracked path; review Git index')
run(['git', 'diff', '--check'])
run(['git', 'diff', '--cached', '--check'])
run([sys.executable, '-m', 'unittest', 'discover', '-s', 'tests', '-v'])
print(f'OK: syntax, secret patterns, recipe checksums, profile versions and tests ({len(candidates)} files)')
def repo_at(path, source, fetch):
if path.exists():
actual = subprocess.check_output(['git', '-C', str(path), 'rev-parse', 'HEAD'], text=True).strip()
if actual != source['commit']:
raise ValueError('Checkout differs from source lock: ' + str(path.relative_to(ROOT)))
return
if not fetch:
raise ValueError('Missing checkout; use prepare --fetch for explicit source download')
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.platina-', dir=path.parent) as temporary:
temp = Path(temporary) / 'checkout'
run(['git', 'init', '-q', str(temp)])
run(['git', '-C', str(temp), 'remote', 'add', 'origin', source['url']])
run(['git', '-C', str(temp), 'fetch', '--depth=1', 'origin', source['commit']])
run(['git', '-C', str(temp), 'checkout', '--detach', source['commit']])
temp.rename(path)
def config_path(profile):
return ROOT / 'config' / ('pmbootstrap-managed-' + profile + '.cfg')
def managed_path(profile):
return ROOT / 'sources' / ('pmaports-managed-' + profile)
def port_files(directory):
result = {}
for name in RECIPES:
for path in sorted((directory / name).rglob('*')):
if path.is_symlink():
raise ValueError('Unexpected symlink in managed recipes')
if path.is_file():
result[str(path.relative_to(directory))] = digest(path)
return result
def write_stamp(profile):
destination = managed_path(profile)
data = {'profile': profile, 'files': port_files(destination / 'device/testing')}
(destination / '.platina-managed.json').write_text(json.dumps(data, indent=2) + '\n')
def sync(profile):
data = lock()
definition = data['profiles'][profile]
destination = managed_path(profile)
stamp = json.loads((destination / '.platina-managed.json').read_text())
if stamp['profile'] != profile or port_files(destination / 'device/testing') != stamp['files']:
raise ValueError('Managed recipes were edited locally; preserve and review before sync')
recipe_checks(ROOT / definition['ports'], set(data['local_firmware']) | ARCHIVES)
firmware = destination / 'device/testing/firmware-xiaomi-platina'
sums = checksums(ROOT / definition['ports'] / 'firmware-xiaomi-platina/APKBUILD')
for name in data['local_firmware']:
if digest(firmware / name, 'sha512') != sums[name]:
raise ValueError('Firmware changed; prepare a new isolated profile')
new_files = port_files(ROOT / definition['ports'])
for name in stamp['files'].keys() - new_files.keys():
if Path(name).name not in data['local_firmware']:
(destination / 'device/testing' / name).unlink()
for name in new_files:
target = destination / 'device/testing' / name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ROOT / definition['ports'] / name, target)
write_stamp(profile)
print('Managed recipes synchronized; no build or device action performed.')
@contextmanager
def build_slot():
(ROOT / 'logs').mkdir(exist_ok=True)
with (ROOT / 'logs/managed-build.lock').open('a') as stream:
try:
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise ValueError('Another managed build/prepare/sync is running') from None
yield
def prepare(profile, fetch):
data = lock()
definition = data['profiles'][profile]
destination = managed_path(profile)
cfg_path = config_path(profile)
if destination.exists() or cfg_path.exists():
raise ValueError('Managed profile already exists; preserve it and review changes manually')
recipe_checks(ROOT / definition['ports'], set(data['local_firmware']) | ARCHIVES)
sums = checksums(ROOT / definition['ports'] / 'firmware-xiaomi-platina/APKBUILD')
blob_sources = []
for name in data['local_firmware']:
options = [ROOT / 'config/firmware' / name,
ROOT / 'sources/pmaports-server/device/testing/firmware-xiaomi-platina' / name]
source = next((p for p in options if p.is_file()), None)
if source is None or digest(source, 'sha512') != sums[name]:
raise ValueError('Missing or incorrect local firmware: ' + name + '; see docs/DEVELOPMENT.md')
blob_sources.append(source)
if not list((ROOT / 'config').glob('admin-*.pub')):
raise ValueError('Add your public SSH key as config/admin-*.pub before preparing a server image')
repo_at(ROOT / data['repositories']['pmbootstrap']['path'], data['repositories']['pmbootstrap'], fetch)
# Clone committed objects only; the existing pmaports index and edits are preserved.
source = ROOT / 'sources/pmaports-server'
if source.exists():
run(['git', 'clone', '--no-hardlinks', '--no-checkout', str(source), str(destination)])
run(['git', '-C', str(destination), 'checkout', '--detach', data['repositories']['pmaports']['commit']])
else:
repo_at(destination, data['repositories']['pmaports'], fetch)
# The channel table lives on main, independently of the pinned release tree.
channels = data['repositories']['pmaports'].get('channels_commit')
if channels:
run(['git', '-C', str(destination), 'fetch', '--depth=1',
str(source) if source.exists() else data['repositories']['pmaports']['url'],
channels])
run(['git', '-C', str(destination), 'update-ref', 'refs/remotes/origin/main', channels])
# pmbootstrap identifies the checkout by its canonical remote URL.
run(['git', '-C', str(destination), 'remote', 'set-url', 'origin',
data['repositories']['pmaports']['url']])
for name in RECIPES:
target = destination / 'device/testing' / name
if target.exists():
shutil.rmtree(target) # Only in the newly created checkout above.
shutil.copytree(ROOT / definition['ports'] / name, target)
for source in blob_sources:
shutil.copyfile(source, destination / 'device/testing/firmware-xiaomi-platina' / source.name)
write_stamp(profile)
for name in ('config', 'logs', 'reports', 'artifacts', 'work'):
(ROOT / name).mkdir(exist_ok=True)
cfg = configparser.ConfigParser()
cfg['pmbootstrap'] = {
'aports': str(destination), 'work': str(ROOT / 'work' / ('pmbootstrap-managed-' + profile)),
'device': 'xiaomi-platina', 'hostname': 'platina', 'user': 'server', 'ui': 'none',
'ui_extras': 'False', 'service_manager': 'openrc', 'timezone': 'Europe/Prague',
'locale': 'C.UTF-8', 'jobs': '2', 'ssh_keys': 'True', 'extra_packages': 'chrony',
'auto_zap_misconfigured_chroots': 'no',
'ssh_key_glob': str(ROOT / 'config/admin-*.pub'), 'is_default_channel': 'False'}
cfg['providers'] = {}
cfg['mirrors'] = {}
with cfg_path.open('x') as stream:
cfg.write(stream)
print('Prepared isolated ' + profile + ' profile. No build or device action performed.')
def pmb(profile):
cfg = config_path(profile)
if not cfg.is_file():
raise ValueError('Run prepare --profile ' + profile + ' first')
data = lock()
tool = ROOT / data['repositories']['pmbootstrap']['path']
repo_at(tool, data['repositories']['pmbootstrap'], False)
destination = managed_path(profile)
repo_at(destination, data['repositories']['pmaports'], False)
config = configparser.ConfigParser()
config.read(cfg)
if (config['pmbootstrap']['aports'] != str(destination)
or config['pmbootstrap']['work'] != str(ROOT / 'work' / ('pmbootstrap-managed-' + profile))):
raise ValueError('Managed config paths changed; review before building')
stamp = json.loads((destination / '.platina-managed.json').read_text())
if stamp['files'] != port_files(destination / 'device/testing'):
raise ValueError('Managed recipes changed; preserve and review local edits')
for name, expected in port_files(ROOT / data['profiles'][profile]['ports']).items():
if stamp['files'].get(name) != expected:
raise ValueError('Versioned recipes changed; run sync --profile ' + profile)
return ['nice', '-n', '10', sys.executable, str(tool / 'pmbootstrap.py'), '-c', str(cfg), '-j', '2']
def doctor():
for name in ('git', 'python3', 'make', 'sh', 'sudo', 'debugfs', 'blkid', 'ssh'):
print(name + ': ' + ('available' if shutil.which(name) else 'missing'))
data = lock()
tool = ROOT / data['repositories']['pmbootstrap']['path']
print('pmbootstrap checkout: ' + ('present' if tool.exists() else 'missing; prepare --fetch'))
for profile in data['profiles']:
print(profile + ' managed config: ' + ('present' if config_path(profile).is_file() else 'not prepared'))
print('Read-only local check; phone, USB ports and services were not probed.')
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
for name in ('check', 'doctor'):
commands.add_parser(name)
prep = commands.add_parser('prepare', help='Create isolated local build checkout/config')
prep.add_argument('--profile', choices=tuple(lock()['profiles']), default='candidate')
prep.add_argument('--fetch', action='store_true', help='Allow downloading pinned Git sources')
syncing = commands.add_parser('sync', help='Refresh managed recipes, preserving local edits on conflict')
syncing.add_argument('--profile', choices=tuple(lock()['profiles']), default='candidate')
kernel = commands.add_parser('kernel', help='Build a kernel locally; no phone connection')
kernel.add_argument('--profile', choices=tuple(lock()['profiles']), default='candidate')
images = commands.add_parser('images', help='Build candidate images locally')
images.add_argument('--output', required=True, help='New candidate-* artifact directory')
for name in ('verify', 'audit'):
command = commands.add_parser(name, help='Offline artifact ' + name)
command.add_argument('directory', type=Path)
args = parser.parse_args()
if args.command == 'check':
check()
elif args.command == 'doctor':
doctor()
elif args.command == 'prepare':
with build_slot():
prepare(args.profile, args.fetch)
elif args.command == 'sync':
with build_slot():
sync(args.profile)
elif args.command == 'kernel':
with build_slot():
run(pmb(args.profile) + ['build', '--arch', 'aarch64', 'linux-postmarketos-qcom-sdm660'])
elif args.command == 'images':
with build_slot():
pmb('candidate')
run([sys.executable, str(ROOT / 'scripts/build-candidate-images.py'),
'--config', str(config_path('candidate')), '--output-name', args.output])
elif args.command == 'verify':
verify(args.directory)
elif args.command == 'audit':
verify(args.directory)
(ROOT / 'reports').mkdir(exist_ok=True)
run([sys.executable, str(ROOT / 'scripts/audit-candidate-artifacts.py'),
'--directory', str(args.directory.resolve())])
if __name__ == '__main__':
try:
main()
except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as exc:
print('ERROR: ' + str(exc), file=sys.stderr)
sys.exit(1)
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Rebuild initramfs module indexes for its actual files; never deploys.
mkinitfs 2.11 copies the complete rootfs module indexes into a partial module
archive. Early udev can then attempt to load drivers absent from that archive.
Run depmod against only the archived modules, preserving the kernel and cmdline.
Only the verified Android v0 layout used by this project is accepted.
"""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
import re
import stat
import struct
import subprocess
import tempfile
def unpack(data):
records = []
offset = 0
seen = set()
while offset + 110 <= len(data):
header = data[offset:offset + 110]
if header[:6] != b'070701':
raise ValueError('Expected newc archive')
fields = [int(header[i:i + 8], 16) for i in range(6, 110, 8)]
size, namesize = fields[6], fields[11]
rawname = data[offset + 110:offset + 110 + namesize]
if not rawname.endswith(b'\0'):
raise ValueError('Invalid archive name')
name = rawname[:-1].decode()
start = (offset + 110 + namesize + 3) & ~3
end = start + size
if end > len(data):
raise ValueError('Truncated archive')
if name == 'TRAILER!!!':
return records
name = name.removeprefix('./')
if name.startswith('/') or '..' in Path(name).parts or name in seen:
raise ValueError('Unsafe or duplicate archive path')
seen.add(name)
records.append((name, fields, data[start:end]))
offset = (end + 3) & ~3
raise ValueError('Missing archive trailer')
def pack(records):
output = bytearray()
trailer = ('TRAILER!!!', [0] * 13, b'')
for name, original, data in [*records, trailer]:
fields = original.copy()
encoded = name.encode() + b'\0'
fields[6], fields[11], fields[12] = len(data), len(encoded), 0
output.extend(b'070701' + ''.join(f'{v:08x}' for v in fields).encode())
output.extend(encoded)
output.extend(b'\0' * (-len(output) % 4))
output.extend(data)
output.extend(b'\0' * (-len(output) % 4))
output.extend(b'\0' * (-len(output) % 512))
return bytes(output)
def parts(boot):
if boot[:8] != b'ANDROID!':
raise ValueError('Not an Android boot image')
f = struct.unpack_from('<10I', boot, 8)
ksize, rsize, second, page, version = f[0], f[2], f[4], f[7], f[8]
if page != 4096 or version != 0 or second != 0:
raise ValueError('Unsupported boot layout')
start = page + ((ksize + page - 1) // page) * page
end = start + ((rsize + page - 1) // page) * page
if end != len(boot):
raise ValueError('Unexpected boot trailer or length')
kernel, ramdisk = boot[page:page + ksize], boot[start:start + rsize]
if boot[576:596] != boot_hash(kernel, ramdisk):
raise ValueError('Boot payload hash mismatch')
return kernel, ramdisk, start
def boot_hash(kernel, ramdisk):
h = hashlib.sha1()
for blob in (kernel, ramdisk, b''):
h.update(blob)
h.update(struct.pack('<I', len(blob)))
return h.digest()
def replace_ramdisk(boot, ramdisk):
kernel, _, start = parts(boot)
result = bytearray(boot[:start])
struct.pack_into('<I', result, 16, len(ramdisk))
result[576:608] = boot_hash(kernel, ramdisk).ljust(32, b'\0')
result.extend(ramdisk)
result.extend(b'\0' * (-len(result) % 4096))
if len(result) > 0x3FFC000:
raise ValueError('Boot partition limit exceeded')
parts(result)
return bytes(result)
def scope(boot, release):
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+-sdm660', release):
raise ValueError('Invalid kernel release')
_, ramdisk, _ = parts(boot)
records = unpack(gzip.decompress(ramdisk))
prefix = next((v for v in (f'usr/lib/modules/{release}/', f'lib/modules/{release}/')
if any(name.startswith(v) for name, _, _ in records)), None)
if not prefix:
raise ValueError('Kernel modules absent')
modules = {name[len(prefix):]: data for name, mode, data in records
if name.startswith(prefix) and '.ko' in name and stat.S_ISREG(mode[1])}
if not modules:
raise ValueError('Empty module archive')
with tempfile.TemporaryDirectory(prefix='platina-depmod-') as directory:
root = Path(directory)
target = root / 'lib/modules' / release
target.mkdir(parents=True)
for name, data in modules.items():
f = target / name
f.parent.mkdir(parents=True, exist_ok=True)
f.write_bytes(data)
for name, _, data in records:
if name.startswith(prefix + 'modules.builtin'):
(target / Path(name).name).write_bytes(data)
(target / 'modules.order').write_text('\n'.join(sorted(modules)) + '\n')
subprocess.run(['depmod', '-C', '/dev/null', '-b', directory, release],
check=True, capture_output=True)
metadata = {f.name: f.read_bytes() for f in target.glob('modules.*')}
dependencies = dict(line.split(':', 1) for line in metadata['modules.dep'].decode().splitlines())
if set(dependencies) != set(modules) or any(d not in modules for ds in dependencies.values() for d in ds.split()):
raise ValueError('Generated dependency index differs from archived files')
filtered = [(n, m, d) for n, m, d in records if not n.startswith(prefix + 'modules.')]
for i, (name, data) in enumerate(sorted(metadata.items())):
fields = [0, stat.S_IFREG | 0o644, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
fields[0] = 100000 + i
filtered.append((prefix + name, fields, data))
new_ramdisk = gzip.compress(pack(filtered), mtime=0)
new_boot = replace_ramdisk(boot, new_ramdisk)
return new_boot, new_ramdisk, len(modules)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('boot', type=Path)
parser.add_argument('--release', required=True)
parser.add_argument('--output', required=True, type=Path)
args = parser.parse_args()
if args.output.exists():
raise SystemExit('Preserve existing output; choose a new directory')
original = args.boot.read_bytes()
boot, ramdisk, count = scope(original, args.release)
args.output.mkdir(parents=True)
files = []
for name, data in [('boot.img', boot), ('initramfs', ramdisk)]:
(args.output / name).write_bytes(data)
files.append({'file': name, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()})
manifest = {'kernel': args.release, 'flashed': False, 'hardware_tested': False,
'source_sha256': hashlib.sha256(original).hexdigest(),
'initramfs_modules': count, 'module_indexes_scoped': True, 'files': files}
(args.output / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
print(json.dumps(manifest, indent=2))
if __name__ == '__main__':
main()
+47
View File
@@ -0,0 +1,47 @@
"""Verify the Tianma candidate matches the retained stock initialization data."""
import json
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
class DisplayCandidateTests(unittest.TestCase):
def test_init_packets_and_delays_match_stock_panel(self):
reference = json.loads((ROOT / 'project/display/tianma-reference.json').read_text())
raw = bytes.fromhex(reference['on_command_hex'])
expected = []
offset = 0
while offset < len(raw):
header = raw[offset:offset + 7]
size = int.from_bytes(header[5:7], 'big')
payload = raw[offset + 7:offset + 7 + size]
self.assertEqual(len(payload), size)
# Downstream encodes a dummy second byte for DCS no-param packets.
if header[0] == 0x05:
self.assertEqual(payload[1:], b'\0')
payload = payload[:1]
expected.append(('generic' if header[0] == 0x29 else 'dcs', payload))
if header[4]:
expected.append(('delay', header[4]))
offset += 7 + size
self.assertEqual(offset, len(raw))
patch = (ROOT / 'ports/candidate/linux-postmarketos-qcom-sdm660/0030-platina-tianma-panel.patch').read_text()
added = '\n'.join(line[1:] for line in patch.splitlines()
if line.startswith('+') and not line.startswith('+++'))
init = added.split('static void platina_tianma_init_cmds', 1)[1].split('\n}', 1)[0]
actual = []
for line in init.splitlines():
write = re.search(r'mipi_dsi_(generic|dcs)_write_seq_multi\(dsi_ctx, (.*?)\);', line)
delay = re.search(r'mipi_dsi_msleep\(dsi_ctx, (\d+)\);', line)
if write:
actual.append((write[1], bytes(int(v.strip(), 16) for v in write[2].split(','))))
elif delay:
actual.append(('delay', int(delay[1])))
self.assertEqual(len([v for v in expected if v[0] != 'delay']), 180)
self.assertEqual(actual, expected)
if __name__ == '__main__':
unittest.main()
+91
View File
@@ -0,0 +1,91 @@
"""Offline power-order, cleanup and image roundtrip tests for the native panel path."""
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch, MagicMock, call
ROOT = Path(__file__).resolve().parents[1]
def load(name, script):
spec = importlib.util.spec_from_file_location(name, ROOT / 'scripts' / script)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
control = load('display_control', 'phone-display.py')
splash = load('display_splash', 'phone-splash.py')
class ControlTests(unittest.TestCase):
def test_powerdown_clears_backlight_before_drm(self):
events = MagicMock()
with patch.object(control, 'brightness', events.brightness), \
patch.object(control.fcntl, 'ioctl', events.ioctl):
control.off(12)
self.assertEqual(events.mock_calls, [call.brightness(0), call.ioctl(12, control.FBIOBLANK, 4)])
def test_renderer_failure_still_powers_down(self):
helper = {'load_frame': lambda _: ({'version': '0.1.1'}, b'frame'),
'geometry': MagicMock(side_effect=ValueError('bad framebuffer'))}
with patch.object(control.runpy, 'run_path', return_value=helper), \
patch.object(control, 'Path') as path, \
patch.object(control.fcntl, 'ioctl'), \
patch.object(control, 'off') as off:
path.return_value.read_text.return_value = 'boot-id'
with self.assertRaisesRegex(ValueError, 'bad framebuffer'):
control.show(12, ROOT, 1, 25)
off.assert_called_once_with(12)
def test_brightness_scales_and_zero_is_exact(self):
with tempfile.TemporaryDirectory() as temp, patch.object(control, 'BACKLIGHT', Path(temp)):
(Path(temp) / 'max_brightness').write_text('4095')
for percent, expected in [(0, 0), (1, 40), (25, 1023), (100, 4095)]:
control.brightness(percent)
self.assertEqual(int((Path(temp) / 'brightness').read_text()), expected)
with self.assertRaises(ValueError):
control.brightness(101)
def test_old_driver_rejected_before_any_device_changes(self):
with patch.object(control, 'Path') as path, patch.object(control, 'DRIVER') as driver:
path.return_value.read_bytes.return_value = b'xiaomi,platina\0'
driver.resolve.return_value.name = 'panel-simple-dsi'
with self.assertRaisesRegex(ValueError, 'Integrated Tianma'):
control.validate()
def test_status_never_opens_framebuffer(self):
with patch.object(control.os, 'open', side_effect=AssertionError('device opened')), \
patch.object(control, 'Path') as path, \
patch.object(control, 'DRIVER') as driver, \
patch.object(control, 'BACKLIGHT') as backlight:
path.return_value.exists.return_value = False
driver.exists.return_value = False
backlight.__truediv__.return_value.exists.return_value = False
self.assertIsNone(control.status()['driver'])
def test_custom_frame_roundtrip(self):
try:
from PIL import Image
except ImportError:
self.skipTest('Host-only image preparation needs Pillow')
frame = load('prepare_frame', 'prepare-display-frame.py')
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
source = root / 'image.png'
Image.new('RGB', (100, 100), 'red').save(source)
output = frame.build(source, root / 'frame')
manifest, raw = splash.load_frame(output)
self.assertEqual(manifest['purpose'], 'custom-display-frame')
self.assertEqual(len(raw), 1080 * 2280 * 4)
self.assertEqual(raw[:4], b'\0\0\0\0') # black letterbox
center = (1140 * 1080 + 540) * 4
self.assertEqual(raw[center:center + 4], b'\0\0\xff\0')
with self.assertRaisesRegex(ValueError, 'immutable'):
frame.build(source, output)
if __name__ == '__main__':
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
"""Verify rejection of bad DCS replies and cleanup on a failed renderer."""
import importlib.util
from pathlib import Path
import tempfile
import unittest
from unittest.mock import MagicMock, patch
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('display_session', ROOT / 'scripts/phone-display-session.py')
session = importlib.util.module_from_spec(spec)
spec.loader.exec_module(session)
class DisplaySessionTests(unittest.TestCase):
def test_only_valid_awake_panel_is_accepted(self):
with tempfile.TemporaryDirectory() as temp:
params = Path(temp)
values = dict(io_enabled=1, read_result=1, wake_result=0, power_after=0x9c)
for name, value in values.items():
(params / name).write_text(str(value))
self.assertEqual(session.check_panel(params), values)
for field, bad in [('power_after', 0x08), ('read_result', -110),
('wake_result', -5), ('io_enabled', 0)]:
(params / field).write_text(str(bad))
with self.assertRaises(ValueError):
session.check_panel(params)
(params / field).write_text(str(values[field]))
def test_renderer_failure_still_releases_owned_power(self):
params = MagicMock()
params.exists.side_effect = [False, True]
fake_path = MagicMock()
with patch.object(session, 'PARAMS', params), \
patch.object(session, 'Path', return_value=fake_path), \
patch.object(session.fcntl, 'flock'), \
patch.object(session, 'validate', return_value='/verified/module.ko'), \
patch.object(session, 'check_panel', return_value={}), \
patch.object(session.subprocess, 'run') as run, \
patch.object(session.subprocess, 'Popen', side_effect=OSError('renderer unavailable')):
with self.assertRaises(OSError):
session.session(['--seconds', '7'])
self.assertEqual(run.call_args_list[-1].args[0], ['rmmod', 'platina_panel_dcs'])
fake_path.write_text.assert_called_once_with('0\n')
if __name__ == '__main__':
unittest.main()
+53
View File
@@ -0,0 +1,53 @@
"""Check deterministic local firmware packaging without distributing firmware payloads."""
import importlib.util
from pathlib import Path
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def load(name, path):
spec = importlib.util.spec_from_file_location(name, ROOT / path)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
firmware = load('prepare_firmware', 'scripts/prepare-firmware.py')
class FirmwarePackagingTests(unittest.TestCase):
def test_archive_does_not_depend_on_host_mtime(self):
import os
with tempfile.TemporaryDirectory() as temp:
path = Path(temp)
source = path / 'example'
source.write_bytes(b'fixture')
first = firmware.archive_files(path, 'modem')
os.utime(source, (1, 1))
self.assertEqual(first, firmware.archive_files(path, 'modem'))
def test_public_board_helper_indexes_aliases_and_rejects_empty_input(self):
relative = Path('ports/candidate/firmware-xiaomi-platina/gen-board-2.py')
overlay = Path('project/public/files') / relative
if (ROOT / overlay).exists():
relative = overlay
if not (ROOT / relative).exists():
self.skipTest('Public packaging helper is tested in the public export')
helper = load('board_index', relative)
with tempfile.TemporaryDirectory() as temp:
path = Path(temp)
with self.assertRaises(ValueError):
helper.index(path)
for name in ('bdwlan.bin', 'bdwlan.b33', 'bdwlan.102', 'bdwlan.unknown'):
(path / name).write_bytes(b'fixture')
indexed = {row['data']: row['names'] for row in helper.index(path)}
self.assertEqual(indexed['bdwlan.b33'], ['bus=snoc,qmi-board-id=33'])
self.assertEqual(indexed['bdwlan.102'], ['bus=snoc,qmi-board-id=102'])
self.assertEqual(indexed['bdwlan.bin'], ['bus=snoc', 'bus=snoc,qmi-board-id=ff', 'bus=snoc,qmi-board-id=0'])
self.assertNotIn('bdwlan.unknown', indexed)
if __name__ == '__main__':
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
"""Protect kernel/cmdline identity and reject unsafe boot/archive inputs."""
import gzip
import hashlib
import importlib.util
from pathlib import Path
import stat
import struct
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('scope_initramfs', Path(__file__).resolve().parents[1] / 'scripts/scope-initramfs-modules.py')
scope = importlib.util.module_from_spec(spec)
spec.loader.exec_module(scope)
def boot_image(ramdisk=b'old ramdisk'):
kernel = b'kernel and appended device tree'
header = bytearray(4096)
header[:8] = b'ANDROID!'
struct.pack_into('<10I', header, 8, len(kernel), 32768, len(ramdisk), 16777216, 0, 15728640, 256, 4096, 0, 0)
cmdline = b'console=ttyMSM0'
header[64:64 + len(cmdline)] = cmdline
header[576:596] = hashlib.sha1(kernel + struct.pack('<I', len(kernel)) + ramdisk + struct.pack('<I', len(ramdisk)) + b'\0' * 4).digest()
return bytes(header) + kernel.ljust(4096, b'\0') + ramdisk.ljust((len(ramdisk) + 4095) // 4096 * 4096, b'\0')
class BootTests(unittest.TestCase):
def test_replacement_preserves_kernel_and_cmdline(self):
before = boot_image()
changed = scope.replace_ramdisk(before, b'new ramdisk' * 900)
kernel, ramdisk, _ = scope.parts(changed)
self.assertEqual(kernel, scope.parts(before)[0])
self.assertEqual(ramdisk, b'new ramdisk' * 900)
self.assertEqual(changed[64:576], before[64:576])
self.assertEqual(changed[608:1632], before[608:1632])
def test_corrupt_payload_rejected(self):
bad = bytearray(boot_image())
bad[4096] ^= 1
with self.assertRaisesRegex(ValueError, 'hash mismatch'):
scope.replace_ramdisk(bad, b'new')
def test_unknown_trailer_rejected(self):
with self.assertRaisesRegex(ValueError, 'trailer'):
scope.parts(boot_image() + b'unknown footer')
def test_unsupported_header_rejected(self):
bad = bytearray(boot_image())
struct.pack_into('<I', bad, 40, 4)
with self.assertRaisesRegex(ValueError, 'layout'):
scope.parts(bad)
def test_unsafe_archive_path_rejected(self):
record = ('../escape', [0, stat.S_IFREG | 0o600, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], b'data')
with self.assertRaisesRegex(ValueError, 'Unsafe'):
scope.unpack(scope.pack([record]))
def test_scoped_index_must_match_actual_modules(self):
prefix = 'lib/modules/7.2.12-sdm660/'
fields = [0, stat.S_IFREG | 0o644, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
records = [(prefix + 'kernel/fixture.ko.zst', fields, b'fixture')]
boot = boot_image(gzip.compress(scope.pack(records)))
def wrong_index(command, **kwargs):
target = Path(command[4]) / 'lib/modules/7.2.12-sdm660'
(target / 'modules.dep').write_text('kernel/absent.ko.zst:\n')
with patch.object(scope.subprocess, 'run', side_effect=wrong_index):
with self.assertRaisesRegex(ValueError, 'differs'):
scope.scope(boot, '7.2.12-sdm660')
if __name__ == '__main__':
unittest.main()
+65
View File
@@ -0,0 +1,65 @@
"""Exercise public-index checks against accidentally staged local files and credentials."""
import contextlib
import importlib.util
import io
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('public_tree', ROOT / 'scripts/check-public-tree.py')
public = importlib.util.module_from_spec(spec)
spec.loader.exec_module(public)
class PublicBoundaryTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
subprocess.run(['git', 'init', '-q', str(self.root)], check=True)
def stage(self, name, content='fixture\n'):
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
subprocess.run(['git', '-C', str(self.root), 'add', '--', name], check=True)
def check(self):
with contextlib.redirect_stdout(io.StringIO()):
public.check(self.root)
def test_plain_source_is_allowed(self):
self.stage('scripts/example.py', 'print("hello")\n')
self.check()
def test_nested_agent_instructions_rejected(self):
self.stage('docs/AGENTS.md')
with self.assertRaisesRegex(ValueError, 'path'):
self.check()
def test_notes_and_configuration_rejected(self):
for name in ('notes.txt', 'config/phone.conf', 'backups/backup.md'):
with self.subTest(name=name):
self.stage(name)
with self.assertRaisesRegex(ValueError, 'path'):
self.check()
subprocess.run(['git', '-C', str(self.root), 'rm', '--cached', '-q', name], check=True)
def test_accidental_token_value_rejected_without_echoing_it(self):
value = 'ghp_' + 'x' * 36
self.stage('README.md', 'credential: ' + value)
with self.assertRaisesRegex(ValueError, 'suppressed') as caught:
self.check()
self.assertNotIn(value, str(caught.exception))
def test_external_symlink_rejected(self):
(self.root / 'external').symlink_to(self.root.parent / 'other')
subprocess.run(['git', '-C', str(self.root), 'add', '--', 'external'], check=True)
with self.assertRaisesRegex(ValueError, 'symlink'):
self.check()
if __name__ == '__main__':
unittest.main()
+97
View File
@@ -0,0 +1,97 @@
"""Offline checks for release versions, decoded assets and padded fbdev rows."""
import gzip
import hashlib
import importlib.util
import json
from pathlib import Path
import struct
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def module(name, path):
spec = importlib.util.spec_from_file_location(name, ROOT / path)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
release = module('platina_release', 'scripts/platina-release.py')
splash = module('platina_splash', 'scripts/phone-splash.py')
class VersionTests(unittest.TestCase):
def test_semantic_bumps(self):
self.assertEqual(release.next_version('0.1.9', 'patch'), '0.1.10')
self.assertEqual(release.next_version('0.1.9', 'minor'), '0.2.0')
self.assertEqual(release.next_version('0.1.9', 'major'), '1.0.0')
def test_bad_versions_rejected(self):
for value in ('01.2.3', '1.2', '../1.2.3', '1.2.3\n', '1.2.3;reboot'):
with self.subTest(value=value), self.assertRaises(ValueError):
release.version_tuple(value)
def test_canonical_identity(self):
self.assertEqual(release.load_release()['name'], 'Platina Linux')
class FramebufferTests(unittest.TestCase):
def layout(self):
variable = [0] * 40
variable[:7] = [1080, 2280, 1080, 4560, 0, 2280, 32]
variable[8:10], variable[11:13], variable[14:16] = [16, 8], [8, 8], [0, 8]
fixed = bytearray(80)
struct.pack_into('=I', fixed, 24, 4352 * 4560)
struct.pack_into('=I', fixed, 48, 4352)
return variable, fixed
def test_stride_and_virtual_page_offset(self):
variable, fixed = self.layout()
result = splash.geometry(struct.pack('=40I', *variable), fixed)
self.assertEqual(result, (1080, 2280, 4352, 4352 * 2280, 4352 * 4560))
def test_wrong_pixel_order_rejected(self):
variable, fixed = self.layout()
variable[8] = 0
with self.assertRaises(ValueError):
splash.geometry(struct.pack('=40I', *variable), fixed)
def test_too_small_mapping_rejected(self):
variable, fixed = self.layout()
struct.pack_into('=I', fixed, 24, 1024)
with self.assertRaises(ValueError):
splash.geometry(struct.pack('=40I', *variable), fixed)
def test_row_padding_and_outside_viewport_preserved(self):
target = bytearray(b'x' * 40)
splash.paint(target, b'abcdEFGH', (1, 2, 8, 8, 40))
self.assertEqual(target[8:12], b'abcd')
self.assertEqual(target[16:20], b'EFGH')
self.assertEqual(target[12:16], b'xxxx')
self.assertEqual(target[:8], b'x' * 8)
def test_real_bundle_valid_and_version_matches(self):
directory = ROOT / ('artifacts/platina-linux-' + release.load_release()['version'])
if not directory.exists():
self.skipTest('Local generated release bundle is not part of clean source checkouts')
manifest, raw = splash.load_frame(directory)
self.assertEqual(manifest['version'], release.load_release()['version'])
self.assertEqual(len(raw), 1080 * 2280 * 4)
def test_corrupt_frame_rejected_before_hardware_access(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
manifest = {'schema': 1, 'name': 'Platina Linux', 'display': {
'width': 1080, 'height': 2280, 'format': 'BGRX8888',
'frame': 'frame.bgrx.gz', 'raw_bytes': 1080 * 2280 * 4,
'compressed_sha256': '0' * 64, 'raw_sha256': '0' * 64}}
(root / 'release.json').write_text(json.dumps(manifest))
(root / 'frame.bgrx.gz').write_bytes(gzip.compress(b'wrong'))
with self.assertRaisesRegex(ValueError, 'checksum'):
splash.load_frame(root)
if __name__ == '__main__':
unittest.main()
+177
View File
@@ -0,0 +1,177 @@
"""Offline regression tests for artifact integrity and isolated build preparation."""
import contextlib
import hashlib
import importlib.util
import io
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('project_workflow', Path(__file__).resolve().parents[1] / 'scripts/project.py')
workflow = importlib.util.module_from_spec(spec)
spec.loader.exec_module(workflow)
class ArtifactTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.bundle = self.root / 'bundle'
self.bundle.mkdir()
self.payload = b'audited boot payload'
(self.bundle / 'boot.img').write_bytes(self.payload)
self.row = {'file': 'boot.img', 'bytes': len(self.payload),
'sha256': hashlib.sha256(self.payload).hexdigest()}
def verify(self, rows=None):
(self.bundle / 'manifest.json').write_text(json.dumps({'files': rows if rows is not None else [self.row]}))
with contextlib.redirect_stdout(io.StringIO()):
workflow.verify(self.bundle)
def test_valid_bundle(self):
self.verify()
def test_same_length_corruption(self):
(self.bundle / 'boot.img').write_bytes(b'X' * len(self.payload))
with self.assertRaisesRegex(ValueError, 'verification failed'):
self.verify()
def test_wrong_length(self):
self.row['bytes'] += 1
with self.assertRaisesRegex(ValueError, 'verification failed'):
self.verify()
def test_path_traversal(self):
self.row['file'] = '../boot.img'
with self.assertRaisesRegex(ValueError, 'Unsafe'):
self.verify()
def test_absolute_path(self):
self.row['file'] = str(self.bundle / 'boot.img')
with self.assertRaisesRegex(ValueError, 'Unsafe'):
self.verify()
def test_symlink(self):
(self.bundle / 'alias.img').symlink_to('boot.img')
self.row['file'] = 'alias.img'
with self.assertRaisesRegex(ValueError, 'symlink'):
self.verify()
def test_duplicate_files(self):
with self.assertRaisesRegex(ValueError, 'Duplicate'):
self.verify([self.row, self.row])
def test_empty_manifest(self):
with self.assertRaisesRegex(ValueError, 'nonempty'):
self.verify([])
def test_missing_file(self):
(self.bundle / 'boot.img').unlink()
with self.assertRaisesRegex(ValueError, 'Missing'):
self.verify()
class PrepareTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.patch = patch.object(workflow, 'ROOT', self.root)
self.patch.start()
self.addCleanup(self.patch.stop)
self.source = self.root / 'sources/pmaports-server'
self.source.mkdir(parents=True)
self.git('init', '-q')
(self.source / 'upstream.txt').write_text('original\n')
self.git('add', 'upstream.txt')
self.git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'fixture')
commit = self.git('rev-parse', 'HEAD').strip()
# Preserve both staged and unstaged edits, like the actual working source.
(self.source / 'upstream.txt').write_text('staged\n')
self.git('add', 'upstream.txt')
(self.source / 'upstream.txt').write_text('unstaged\n')
self.initial_index = self.git('diff', '--cached')
self.initial_work = self.git('diff')
(self.root / 'config/firmware').mkdir(parents=True)
(self.root / 'config/admin-test.pub').write_text('fixture public key\n')
(self.root / 'project').mkdir()
for name in workflow.RECIPES:
directory = self.root / 'ports/candidate' / name
directory.mkdir(parents=True)
(directory / 'input.txt').write_text(name)
checksum = workflow.digest(directory / 'input.txt', 'sha512')
(directory / 'APKBUILD').write_text('sha512sums="\n' + checksum + ' input.txt\n"\n')
blob = self.root / 'config/firmware/local.tar.gz'
blob.write_bytes(b'local fixture firmware')
recipe = self.root / 'ports/candidate/firmware-xiaomi-platina/APKBUILD'
recipe.write_text(recipe.read_text().replace('\n"\n', '\n' + workflow.digest(blob, 'sha512') + ' local.tar.gz\n"\n'))
data = {'schema': 1, 'repositories': {
'pmbootstrap': {'path': 'sources/pmaports-server', 'commit': commit, 'url': 'unused'},
'pmaports': {'commit': commit, 'channels_commit': commit, 'url': 'unused'}},
'profiles': {'candidate': {'ports': 'ports/candidate'}}, 'local_firmware': ['local.tar.gz']}
(self.root / 'project/sources.lock.json').write_text(json.dumps(data))
def git(self, *args):
return subprocess.check_output(['git', '-C', str(self.source), *args], text=True)
def test_prepare_preserves_existing_tree_and_generates_absolute_config(self):
with contextlib.redirect_stdout(io.StringIO()):
workflow.prepare('candidate', False)
self.assertEqual(self.git('diff', '--cached'), self.initial_index)
self.assertEqual(self.git('diff'), self.initial_work)
cfg = workflow.config_path('candidate').read_text()
self.assertIn(str(self.root / 'sources/pmaports-managed-candidate'), cfg)
self.assertIn(str(self.root / 'work/pmbootstrap-managed-candidate'), cfg)
self.assertEqual((self.root / 'sources/pmaports-managed-candidate/upstream.txt').read_text(), 'original\n')
managed = str(self.root / 'sources/pmaports-managed-candidate')
self.assertEqual(subprocess.check_output(['git', '-C', managed, 'remote', 'get-url', 'origin'], text=True).strip(), 'unused')
self.assertEqual(subprocess.check_output(['git', '-C', managed, 'rev-parse', 'origin/main'], text=True).strip(), self.git('rev-parse', 'HEAD').strip())
with self.assertRaisesRegex(ValueError, 'already exists'):
workflow.prepare('candidate', False)
def test_missing_blob_fails_before_checkout(self):
(self.root / 'config/firmware/local.tar.gz').unlink()
with self.assertRaisesRegex(ValueError, 'firmware'):
workflow.prepare('candidate', False)
self.assertFalse((self.root / 'sources/pmaports-managed-candidate').exists())
def test_changed_recipe_fails_before_checkout(self):
(self.root / 'ports/candidate/device-xiaomi-platina/input.txt').write_text('modified')
with self.assertRaisesRegex(ValueError, 'Recipe input'):
workflow.prepare('candidate', False)
self.assertFalse((self.root / 'sources/pmaports-managed-candidate').exists())
def test_sync_refuses_to_overwrite_local_edits(self):
with contextlib.redirect_stdout(io.StringIO()):
workflow.prepare('candidate', False)
target = self.root / 'sources/pmaports-managed-candidate/device/testing/device-xiaomi-platina/input.txt'
target.write_text('important local change')
with self.assertRaisesRegex(ValueError, 'edited locally'):
workflow.sync('candidate')
self.assertEqual(target.read_text(), 'important local change')
def test_sync_applies_verified_snapshot_change(self):
with contextlib.redirect_stdout(io.StringIO()):
workflow.prepare('candidate', False)
source = self.root / 'ports/candidate/device-xiaomi-platina/input.txt'
source.write_text('reviewed update')
(source.parent / 'APKBUILD').write_text('sha512sums="\n' + workflow.digest(source, 'sha512') + ' input.txt\n"\n')
with contextlib.redirect_stdout(io.StringIO()):
workflow.sync('candidate')
target = self.root / 'sources/pmaports-managed-candidate/device/testing/device-xiaomi-platina/input.txt'
self.assertEqual(target.read_text(), 'reviewed update')
self.assertEqual(self.git('diff', '--cached'), self.initial_index)
def test_concurrent_build_rejected(self):
with workflow.build_slot():
with self.assertRaisesRegex(ValueError, 'running'):
with workflow.build_slot():
self.fail('Concurrent build accepted')
if __name__ == '__main__':
unittest.main()