Explorar el Código

Make the driver a standalone repository: README, Makefile, license, board DT example

k4be hace 2 semanas
padre
commit
b3e7f6625a
Se han modificado 5 ficheros con 640 adiciones y 192 borrados
  1. 9 7
      .gitignore
  2. 338 0
      LICENSE
  3. 12 26
      Makefile
  4. 188 159
      README.md
  5. 93 0
      dts/examples/orangepi-zero-i2c1.dtsi

+ 9 - 7
.gitignore

@@ -1,8 +1,10 @@
 build/
-driver/*.mod
-driver/*.mod.c
-driver/.*.cmd
-driver/Module.symvers
-driver/modules.order
-driver/.tmp_versions/
-__pycache__/
+*.o
+*.ko
+*.mod
+*.mod.c
+.*.cmd
+.module-common.o
+Module.symvers
+modules.order
+.tmp_versions/

+ 338 - 0
LICENSE

@@ -0,0 +1,338 @@
+		    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.

+ 12 - 26
Makefile

@@ -1,9 +1,8 @@
-# Linux port: run from this directory.
+# S1D13700 behind a TCA9539: panel core, simulator, DRM driver, overlay.
 #   make test        panel core tests (no hardware, no libraries)
-#   make lib         panel core library for the Python UI (./radio-ui)
-#   make pytest      UI tests: MPD client, rendering, simulated panel
-#   make dtbo        device tree overlay
-#   make module      DRM driver, against KDIR (default: running kernel source)
+#   make asan        the same under ASan and UBSan
+#   make dtbo        device tree overlay(s) from dts/*.dts
+#   make module      DRM driver, against KDIR (default: /usr/src/linux)
 
 BUILD   := build
 CC      ?= gcc
@@ -12,15 +11,13 @@ CFLAGS  += -std=gnu11 -Wall -Wextra -MMD -MP
 CFLAGS  += -Idriver -Isim
 KDIR    ?= /usr/src/linux
 
-CORE     := driver/s1d13700_core.c
-SIM      := sim/s1d13700_sim.c
-PYTHON   ?= python3
-PANEL_LIB := $(BUILD)/libradiopanel.so
+CORE    := driver/s1d13700_core.c
+SIM     := sim/s1d13700_sim.c
+DTBOS   := $(patsubst dts/%.dts,$(BUILD)/%.dtbo,$(wildcard dts/*.dts))
 
-.PHONY: all test asan lib pytest dtbo module clean
-all: test lib
+.PHONY: all test asan dtbo module clean
+all: test
 
-# ---- tests -----------------------------------------------------------------
 $(BUILD)/test_panel: tests/test_panel.c $(CORE) $(SIM)
 	@mkdir -p $(dir $@)
 	$(CC) $(CFLAGS) -o $@ $^
@@ -35,20 +32,9 @@ test: $(BUILD)/test_panel
 asan: $(BUILD)/test_panel_asan
 	$<
 
-# ---- Python UI -------------------------------------------------------------
-lib: $(PANEL_LIB)
+dtbo: $(DTBOS)
 
-$(PANEL_LIB): radio/libpanel.c $(CORE) $(SIM)
-	@mkdir -p $(dir $@)
-	$(CC) $(CFLAGS) -fPIC -shared -o $@ $^
-
-pytest: $(PANEL_LIB)
-	$(PYTHON) -W 'ignore::DeprecationWarning:gi.events' -m unittest discover -s tests -p 'test_*.py' -v
-
-# ---- device tree and kernel module -----------------------------------------
-dtbo: $(BUILD)/radio-panel.dtbo
-
-$(BUILD)/radio-panel.dtbo: dts/radio-panel.dts
+$(BUILD)/%.dtbo: dts/%.dts
 	@mkdir -p $(dir $@)
 	dtc -@ -I dts -O dtb -o $@ $<
 
@@ -59,4 +45,4 @@ clean:
 	rm -rf $(BUILD)
 	-$(MAKE) -C $(KDIR) M=$(CURDIR)/driver clean
 
--include $(shell find $(BUILD) -name '*.d' 2>/dev/null)
+-include $(wildcard $(BUILD)/*.d)

+ 188 - 159
README.md

@@ -1,180 +1,129 @@
-# Linux port
+# s1d13700-tca: S1D13700 LCD behind a TCA9539 I²C expander
 
-Replaces the LPC1114 firmware: the panel and keys hang off I²C expanders on the
-Linux board. The panel runs on real hardware through `radio-ui i2c` and
-`radio-ui drm`. All 13 keys read correctly through the key expander on the test
-rig. The overlay has not run.
+A Linux DRM driver for an Epson S1D13700 (SED1335 family) graphic LCD whose
+8080-style parallel bus is driven through a TI TCA9539 16-bit I²C GPIO
+expander, plus the parts that make it testable without hardware:
+
+- an OS-independent **panel core** (`driver/s1d13700_core.*`) that the
+  driver uses and userspace can link as well,
+- a **simulator** (`sim/`) that decodes the I²C byte stream as a TCA9539 and
+  S1D13700 would and flags bus protocol faults,
+- **tests** for the core, run against the simulator,
+- **device tree** examples: an overlay and a board DT fragment.
+
+It was written for a 240×160 panel at 2 bpp on an Orange Pi Zero (Allwinner
+H2+, 400 kHz I²C) and runs there, built into the kernel, with fbcon on the
+panel. The radio-ui application (sibling repository `radio-ui`) uses the
+same core from userspace, over i2c-dev or through this driver.
 
 | Path | What |
 |---|---|
-| `driver/s1d13700_core.*` | Panel core, used by everything: init, 2 bpp conversion, write planner, TCA9539 stream |
-| `driver/s1d13700_drm.c` | DRM driver (6.x kernels) |
-| `sim/` | Model of the TCA9539 and S1D13700: decodes the I²C bytes and flags bus faults |
-| `radio/` | The application, in Python: UI, MPD client, I²C key polling and the `sim`, `i2c`, `drm` and `keytest` frontends |
-| `radio/libpanel.c` | The panel core and simulator as a library for the application |
-| `radio-ui` | Starts the application |
-| `dts/radio-panel.dts` | Overlay for the keys, backlight and panel |
-| `tests/` | Panel core tests, application tests, a fake MPD server and `hw_test.sh` |
+| `driver/s1d13700_core.*` | Panel core: init, XRGB8888 to 1/2/4 bpp, write planner, TCA9539 stream encoder |
+| `driver/s1d13700_drm.c` | Atomic KMS driver with fbdev emulation and a backlight device |
+| `driver/Kbuild` | Out-of-tree build |
+| `sim/` | Model of the TCA9539 and S1D13700 interface, with fault counters |
+| `tests/test_panel.c` | Core tests against the simulator |
+| `dts/radio-panel.dts` | Overlay: panel, key expander, `gpio-keys` |
+| `dts/examples/orangepi-zero-i2c1.dtsi` | The same for a board DT, as used on the Orange Pi Zero |
+| `docs/s1d13700-recommendations.md` | Review of the core and driver, applied |
 
 ## Building
 
-    make test          # panel core tests, no hardware or libraries
-    make lib           # build/libradiopanel.so, needed by the application
-    make pytest        # application tests, no hardware or display
-    make dtbo
+    make test                       # core tests, no hardware or libraries
+    make asan                       # the same under ASan and UBSan
     make module KDIR=/path/to/kernel
-
-The application runs on Python 3.7.3 (Debian buster) to 3.14 and needs
-PyGObject with GLib, Pango and PangoCairo, pycairo and its PyGObject bridge;
-GTK 3 for `sim` and `--window-keys`; libdrm for `drm`. On Debian:
-
-    apt install python3-gi python3-gi-cairo gir1.2-pango-1.0 gir1.2-gtk-3.0
-
-`RADIO_PANEL_LIB` points it at the library if it is not in `build/`.
-
-Volume is set through MPD (`volume ±1`), so MPD needs a working mixer. The
-default hardware mixer looks for a `PCM` control, which the H3 codec does not
-have; the firmware's old `volup`/`voldown` scripts used `DAC`, so the ALSA
-output in `/etc/mpd.conf` needs:
-
-    mixer_type      "hardware"
-    mixer_device    "default"
-    mixer_control   "DAC"
-
-Without it MPD's status has no `volume:` line and the volume keys do nothing.
-
-## Running
-
-Window with the simulated panel, using a real MPD:
-
-    ./radio-ui sim --host radio.lo
-
-The window shows the simulator's display memory, and the traffic each update
-costs. Keys: `Z X C V B` for prev/play/pause/stop/next, arrows, `Enter`, `Esc`,
-`M`, `L`, `Space` for pause, and a multimedia keyboard's media keys.
-
-Real panel through i2c-dev, for bring-up or on a kernel too old for the driver,
-or through the DRM driver:
-
-    ./radio-ui i2c --bus N --pattern geometry
-    ./radio-ui i2c --bus N --pattern gray
-    ./radio-ui i2c --bus N --host radio.lo
-    ./radio-ui drm --host radio.lo
-
-On the main screen the keys are prev/play/pause/stop/next, up/down for the
-volume and Esc to refresh. List opens the playlist: the whole MPD queue, the
-current song centered and selected. Up/down move the selection, OK plays it,
-and Menu, Esc, List or 30 s without a key go back. With more than 1 bpp the
-selection is a gray bar, otherwise inverted. The transport keys keep working
-there.
-
-`--bus` must name a known adapter; motherboard and display buses are always
-refused. Only use the bus number of the adapter the panel is wired to.
-`./radio-ui FRONTEND --help` lists all options.
-
-### Hardware test: panel and keys
-
-`tests/hw_test.sh` finds the i2c-tiny-usb bus, checks that no kernel driver
-holds 0x74 or 0x76, builds the library if needed and runs:
-
-    tests/hw_test.sh             # panel shows the 13 keys; pressed ones inverted
-    tests/hw_test.sh keys-only   # keys printed to the terminal, panel untouched
-    tests/hw_test.sh pattern     # geometry and gray patterns, then the keys
-    tests/hw_test.sh ui          # full UI with the I2C keys, against the fake MPD
-    tests/hw_test.sh init        # panel and U2 set up over i2c-dev, left on
-    tests/hw_test.sh drm         # sudo: bind the DRM driver to 0x74, pattern,
-                                 # backlight on, U2 set up; left active
-    tests/hw_test.sh release     # sudo: unbind the DRM driver again
-    tests/hw_test.sh -b 11 keys  # a given bus
-
-The key screen (`radio-ui keytest --bus N`) also shows the raw input ports,
-press and repeat counts and read errors; each event is printed too. Ctrl-C
-quits and switches the panel off. The i2c-dev modes refuse to run while a
-kernel driver holds 0x74 or 0x76; `release` frees 0x74 after `drm`.
-
-After `drm`, `./radio-ui drm --host radio.lo` drives the panel through the
-driver and reads the keys from U2 on the same bus.
-
-### Keys over I²C
-
-`radio-ui i2c` polls U2 at 0x76 on its own bus every 20 ms (`--keys-addr`,
-`--keys-poll`; `--no-i2c-keys` falls back to evdev). `radio-ui drm` uses the
-evdev device `radio-keys` if it exists (the overlay on the target), otherwise
-U2 on the bus the DRM panel is on; `--keys-bus N` names another bus and
-`--no-i2c-keys` disables this. The polling reads debounce over two samples and
-autorepeat like gpio-keys (250 ms, then every 33 ms; the app's 300 ms lockout
-applies). Keys held at start are ignored until released, and a reading with
-more than 3 keys down is taken as a bus fault, so a fault cannot send player
-commands. Do not load the overlay's U2 node while doing this.
-
-### Test mode: real panel, PC keyboard
-
-`--window-keys` opens a small window on the X display; keys typed into it (the
-same as in `sim`) go to the app, which drives the real panel and the real MPD:
-
-    ./radio-ui i2c --bus 11 --host radio.lo --window-keys
-    ./radio-ui drm --host radio.lo --window-keys
-
-It also has a button per key. Closing the window quits. Evdev is not read in
-this mode unless `--input` is given as well.
-
-Text uses Verdana and Andale Mono (Microsoft core fonts) if installed, otherwise
-Liberation Sans and Mono, drawn without antialiasing.
-
-### Test rig on the development PC
-
-The panel hangs off an ATmega8U2 i2c-tiny-usb bridge. Load the driver for
-400 kHz (its default, `delay=10`, is only 50 kHz), then find the bus number:
-
-    sudo modprobe -r i2c_tiny_usb; sudo modprobe i2c_tiny_usb delay=1
-    grep -l i2c-tiny-usb /sys/bus/i2c/devices/i2c-*/name
-
-To try the keys without touching the real player, run the fake MPD and point
-the panel at it:
-
-    tests/fake_mpd.py 6601 build/mpd-commands.log 5 &
-    ./radio-ui i2c --bus 11 --host localhost --port 6601 --window-keys
-
-Never scan or use the other buses on this PC: some reach the CPU regulators.
-
-### Simulating keys
-
-The panel frontends read keys from evdev: the device named `radio-keys`, or
-whatever `--input` names. On the PC without the U2 keypad:
-
-- **PC keyboard:** `--input /dev/input/by-id/<keyboard>-event-kbd` (needs read
-  access, group `input`). Arrows and Esc map directly; the media keys of a
-  multimedia keyboard map to Prev/Next/Stop if they send `KEY_PREVIOUSSONG`,
-  `KEY_NEXTSONG`, `KEY_STOPCD`. Play, Pause, OK, Menu and List have no
-  ordinary key. The keyboard keeps typing into the focused window too.
-- **Virtual device:** with `CONFIG_INPUT_UINPUT`, create a device named
-  `radio-keys` (for example `evemu-device` or python-evdev's `UInput`) and send
-  the codes in `radio/platform.py`. `radio-ui` finds it without `--input`.
-  The development kernel has uinput disabled.
-- **Window:** `--window-keys` (above), or `radio-ui sim`, which draws on the
-  simulated panel only.
+    make dtbo                       # build/*.dtbo from dts/*.dts
+
+The driver needs a 6.x kernel with damage helpers, `drm_fbdev_shmem` and the
+DRM client setup (built against 6.18 and 7.3). It does not build on 4.19;
+there the panel can still be driven from userspace through i2c-dev with the
+core.
+
+### In the kernel tree
+
+Copy `driver/s1d13700_drm.c`, `s1d13700_core.c` and `s1d13700_core.h` into
+e.g. `drivers/gpu/drm/tiny/s1d13700-tca/` and add:
+
+    # Kconfig
+    config DRM_S1D13700_TCA
+    	tristate "S1D13700 panel behind a TCA9539 I2C expander"
+    	depends on DRM && I2C
+    	select DRM_CLIENT_SELECTION
+    	select DRM_KMS_HELPER
+    	select DRM_GEM_SHMEM_HELPER
+    	select BACKLIGHT_CLASS_DEVICE
+
+    # Makefile
+    obj-$(CONFIG_DRM_S1D13700_TCA) += s1d13700-tca.o
+    s1d13700-tca-y := s1d13700_drm.o s1d13700_core.o
+
+The Orange Pi Zero build scripts (`build-kernel.sh` in the OPi0 project) do
+this on every build and set it to built-in, so fbcon shows the boot log on
+the panel. Linux 7.3 renamed `struct drm_atomic_state` to
+`struct drm_atomic_commit`; that script force-includes a small compatibility
+header into `s1d13700_drm.c` rather than changing the source.
+
+## Driver
+
+- **Binding:** I²C client, `compatible = "k4be,s1d13700-tca9539"` (`k4be` is
+  not a registered vendor prefix, so `dtbs_check` warns), or I²C id
+  `s1d13700-tca9539` for `new_device`:
+
+      echo s1d13700-tca9539 0x74 > /sys/bus/i2c/devices/i2c-N/new_device
+
+- **Module parameters** (read-only, so kernel arguments when built in, e.g.
+  `s1d13700_tca.tcr=162`):
+
+  | Parameter | Default | |
+  |---|---|---|
+  | `width`, `height` | 240, 160 | panel size in pixels |
+  | `bpp` | 2 | 1, 2 or 4 bits per pixel |
+  | `tcr` | 162 | SYSTEM SET TC/R, sets the frame rate |
+
+- **Format:** XRGB8888, converted to gray with a plain threshold (no
+  dithering). White maps to "pixel off", the light background of the LCD.
+- **Updates:** plane updates turn damage into a pending frame; a worker sends
+  it and merges whatever arrives meanwhile. Messages are capped at 1025 bytes
+  (about 23 ms at 400 kHz) so other devices on the bus get a turn, and the
+  adapter's `max_write_len` is honoured. A failed transfer makes the next
+  update rewrite the frame; a failed init is retried.
+- **Backlight:** expander pin P1.0 is registered as
+  `/sys/class/backlight/radio-backlight` (brightness 0 or 1, on at probe).
+  The sysfs file is `root:root 0644`; a udev rule can open it to a group:
+
+      ACTION=="add", SUBSYSTEM=="backlight", KERNEL=="radio-backlight", RUN+="/bin/chgrp video /sys%p/brightness", RUN+="/bin/chmod g+w /sys%p/brightness"
+
+- **Statistics** in debugfs, under the I²C client's directory:
+  `lcd_writes`, `data_bytes`, `seeks`, `dir_changes`, `i2c_msgs`, `i2c_bytes`.
+- Blanking is display off only; the controller's `SLEEP` is not used.
+
+Only one driver can own an I²C address: U1 must not be bound to
+`gpio-pca953x`. The driver needs one continuous write that alternates both
+expander ports, which the GPIO API cannot express (going through it would
+cost roughly 2.5-3× more bus time per LCD byte).
 
 ## Wiring
 
-**U1, TCA9539 at 0x74** (A1=L, A0=L), raw I²C client of the panel code
+**U1, TCA9539 at 0x74** (A1=L, A0=L), the driver's I²C client:
 
 | Pin | Signal | Module pin |
 |---|---|---|
 | P0.0-7 | D0-D7 | D0-D7 |
-| P1.0 | Backlight enable (active high, assumed) | |
+| P1.0 | Backlight enable (active high) | |
 | P1.1 | RES# | RST |
 | P1.2 | A0 | A15 |
 | P1.3 | WR# | WE |
 | P1.4 | RD# | RE |
-| P1.5 | CS# (held low after reset; was hardwired low on the old board) | CS0 |
+| P1.5 | CS# (held low after reset) | CS0 |
 | P1.6-7 | spare | |
 
-**U2, TCA9539 at 0x76** (A1=H, A0=L): polled by `radio-ui i2c`, or stock
-`gpio-pca953x` with the overlay
+The pin assignment is fixed in `s1d13700_core.h`.
 
-Keys are active high: each pin has a pull-down (the TCA9539 has no internal
-ones) and its key connects it to the supply. `INT` is not connected on the USB
-test board, so the keys are polled; the final board wires it to a host GPIO.
+**U2, TCA9539 at 0x76** (A1=H, A0=L), optional, for keys: stock
+`gpio-pca953x` plus `gpio-keys`, as in the device tree examples. Keys are
+active high, each pin with an external pull-down (the TCA9539 has none) and
+its key to the supply. `INT` (open drain, active low) goes to a host GPIO;
+without it, use `gpio-keys-polled`.
 
 | Pin | Key | Pin | Key |
 |---|---|---|---|
@@ -187,8 +136,88 @@ test board, so the keys are polled; the final board wires it to a host GPIO.
 | | | P1.6 | Play |
 | | | P1.7 | Prev |
 
-## To confirm on hardware
+## Device tree
+
+`dts/radio-panel.dts` is an overlay written with plain numbers instead of
+`#include`, so it also works with `armbian-add-overlay`. It targets `i2c0`
+and puts U2's INT on PA6; check both against the board. For the i2c-dev
+userspace path, remove its `panel@74` node; with keys polled over i2c-dev,
+do not load the U2 node either.
+
+`dts/examples/orangepi-zero-i2c1.dtsi` is the version in use on the Orange Pi
+Zero, for inclusion in a board DTS: i2c1 at 400 kHz, panel, U2 with INT on
+PA6 and the `radio-keys` input device. The two key tables must stay the
+same; the OPi0 build compares the overlay's with its board DTB.
+
+## How it works
+
+### Panel core
+
+- **Stream encoder.** One write message starts with command byte `0x02`, then
+  alternates P0 (data) and P1 (control). Each LCD cycle is
+  `data, WR=0, data, WR=1`. A0 changes get their own P0/P1 pair with WR# high,
+  because A0 needs setup time before the WR# edge and shares a port with it. A
+  cycle is never split across messages, so WR# is not left low when the bus is
+  released.
+- **Init.** Programs the expander outputs before the directions, holds reset
+  20 ms, then configures the controller: `FX=7` and `HDOT=0` (required above
+  1 bpp), `CM=1` (required in graphics mode), grayscale value 1. VRAM is
+  cleared before the display is turned on.
+- **Planner.** Compares each frame with a shadow of VRAM at byte level, so even
+  a client that redraws everything costs only what changed. Rows with changes
+  form bands, each written horizontally or vertically (`CSRDIR` down),
+  whichever is cheaper. Unchanged gaps up to 6 bytes (the cost of a seek) are
+  rewritten rather than skipped.
+- **Cursor.** A memory write turns the controller's cursor on even when the
+  DISP ON attributes say off (REG[0Ah] note in the hardware specification).
+  After any update that wrote VRAM while the display is on, the core re-sends
+  DISP ON (12 I²C bytes).
+- **Transport.** The caller supplies a send function: `i2c_master_send()` in
+  the driver, `I2C_RDWR` on i2c-dev, or the simulator.
+
+### Simulator
+
+Models the TCA9539 register pairs and the S1D13700 indirect interface from the
+I²C bytes alone. It counts faults: A0 changing with a WR# edge, parameters
+with no command or too many, unknown commands, bad registers, messages ending
+between P0 and P1, inconsistent SYSTEM SET, and writes during reset. It also
+models the cursor behaviour above.
+
+### Bus cost
+
+| Update (240×160, 2 bpp, 400 kHz) | I²C bytes | Bus time |
+|---|---|---|
+| One 8×13 digit | 169 | 3.8 ms |
+| Full frame | 38 474 (38 messages) | 867 ms |
+| Typical small UI update | 113-177 | 2.6-4.0 ms |
+
+Calculated from the bytes sent on an ideal bus; real timing is slower. The
+Allwinner `i2c-mv64xxx` takes about one interrupt per byte.
+
+## Tests
+
+`make test` covers: init values, invalid configurations, no change means no
+traffic, direction choice, gap merging, 2000 random update rounds at 1/2/4 bpp
+and message sizes 7/61/1025, transport and backlight failure recovery, lost
+direction recovery, pixel conversion, the simulator's renderer and its fault
+detector. They also pass under ASan and UBSan.
+
+## Not settled
+
+- TC/R and the frame rate: 162 comes from a working AVR 2 bpp setup.
+- Flicker: the datasheet recommends VRAM access during blanking, which cannot
+  be synchronised over I²C.
+- The extra cycle for A0 setup may be removable, saving about a third of the
+  seek cost.
+- Only XRGB8888 is exposed; R1/R2 formats could be added.
+- The backlight name and the U1 pin assignment are fixed in the source.
+
+## References
+
+- [S1D13700F01 hardware specification, Rev. 4.07](https://global-origin.epson.com/products_and_drivers/semicon/pdf/id003161.pdf)
+- [TCA9539 datasheet (SCPS202C)](https://www.ti.com/lit/ds/symlink/tca9539.pdf)
+- In-tree template: `drivers/gpu/drm/sitronix/st7571-i2c.c`
+
+## License
 
-- TC/R (`--tcr`) for frame rate; 162 comes from the AVR project's 2 bpp setup
-- Key autorepeat on Up/Down; then the overlay (`evtest`)
-- The application on the target's Python 3.7.3
+GPL-2.0-only (see `LICENSE` and the SPDX headers).

+ 93 - 0
dts/examples/orangepi-zero-i2c1.dtsi

@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: (GPL-2.0+ OR MIT)
+/*
+ * Example for a board device tree (not an overlay): the panel (U1, 0x74),
+ * the key expander (U2, 0x76) and the 13 keys on i2c1 of an Orange Pi Zero
+ * (Allwinner H2+). Running on real hardware, built into the board DTB.
+ *
+ * Include it after the mainline board file, e.g.
+ *
+ *	#include "sun8i-h2-plus-orangepi-zero.dts"
+ *	#include "orangepi-zero-i2c1.dtsi"
+ *
+ * For another board: change the bus (&i2c1, its pinctrl) and the INT pin
+ * (PA6 here, in &pio and in the interrupts of gpio@76). Without INT wired,
+ * drop the interrupt properties and use "gpio-keys-polled" with
+ * poll-interval = <20> instead of "gpio-keys".
+ *
+ * The key table matches dts/radio-panel.dts. Keep the two the same.
+ */
+
+#include <dt-bindings/gpio/gpio.h>
+#include <dt-bindings/input/input.h>
+#include <dt-bindings/interrupt-controller/irq.h>
+
+/ {
+	aliases {
+		i2c1 = &i2c1;	/* keep /dev/i2c-1 */
+	};
+};
+
+/*
+ * PA18 (SCL) / PA19 (SDA). 400 kHz relies on the pull-ups on the panel
+ * board; the SoC's internal ones are too weak for that speed.
+ */
+&i2c1 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&i2c1_pins>;
+	clock-frequency = <400000>;
+	status = "okay";
+
+	/* "k4be" is not a registered vendor prefix: dtbs_check warns here */
+	panel@74 {
+		compatible = "k4be,s1d13700-tca9539";
+		reg = <0x74>;
+	};
+
+	/* U2: A1=H, A0=L. INT is open drain, active low, on PA6. */
+	radio_u2: gpio@76 {
+		compatible = "ti,tca9539";
+		reg = <0x76>;
+		pinctrl-names = "default";
+		pinctrl-0 = <&radio_u2_int_pin>;
+		gpio-controller;
+		#gpio-cells = <2>;
+		interrupt-controller;
+		#interrupt-cells = <2>;
+		interrupt-parent = <&pio>;
+		interrupts = <0 6 IRQ_TYPE_LEVEL_LOW>;	/* PA6 */
+	};
+};
+
+&pio {
+	radio_u2_int_pin: radio-u2-int-pin {
+		pins = "PA6";
+		function = "irq";
+		bias-pull-up;
+	};
+};
+
+/ {
+	/*
+	 * Keys are active high: one pin each to the supply, with an external
+	 * pull-down. Pins 0-7 are P0.0-7, 8-15 are P1.0-7; P0.0-2 unused.
+	 */
+	radio-keys {
+		compatible = "gpio-keys";
+		label = "radio-keys";
+		autorepeat;
+
+		key-next  { label = "next";  gpios = <&radio_u2 3 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_NEXTSONG>;     debounce-interval = <20>; };
+		key-left  { label = "left";  gpios = <&radio_u2 4 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_LEFT>;         debounce-interval = <20>; };
+		key-down  { label = "down";  gpios = <&radio_u2 5 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_DOWN>;         debounce-interval = <20>; };
+		key-up    { label = "up";    gpios = <&radio_u2 6 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_UP>;           debounce-interval = <20>; };
+		key-right { label = "right"; gpios = <&radio_u2 7 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_RIGHT>;        debounce-interval = <20>; };
+		key-esc   { label = "esc";   gpios = <&radio_u2 8 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_ESC>;          debounce-interval = <20>; };
+		key-ok    { label = "ok";    gpios = <&radio_u2 9 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_OK>;           debounce-interval = <20>; };
+		key-menu  { label = "menu";  gpios = <&radio_u2 10 GPIO_ACTIVE_HIGH>; linux,code = <KEY_MENU>;         debounce-interval = <20>; };
+		key-list  { label = "list";  gpios = <&radio_u2 11 GPIO_ACTIVE_HIGH>; linux,code = <KEY_LIST>;         debounce-interval = <20>; };
+		key-stop  { label = "stop";  gpios = <&radio_u2 12 GPIO_ACTIVE_HIGH>; linux,code = <KEY_STOPCD>;       debounce-interval = <20>; };
+		key-pause { label = "pause"; gpios = <&radio_u2 13 GPIO_ACTIVE_HIGH>; linux,code = <KEY_PAUSECD>;      debounce-interval = <20>; };
+		key-play  { label = "play";  gpios = <&radio_u2 14 GPIO_ACTIVE_HIGH>; linux,code = <KEY_PLAYCD>;       debounce-interval = <20>; };
+		key-prev  { label = "prev";  gpios = <&radio_u2 15 GPIO_ACTIVE_HIGH>; linux,code = <KEY_PREVIOUSSONG>; debounce-interval = <20>; };
+	};
+};