On this page
I needed a NAS for backups, and I already had one in a cupboard: an Acer Aspire easyStore H340. I had not used it for years. It ran Windows Home Server, it was slow, and Microsoft ended support for that system in 2013 (opens in a new tab).
So I put Debian and OpenMediaVault on it. That worked well. The disks and the network worked, and the shares did what I needed.
Only the front of the box stayed dead. The drive lamps stayed dark. The USB Backup button did nothing, and neither did the power button. On Windows Home Server all of these worked, so I knew the hardware was fine. The software was missing.
I wrote that software. After using it for a while, I decided to share it as open source, for anyone who has the same box and the same problem. This article explains what the problem is and how the fix works.
The code is here: github.com/ehsanenaloo/Acer-h340-linux (opens in a new tab)
The machine
The H340 is a small home server with four drive bays. Inside is an Intel Atom 230 at 1.6 GHz with one core, 2 GiB of RAM and a legacy BIOS. The board is called WG945GCM. A Super I/O chip, the SMSC SCH5127, sits on the board. It reads fan speed and temperature, and it has pins that Acer wired to the front lamps. Linux has a driver for the sensors of this chip (opens in a new tab), but there is no driver for the lamps.
On the front you get a power button, a USB Backup button and one USB port. You also get lamps for power, network, USB and system status, and one lamp for each of the four bays.
Linux does not know any of this. The USB Backup button is not a standard device either. So nothing happens.
Problem 1: the power button
This one was the easiest. The power button is a normal ACPI button, and systemd-logind handles it. The button worked. The setting was the problem.
By default, systemd shuts the machine down when you press the power key (logind.conf (opens in a new tab)). OpenMediaVault changes that. It has a power button setting under System > Power Management (documentation (opens in a new tab)), and its default is "nothing". OpenMediaVault turns that into HandlePowerKey=ignore in the logind config (the Salt state that does it (opens in a new tab)). So every press was ignored on purpose.
The plugin I wrote has a page for this, with three choices: shut down, sleep or nothing. It does not keep its own copy of the setting. It reads and writes the same OpenMediaVault setting that the system page uses, so the two pages always agree. On a fresh install, if the setting is still the default, the plugin changes it to "shut down".
Problem 2: the USB Backup button
This button is not a keyboard key. The firmware tells the system about it with an ACPI notification. An ACPI device named MBTN (hardware ID PNP0C32) gets a Notify with the value 0x80 every time you press it. The values from 0x80 up are for the device itself, and the kernel header (opens in a new tab) lists them as device-specific. The notification comes from a general purpose event, _L18. In the name, L means that the event is level triggered, and 18 is the event number in hex (ACPICA source in the kernel (opens in a new tab)).
Some systems have a generic way to turn this into a key press. This firmware does not. So I wrote a small kernel module. It does one thing: it listens for that notification and sends a normal Linux key event. The key is KEY_COPY, which has the number 133 in the kernel header (opens in a new tab).
static void h340_backup_notify(acpi_handle handle, u32 event, void *context)
{
struct h340_backup_button *button = context;
if (event != 0x80)
return;
mutex_lock(&button->lock);
input_report_key(button->input, KEY_COPY, 1);
input_sync(button->input);
input_report_key(button->input, KEY_COPY, 0);
input_sync(button->input);
mutex_unlock(&button->lock);
}The module does no port I/O and no hardware writes. It only turns an event into a key. After that, any program can read the key from /dev/input (kernel documentation (opens in a new tab)).
The check for 0x80 matters. Other notifications, such as wake-up events, must never become a "copy" key. I keep the module in DKMS, so it is built again for each new kernel (Debian wiki (opens in a new tab)).
Problem 3: the lamps
The lamps were the hard part. They are not on any bus that Linux drives for you. They are single pins on the chipset and the Super I/O chip, and the only way to switch them is to write to I/O ports.
I did not find these addresses alone. The open source project mediasmartserverd (opens in a new tab) has already mapped the lamps of this family of boxes, and the H340 is on its list. I took the measured addresses and bit masks from it, and then I checked each one on my own machine. My code is separate from that project. I do not use its start-up routines, and I never touch the watchdog.
How a lamp is switched
Each lamp is one bit in a byte at an I/O port. To light a lamp you read the byte, change one bit and write it back. On Linux, root can reach the ports through /dev/port (man page (opens in a new tab)).
class Ports:
def __enter__(self):
self.fd = os.open("/dev/port", os.O_RDWR | os.O_CLOEXEC)
return self
def read(self, port):
data = os.pread(self.fd, 1, port)
if len(data) != 1:
raise OSError("Short read at port 0x%04x" % port)
return data[0]
def write(self, port, value):
if os.pwrite(self.fd, bytes([value]), port) != 1:
raise OSError("Short write at port 0x%04x" % port)These ports also control other things on the board, so I take care with every write. The service has a fixed list of bits it owns:
OWNED_BITS = {0x084B: 0x12, 0x084F: 0xCF, 0x118E: 0x10,
0x118F: 0x09, 0x119A: 0x10, 0x119B: 0x09}A write changes only the bits in that list. All other bits keep the value they had. After each write, the service reads the byte again and checks that it matches. If it does not match, the service stops and restores the start-up values.
The write itself is a masked read, change and write. This is the only function that touches a lamp byte:
def masked_write(self, port, value):
mask = OWNED_BITS[port]
before = self.io.read(port)
desired = (before & ~mask) | (value & mask)
if before != desired:
self.io.write(port, desired)
if self.io.read(port) & mask != desired & mask:
raise RuntimeError("LED readback mismatch at 0x%04x" % port)Bits outside the mask are never changed. The last two lines are the read-back check.
What the bits mean
| Lamp | Ports | Notes |
|---|---|---|
| Bays 1 to 4 | 0x084B, 0x084F | Each bay has a blue LED and a red LED. They are separate parts |
| System (i) | 0x118E, 0x118F, 0x119A, 0x119B | Blue and red, active low |
| USB | 0x118F | One blue LED on GPIO 27, active low |
"Active low" means a zero lights the lamp.
Each bay has two LEDs. When both are on, you see purple. The service uses that on purpose: a purple bay means a disk is present but not mounted yet.
Safety checks before the first write
Writing to random ports on the wrong machine can do real harm. So the service checks the board before it writes anything:
- The DMI vendor and product name must be exactly
AcerandAspire easyStore H340. - The LPC bridge must have the expected PCI ID, and its GPIO base register must read
0x1181. - The Super I/O chip must identify itself correctly.
- The kernel modules
dme1737,gpio_ichandleds_ss4200must not be loaded, because they would fight for the same pins. The first one is the kernel driver for the sensors of the SCH5127.
In code, the DMI check and the module check look like this:
def verify_platform(root=Path("/sys")):
dmi = root / "class/dmi/id"
if ((dmi / "sys_vendor").read_text().strip(),
(dmi / "product_name").read_text().strip()) != ("Acer", "Aspire easyStore H340"):
raise RuntimeError("Unsupported DMI identity")
for module in ("dme1737", "gpio_ich", "leds_ss4200"):
if (root / "module" / module).exists():
raise RuntimeError("Potentially competing hardware driver: " + module)If any check fails, the service refuses to start. There is no fallback for other boards. When the service stops in a normal way, it puts the lamp bits back to the values it found.
From disk state to lamp state
The lamps are only useful if they show the truth. The service looks at the system every 0.2 seconds and decides what each lamp should do.
Bays
A bay is a fixed SATA port. The service reads the port of each disk from /sys and uses it as the bay number. The user never has to assign a disk to a bay. I first thought of a setting for this. Then I saw that a user could easily point a bay at the wrong disk, so I removed the idea.
The service remembers which disks belong to the machine. It identifies a disk by its ata- name in /dev/disk/by-id. A disk joins the list when it is mounted. After that, if the disk disappears, the bay shows a red blink, because a known disk is missing.
| Bay lamp | Meaning |
|---|---|
| Blue pulse | The disk is in use |
| Red blink | SMART reports a problem, or a known disk is missing |
| Steady purple | A disk is present but not mounted |
Unknown values stay unknown. If the service cannot read SMART data, it does not pretend that the disk is healthy.
System lamp
Steady blue means every check passed. Blinking blue means the system is starting or stopping. Red means a failing disk, a hot CPU, a stopped fan or a failed system service. The CPU temperature and the fan speed come from the SCH5127.
USB lamp
This lamp tells the story of a copy:
- Steady: a device is connected.
- Slow blink: a copy is running.
- Three quick pulses and a pause, for one minute: the copy finished, every file was checked, and the device is unmounted. You can pull it out.
- Fast blink, for one minute: the copy did not finish.
The pattern comes from one small function. The lamp has a single blue LED, so the meaning is in the rhythm:
def usb_signal(snapshot, now):
if not snapshot["usb_connected"]:
return False
step = int(now / TICK)
if snapshot.get("usb_backup") == "copying":
return int(now * 2) % 2 == 0
last = snapshot.get("usb_last")
if last == "done":
return step % 10 in (0, 2, 4)
if last == "error":
return step % 2 == 0
return TrueTICK is 0.2 seconds. Out of every ten steps, "done" is on in steps 0, 2 and 4, so you see quick pulses and then a pause of about one second. "Error" flips every step, which is a fast blink.
The lamp reads the result from a small file, /var/lib/h340-usb-backup/last-run.json, which the copy service writes after it unmounts the device. A lamp is only a view of that file. It does not decide anything.
The USB flash backup
With the button working, I could build the part I wanted most: plug in a USB disk, press the button, and the files go to the NAS. This is the h340-usb-backup service. It is plain Python and uses only the standard library.
The rules
- The button is the only trigger. Plugging in a device never starts a copy. A key press is only a request, and the service still checks everything.
- The source is read-only. The device is mounted with
ro,nosuid,nodev,noexec. Nothing on it is ever deleted or changed. - Only the front port counts. A disk on any other port is ignored.
- Each run is new. Every copy goes to its own folder. Older copies are never touched and nothing is overwritten.
- Each file is checked. A file gets its final name only after it was read back and compared.
- Space comes first. The copy is refused if it would leave too little free space.
- No result without proof. A run is "ok" only when every regular file was copied and checked.
Step 1: wait for the button
The service reads the key press straight from the input device that the kernel module created. Each record is a Linux input_event. The service looks for KEY_COPY (code 133) with value 1:
KEY_COPY = 133
EVENT = struct.Struct("llHHi")
def parse_events(data):
"""Yield True for each KEY_COPY press in a buffer of input_event records."""
for offset in range(0, len(data) - EVENT.size + 1, EVENT.size):
_, _, kind, code, value = EVENT.unpack_from(data, offset)
if kind == EV_KEY and code == KEY_COPY and value == 1:
yield TrueThe service finds that device by name in /sys/class/input. If the module is not loaded yet, the service does not exit. It waits and looks again every five seconds. So a late module load, or a kernel without the module, never leaves the unit in a failed state.
While one copy runs, a second press is ignored:
def press(self):
if not self.busy.acquire(blocking=False):
LOG.info("Press ignored: a copy is already running")
return None
try:
return self._copy_once()
finally:
self.busy.release()Step 2: find the front USB disk
The service does not guess. It resolves each block device in /sys/class/block to its real place in the PCI tree and matches that path. On the H340 the front port is port 5 on the USB 2.0 controller at 00:1d.7:
FRONT_ROUTE = re.compile(r"/0000:00:1d\.7/usb\d+/\d+-5/\d+-5:1\.0/host\d+/")
def find_front_device(root=Path("/sys/class/block")):
disks = []
for block in root.iterdir():
if (block / "partition").exists():
continue
try:
actual = str(block.resolve(strict=True))
except FileNotFoundError:
continue
if FRONT_ROUTE.search(actual):
disks.append(block)
if len(disks) != 1:
raise Refused("Expected exactly one front USB disk, found %d" % len(disks))
...If there are zero disks, or two, the service refuses. If the disk has more than one partition, it also refuses, because it cannot know which one you mean.
Step 3: mount it read-only
MOUNT_OPTIONS = "ro,nosuid,nodev,noexec"
def mount_readonly(device, target):
Path(target).mkdir(parents=True, exist_ok=True)
if is_mounted(target):
raise Refused("Mount point already in use")
result = subprocess.run(["/usr/bin/mount", "-o", MOUNT_OPTIONS, device, target],
capture_output=True, text=True, timeout=60, check=False)
if result.returncode:
raise Refused("Mount failed: " + result.stderr.strip()[:200])Because the mount is read-only, a bug in my code cannot write to your flash disk through the file system. The options noexec and nodev also protect the NAS from anything odd on the disk.
Step 4: scan and skip
The service walks the tree and builds a list of regular files. It does not follow symbolic links. Links and special files are listed as "skipped", and they never count as copied. Names you chose to exclude are counted apart, so they never make a run look incomplete:
def is_excluded(name, patterns):
"""Match one path component against user patterns, ignoring case."""
name = name.casefold()
return any(fnmatch.fnmatchcase(name, pattern.casefold()) for pattern in patterns)The default patterns skip System Volume Information, $RECYCLE.BIN, lost+found and .Trash-*.
Step 5: check the space
Before it writes anything, the service adds up the size of all files and compares the total with the free space on the destination:
if total + reserve > free_space():
result = {"ok": False, "error": "Not enough free space", ...}
status.write("failed", error=result["error"])
return resultreserve is a setting. The example file keeps 5 GiB free, so a backup cannot fill the disk that the rest of the NAS uses.
Step 6: copy and verify every file
Each run gets a new folder named from the UTC time and your label, for example 20240712T142530Z-usb. The mkdir() call fails if the folder already exists, so a run can never merge into an older one.
Then each file goes through copy_one. This is the heart of the service:
def copy_one(source_file, target, stop=None):
before = os.stat(source_file)
partial = target.with_name(target.name + ".part")
target.parent.mkdir(parents=True, exist_ok=True)
try:
digest = hashlib.sha256()
# 'xb' refuses an existing partial name instead of replacing it.
with open(source_file, "rb") as src, open(partial, "xb") as dst:
while True:
chunk = src.read(CHUNK)
if not chunk:
break
digest.update(chunk)
dst.write(chunk)
dst.flush()
os.fsync(dst.fileno())
if file_digest(partial, stop) != digest.hexdigest():
raise OSError("Verification failed")
after = os.stat(source_file)
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError("Source changed during copy")
os.utime(partial, ns=(before.st_atime_ns, before.st_mtime_ns))
if os.path.lexists(target):
raise FileExistsError(str(target))
os.rename(partial, target)
except BaseException:
try:
os.unlink(partial)
except OSError:
pass
raiseHere is what happens, in order:
- The file is written to a name that ends in
.part. The modexbfails if that name exists, so nothing is replaced. - While it copies, the service computes the SHA-256 of the data it read from the source.
- It calls
fsync, so the data is handed to the disk and not only kept in the cache. - It reads the
.partfile back from the destination and computes the SHA-256 again. The two values must match. - It checks that the source file did not change in the meantime.
- It sets the original modification time on the copy.
- Only then does it rename
.partto the final name. A rename on one file system replaces the name in one atomic step (rename(2) (opens in a new tab)), so you never see a half-written file under its real name.
If anything fails, the .part file is removed. A crash or a pulled power cord can leave a .part file. It never leaves a file that looks complete and is not.
Step 7: unmount and record the result
When the copy ends, the runner unmounts the flash disk and then writes the result to /var/lib/h340-usb-backup/last-run.json. The order matters. The lamp shows "safe to remove" only after the unmount worked:
if mounted:
try:
self.umount(self.mount_point)
except OSError as exc:
result = {"ok": False, "error": str(exc), "skipped": []}
self.status.write("failed", error=str(exc))
try:
self.history(self.history_path, result)If the unmount fails, the run counts as failed, even when every file was copied. The lamp then blinks fast. I prefer a false alarm over telling you to pull a disk that is still mounted.
While the copy runs, the service also writes a small status file, /run/h340-usb-backup/state.json, every two seconds. It holds the number of files copied and the total. The lamp service and the OpenMediaVault status page read it. If the file gets old, they treat the copy as dead and do not show "copying" forever.
The settings file
One small JSON file, /etc/h340-usb-backup.json, controls all of this. The OpenMediaVault plugin writes it for you. Without OpenMediaVault, you write it by hand:
{
"destination_root": "/srv/backups/h340-usb",
"reserve_bytes": 5368709120,
"label": "usb",
"exclude": [
"System Volume Information",
"$RECYCLE.BIN",
"lost+found",
".Trash-*"
]
}The systemd unit starts only if this file exists, so a fresh install does nothing until you set a destination:
[Unit]
Description=Acer H340 USB Backup button copy runner
After=local-fs.target systemd-modules-load.service
ConditionPathExists=/etc/h340-usb-backup.json
[Service]
Type=simple
ExecStart=/usr/bin/python3 -B /usr/lib/h340-usb-backup/h340_usb_runner.py --config /etc/h340-usb-backup.json
User=root
RuntimeDirectory=h340-usb-backup
StateDirectory=h340-usb-backup
TimeoutStopSec=120
Restart=noThe value TimeoutStopSec=120 gives a running copy time to end in a clean way when you stop the service.
Speed
A big copy of many small files from an NTFS disk is slow on this CPU. A common NTFS driver, NTFS-3G (opens in a new tab), runs in user space, and the Atom has one core. I found that ext4 on the NAS disks is much better. If your flash disks are NTFS, expect low speed. It still works. It only takes longer.
OpenMediaVault integration
The plugin adds a menu, Services > H340 USB Backup, with four pages:
- Backup: the shared folder for copies, a sub-folder, the free space to keep, a label and the names to skip.
- LEDs: the lamp service on or off, and a button that forgets disks that were removed.
- Power button: shut down, sleep or nothing.
- Status: the state of both services, what each bay holds, the power button and the last copy.
The plugin follows the layout of the official OpenMediaVault plugins: a data model in the configuration database, an RPC service, a Salt state that writes the config files, and Workbench pages in YAML.
One lesson from packaging: I first shipped the copy service inside the plugin. A user asked me, and I asked myself, what happens on a plain Debian system without OpenMediaVault. So I split it. There are now four packages:
| Package | What it does |
|---|---|
acer-h340-usb-backup-dkms | The kernel module for the button |
h340-leds | The lamp service |
h340-usb-backup | The copy service |
openmediavault-h340 | The settings pages |
The first three work on any systemd system. Only the settings pages need OpenMediaVault.
How to use it
On Debian or Ubuntu, build the packages with Python 3 and install them with apt, not dpkg -i:
python3 tools/build_plugin.py
sudo apt install ./dist/acer-h340-usb-backup-dkms_*.deb ./dist/h340-leds_*.deb ./dist/h340-usb-backup_*.debAdd ./dist/openmediavault-h340_*.deb if you run OpenMediaVault. The install guide (opens in a new tab) has the two small settings files and the power button setting for systems without OpenMediaVault.
Why open source
I built this for myself. The box works now, and it will keep working for me. But I know the H340 is old, many people have one, and most of them hit the same wall when they leave Windows Home Server. If you are one of them, I hope this saves you the weeks I spent.
Bug reports are welcome, and so are reports from other H340 owners. If your board differs from mine, tell me what you see before you try anything.
Read more
- Acer-h340-linux on GitHub (opens in a new tab), the code of this project, with the install guide
- mediasmartserverd (opens in a new tab), the project that mapped the lamps of this family of boxes
- Windows Home Server on Wikipedia (opens in a new tab), the end of support in January 2013
- dme1737, the kernel hwmon driver (opens in a new tab), the chips it supports, with the SCH5127
- logind.conf, HandlePowerKey (opens in a new tab), the values and the default
- OpenMediaVault, Power Management (opens in a new tab), the power button section
- The Salt state of OpenMediaVault for the power button (opens in a new tab), where
nothingbecomesignore - actypes.h (opens in a new tab), the ACPI notify values in the Linux kernel, with the device-specific range
- evgpeinit.c (opens in a new tab), how the kernel names the methods of general purpose events (
_Lxxand_Exx) - input-event-codes.h (opens in a new tab), the numbers of the key codes, including
KEY_COPY - The Linux input subsystem (opens in a new tab), the
input_eventrecord and/dev/input - DKMS on the Debian wiki (opens in a new tab), how out-of-tree kernel modules are built for each kernel
- port(4) man page (opens in a new tab), the
/dev/portdevice - rename(2) man page (opens in a new tab), the atomic replace of a name
- NTFS-3G (opens in a new tab), the user-space NTFS driver
Was this post helpful?