output
stringlengths 9
26.3k
| input
stringlengths 26
29.8k
| instruction
stringlengths 14
159
|
---|---|---|
From this link, I see that, these values can be edited.
ip_forward=no
ipv6_forward=no
spoofprotect=yes
syncookies=noThe above variables can now be set in /etc/sysctl.conf which is acceseble via the System configuration menu, System variables.
From this answer, I see changing net.ipv4.icmp_echo_ignore_broadcasts is not going to change anything.
For timestamp, I believe you refer to the system variable net.ipv4.tcp_timestamps. As per this link, it is suggested to leave it turned on unless if you live on an extremely slow connection such as a 56 kbps modem connection to the internet.
|
Can I change the value of those parameters (spoofprotect, syncookies, dynaddr_hack, notimestamps, nobroadcasticmpecho, ip_forward) from sysctl.conf file in systemd?
| Change network values from sysctl.conf |
The sysctl --system load settings from all configuration files.
The sysctl -p will load settings from the default /etc/sysctl.conf.
man sysctl:
-p[FILE], --load[=FILE]
Load in sysctl settings from the file specified or /etc/sysctl.conf if none given. Specifying - as filename means
reading data from standard input. Using this option will mean arguments to sysctl are files, which are read in the
order they are specified. The file argument may be specified as regular expression. --system
Load settings from all system configuration files. Files are read from directories in the following list in given
order from top to bottom. Once a file of a given filename is loaded, any file of the same name in subsequent direc‐
tories is ignored.
/etc/sysctl.d/*.conf
/run/sysctl.d/*.conf
/usr/local/lib/sysctl.d/*.conf
/usr/lib/sysctl.d/*.conf
/lib/sysctl.d/*.conf
/etc/sysctl.conf |
I see on the web two different commands to load sysctl custom parameters:sysctl --system
sysctl -pIs there any difference between the two commands? I know the second one I posted can take the path of a file to load but without any file specified, everything will be loaded.
| Difference between sysctl options to set system parameters |
What is the difference between procfs
and sysfs?proc is the old one, it is more or less without rules and structure. And at some point it was decided that proc was a little too chaotic and a new way was needed.
Then sysfs was created, and the new stuff that was added was put into sysfs like device information.
So in some sense they do the same, but sysfs is a little bit more structured.Why are they made as file systems?UNIX philosophy tells us that everything is a "file", therefore it was created so it behaves as files. As I understand it, proc is just
something to store the immediate info
regarding the processes running in the
system.Those parts has always been there and they will probably never move into sysfs.
But there is more old stuff that you can find in proc, that has not been moved.
|
What is the difference between procfs and sysfs? Why are they made as file systems? As I understand it, proc is just something to store the immediate info regarding the processes running in the system.
| What is the difference between procfs and sysfs? |
The files in /dev are actual devices files which UDEV creates at run time. The directory /sys/class is exported by the kernel at run time, exposing the hierarchy of the hardware through sysfs.
From the libudev and Sysfs Tutorial
excerptOn Unix and Unix-like systems, hardware devices are accessed through special files (also called device files or nodes) located in the /dev directory. These files are read from and written to just like normal files, but instead of writing and reading data on a disk, they communicate directly with a kernel driver which then communicates with the hardware. There are many online resources describing /dev files in more detail. Traditonally, these special files were created at install time by the distribution, using the mknod command. In recent years, Linux systems began using udev to manage these /dev files at runtime. For example, udev will create nodes when devices are detected and delete them when devices are removed (including hotplug devices at runtime). This way, the /dev directory contains (for the most part) only entries for devices which actually exist on the system at the current time, as opposed to devices which could exist.another excerptThe directories in Sysfs contain the heirarchy of devices, as they are attached to the computer. For example, on my computer, the hidraw0 device is located under:
/sys/devices/pci0000:00/0000:00:12.2/usb1/1-5/1-5.4/1-5.4:1.0/0003:04D8:003F.0001/hidraw/hidraw0Based on the path, the device is attached to (roughly, starting from the end) configuration 1 (:1.0) of the device attached to port number 4 of device 1-5, connected to USB controller 1 (usb1), connected to the PCI bus. While interesting, this directory path doesn't do us very much good, since it's dependent on how the hardware is physically connected to the computer.
Fortunately, Sysfs also provides a large number of symlinks, for easy access to devices without having to know which PCI and USB ports they are connected to. In /sys/class there is a directory for each different class of device.Usage?
In general you use rules in /etc/udev/rules.d to augment your system. Rules can be constructed to run scripts when various hardware is present.
Once a system is up you can write scripts to work against either /dev or /sys, and it really comes down to personal preferences, but I would usually try and work against /sys and make use of tools such as udevadm to query UDEV for locations of various system resources.
$ udevadm info -a -p $(udevadm info -q path -n /dev/sda) | head -15Udevadm info starts with the device specified by the devpath and then
walks up the chain of parent devices. It prints for every device
found, all possible attributes in the udev rules key format.
A rule to match, can be composed by the attributes of the device
and the attributes from one single parent device. looking at device '/devices/pci0000:00/0000:00:1f.2/ata1/host0/target0:0:0/0:0:0:0/block/sda':
KERNEL=="sda"
SUBSYSTEM=="block"
DRIVER==""
ATTR{ro}=="0"
ATTR{size}=="976773168"
ATTR{stat}==" 6951659 2950164 183733008 41904530 16928577 18806302 597365181 580435555 0 138442293 622621324"
ATTR{range}=="16"
... |
What is the difference between the device representation in /dev and the one in /sys/class?
Is one preferred over the other? Is there something one offers and the other doesn't?
| Difference between /dev and /sys/class? |
Based on memdump program originally found here I've created a script to selectively read specified applications back into memory. remember:
#!/bin/bash
declare -A Q
for i in "$@"; do
E=$(readlink /proc/$i/exe);
if [ -z "$E" ]; then
#echo skipped $i;
continue;
fi
if echo $E | grep -qF memdump; then
#echo skipped $i >&2;
continue;
fi
if [ -n "${Q[${E}]}" ]; then
#echo already $i >&2;
continue;
fi
echo "$i $E" >&2
memdump $i 2> /dev/null
Q[$E]=$i
done | pv -c -i 2 > /dev/nullUsage: something like
# ./remember $(< /mnt/cgroup/tasks )
1 /sbin/init
882 /bin/bash
1301 /usr/bin/hexchat
...
2.21GiB 0:00:02 [ 1.1GiB/s] [ <=> ]
...
6838 /sbin/agetty
11.6GiB 0:00:10 [1.16GiB/s] [ <=> ]
...
23.7GiB 0:00:38 [ 637MiB/s] [ <=> ]
# It quickly skips over non-swapped memory (gigabytes per second) and slows down when swap is needed.
|
The Linux kernel swaps out most pages from memory when I run an application that uses most of the 16GB of physical memory. After the application finishes, every action (typing commands, switching workspaces, opening a new web page, etc.) takes very long to complete because the relevant pages first need to be read back in from swap.
Is there a way to tell the Linux kernel to copy pages from swap back into physical memory without manually touching (and waiting for) each application? I run lots of applications so the wait is always painful.
I often use swapoff -a && swapon -a to make the system responsive again, but this clears the pages from swap, so they need to be written again the next time I run the script.
Is there a kernel interface, perhaps using sysfs, to instruct the kernel to read all pages from swap?
Edit: I am indeed looking for a way to make all of swap swapcached. (Thanks derobert!)
[P.S.
serverfault.com/questions/153946/… and serverfault.com/questions/100448/… are related topics but do not address the question of how to get the Linux kernel to copy pages from swap back into memory without clearing swap.]
| Making Linux read swap back into memory |
This information can be retrieved from the iSerial entry of the verbose output of the lsusb. Easiest is to pass the output to the the less viewer and search manually with /, or for example with grep:
$ lsusb -v 2>/dev/null | grep '^Bus\|iSerial'Bus 001 Device 029: ID 12d1:1506 Huawei Technologies Co., Ltd. Modem/Networkcard
iSerial 0
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
iSerial 1 0000:00:1d.7
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
iSerial 1 0000:00:1d.3
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
iSerial 1 0000:00:1d.2
... |
I have a nearly common Linux machine here. So, it has a PCI (*-X, etc) bus, on that some USB controllers, and I have USB devices on these USB controllers. Similar to this:
$ lspci|grep USB
00:12.0 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB OHCI0 Controller
00:12.2 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB EHCI Controller
00:13.0 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB OHCI0 Controller
00:13.2 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB EHCI Controller
00:14.5 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB OHCI2 Controller
00:16.0 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB OHCI0 Controller
00:16.2 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB EHCI Controller
02:00.0 USB controller: VIA Technologies, Inc. VL805 USB 3.0 Host Controller (rev 01)And, there is also an usb device tree, as this:
$ lsusb -t
/: Bus 07.Port 1: Dev 1, Class=root_hub, Driver=ohci-pci/4p, 12M
/: Bus 06.Port 1: Dev 1, Class=root_hub, Driver=ohci-pci/2p, 12M
/: Bus 05.Port 1: Dev 1, Class=root_hub, Driver=ohci-pci/5p, 12M
|__ Port 5: Dev 4, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M
/: Bus 04.Port 1: Dev 1, Class=root_hub, Driver=ohci-pci/5p, 12M
|__ Port 2: Dev 2, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M
|__ Port 2: Dev 2, If 1, Class=Human Interface Device, Driver=usbhid, 1.5M
|__ Port 3: Dev 12, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M
|__ Port 4: Dev 4, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M
|__ Port 4: Dev 4, If 1, Class=Human Interface Device, Driver=usbhid, 1.5M
/: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/4p, 480M
/: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/5p, 480M
|__ Port 2: Dev 2, If 0, Class=Hub, Driver=hub/4p, 480M
|__ Port 1: Dev 4, If 0, Class=Wireless, Driver=btusb, 12M
|__ Port 1: Dev 4, If 1, Class=Wireless, Driver=btusb, 12M
|__ Port 4: Dev 11, If 0, Class=Vendor Specific Class, Driver=r8712u, 480M
|__ Port 3: Dev 3, If 0, Class=Vendor Specific Class, Driver=MOSCHIP usb-ethernet driver, 480M
/: Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/5p, 480M
|__ Port 1: Dev 6, If 0, Class=Video, Driver=uvcvideo, 480M
|__ Port 1: Dev 6, If 1, Class=Video, Driver=uvcvideo, 480M
|__ Port 1: Dev 6, If 2, Class=Audio, Driver=snd-usb-audio, 480M
|__ Port 1: Dev 6, If 3, Class=Audio, Driver=snd-usb-audio, 480MSo, I see my USB controllers on the PCI bus, and also my USB devices on the USB controllers.
But I don't know, which USB controller number (on the USB bus) belongs to which PCI bus number!
How to find that?
| How to find the pci slot of an usb controller in Linux? |
ioctl tends to go hand-in-hand with a /dev entry; your typical code would do
fd=open("/dev/mydevice",O_RDRW);
ioctl(fd,.....);This is perfectly standard Unix behaviour. Inside the kernel driver you can put access controls (eg only root can do some things, or require a specific capability for more fine grained access) which makes it pretty flexible and powerful.
Of course this means that devices can expose a lot more than use block/character read-write activity; many things can be done via ioctl calls. Not so easy to use from shell scripts, but pretty easy from C or perl or python or similar.
sysfs entries are another way of interacting with drivers. Typically each type of command would have a different entry, so it can be complicated to write the driver but it makes it very easy to access via userspace; simple shell scripts can manipulate lots of stuff, but may not be very efficient
netlink is primarily focused (I think!) on network data transfers, but it could be used for other stuff. It's really good for larger volumes of data transfer and is meant to be a successor to ioctl in some cases.
All the options are good; your use case may better determine which type of interface to expose from your driver.
|
I'm trying to clarify which is the most useful (in terms of functionality) method of interacting with devices in Linux. As I understand, device files expose only part of functionality (address blocks in block devices, streams in character devices, etc...). ioctl(2) seems to be most commonly used, yet some people says it's not safe, and so on.
Some good articles or other relevant pointers would be welcome.
| Usage difference between device files, ioctl, sysfs, netlink |
Read this blog post: Solving problems with proc
There are a few tips what you can do with the proc filesystem. Among other things, there is a tip how to get back a deleted disk image or how to staying ahead of the OOM killer.
Don't forget to read the comments, there are good tips, too.
| I'd like to know more about the advanced uses of the /proc and /sys virtual filesystems, but I don't know where to begin. Can anyone suggest any good sources to learn from? Also, since I think sys has regular additions, what's the best way to keep my knowledge current when a new kernel is released.
| How do I learn what I can do with /proc and /sys [closed] |
Rsync has code which specifically checks if a file is truncated during read and gives this error — ENODATA. I don't know why the files in /sys have this behavior, but since they're not real files, I guess it's not too surprising. There doesn't seem to be a way to tell rsync to skip this particular check.
I think you're probably better off not rsyncing /sys and using specific scripts to cherry-pick out the particular information you want (like the network card address).
|
I have a bash script which uses rsync to backup files in Archlinux. I noticed that rsync failed to copy a file from /sys, while cp worked just fine:
# rsync /sys/class/net/enp3s1/address /tmp
rsync: read errors mapping "/sys/class/net/enp3s1/address": No data available (61)
rsync: read errors mapping "/sys/class/net/enp3s1/address": No data available (61)
ERROR: address failed verification -- update discarded.
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1052) [sender=3.0.9]# cp /sys/class/net/enp3s1/address /tmp ## this worksI wonder why does rsync fail, and is it possible to copy the file with it?
| Why does rsync fail to copy files from /sys in Linux? |
This is essentially a matter of checking a whole bag of corner cases.A drive can appear in /proc/mounts
A drive can be used as swap (use /proc/swaps)
A drive can be part of an active LVM pv (use pvdisplay)
A drive can be part of a dm-mapper RAID group (use /proc/mdstat)
A drive can be directly accessed by an application (e.g. Oracle supports writing directly to a drive or partition instead of a filesystem) (use fuser)
A drive can be directly accessed by a virtual machine (use fuser)
A drive can be referenced by a loopback device (e.g: mount /dev/sda -o offset=1M /foo) (use losetup -a)These are just the examples I came up with given a minute and a half to think about it. I'm sure there's a dozen others.
This last example I think is the most interesting and few people know about it. It allows you to mount a filesystem without using partitions. Just specify the starting offset and Linux will transparently create a loopback device. The example above yields the following:
# cat /proc/mounts
...
/dev/loop0 /foo ext4 relatime,data=ordered 0 0# losetup -a
/dev/loop0 [0005]:2048 (/dev/sda), offset 1048576Why would you do that? Typically it involves situations where things have previously gone horribly wrong.
Also bear in mind that with the namespacing feature now in mainline (see unshare), different processes can have different views about what's mounted and what isn't. Here things start to get a little bit red-pill.
|
I want to know what the easiest way is to determine (without root privilege) whether a block device (say sdb) or any part of it is mounted (and which part of it).
Checking /proc/mounts for sdb is not enough because sdb or one of its partitions may be used by LVM. You can check /sys/block/sdb/sdb*/holders/ but you get dm-x entries which have to be resolved to /dev/mapper names in order to check /proc/mounts. Possible but if there is an easier solution... (which should not require root privilege)
| How to find out easily whether a block device (or a part of it) is mounted somehow |
/etc/resolv.conf is copied in order not to lose the DNSs.
/lib/modules is copied because because it may be necessary to use some hardware component that need not be present at the time of setting up the chroot. You must remember that the original question you refer to in your OP concerns the replacement of a NAS OS with Arch Linux. You will thus need drivers for ethernet, possibly wireless, various USB components, and so on. Copying the /lib/modules folder ensures that the new environment will be able to cope with its future tasks.
You are indeed right about re-mounting vs. bind-mounting. The Arch Linux Wiki page on chroot does use re-mounting and bind-mounting as you specify, as per the answer to the post you refer to:
cd /mnt/arch
mount -t proc proc proc/
mount -t sysfs sys sys/
mount -o bind /dev dev/
mount -t devpts pts dev/pts/(I think this shows the syntax of your lines, copied from this post, is wrong: the dev to be mounted precedes the mount point).
However, the Ubuntu man page on chroot tells a different story:
sudo mount -o bind /proc /var/chroot/procHere /proc is bind-mounted, not re-mounted.
I have actually tried both things, and after a brief test run, I have been unable to notie any difference. Not much of a test, admittedly, and I will thus rest my case here that it should not make much of a difference.
|
This answer to another question basically boils down to chrooting into another Linux distribution in order to mainly use that as a replacement to its too restricted (but irreplaceable) parent. The suggested actions before running chroot, which I would like to understand better, are:
cp /etc/resolv.conf etc/resolv.conf
cp -a /lib/modules/$(uname -r) lib/modules
mount -t proc archproc proc
mount -t sysfs archsys sys
mount -o bind /dev dev
mount -t devpts archdevpts dev/ptsCopying resolv.conf is clear (network/internet access), while I'm not sure about the modules - this actually seemed unnecessary when chrooting into a stage3 Gentoo system, right?
But why are proc, sys and dev/pts remounted instead of using bind-mounted? What is the actual difference in this situation, which is "more correct"?
This HowTo bind-mounts proc and dev, but neither dev/pts nor sys are mounted at all. Additionally it copies /etc/{hosts,fstab} over to the new root. Does that make sense? Shouldn't I include /etc/mdadm.conf then as well? | Which of proc, sys etc. should be bind-mounted (or not) when chrooting into a "replacement" distribution? |
Here are some links regarding securityfs:A post from the author of securityfs
Article about PipeFS, SockFS, DebugFS, and SecurityFS.The author stats:This filesystem is meant to be used by security modules, some of which
were otherwise creating their own filesystems.So I guess the name comes from the Linux Security Modules (LSM).
|
While I am studying, I saw security file system which is mounted on /sys/kernel/security . It seems like to operate similar to sysfs or proc file system. Security file system keeps data on memory not in disk, so when write something into the file in securityfs it does not actually write to disk just update data in memory.
What I am wondering is why the name of this file system is securityfs?
Is there any security enhance ability in this file system?
| What is securityfs? |
The sysfs file system, typically mounted on /sys, just like the /proc file system, isn’t a typical file system, it’s a so called pseudo file system. It’s actually populated by the kernel and you can’t delete files directly.
So, if the ASUS laptop support isn’t appropriate for you, then you have to ask the kernel to remove it. To do so, remove the corresponding module:
sudo rmmod asus-laptopThat will remove the relevant /sys entry.
|
I ran some commands without completely understanding them while trying to get screen brightness working and now I'm stuck with a nasty symlink in '/sys/class/backlight/asus_laptop' that I am trying to get rid of.
I have tried
sudo rm /sys/class/backlight/asus_laptop
sudo rm '/sys/class/backlight/asus_laptop'su root
rm /sys/class/backlight/asus_laptop
sudo rm /sys/class/backlight/asus_laptopGoing right into directory and typing rm asus_laptop, changing ownership and using Thunar to try to remove it.
I get
rm: cannot remove '/sys/class/backlight/asus_laptop': Operation not permittedSame goes for unlink, rmdir doesn't work, and Thunar fails.
The permissions on it are lrwxrwxrwx
How can I remove it?
| Debian: cannot remove symlink in /sys/: operation not permitted |
/sys
/sys is sysfs, an entirely virtual view into kernel structures in memory that reflects the current system kernel and hardware configuration, and does not consume any real disk space. New files and directories cannot be written to it in the normal fashion.
Applying disk space monitoring to it does not produce useful information and is a waste of effort. It may have mount points for other RAM-based virtual filesystems inside, including...
/sys/kernel/debug
/sys/kernel/debug is the standard mount point for debugfs, which is an optional virtual filesystem for various kernel debugging and tracing features.
Because it's for debugging features, it is supposed to be unnecessary for production use (although you might choose to use some of the features for enhanced system statistics or similar).
Since using the features offered by debugfs will in most cases require being root anyway, and its primary purpose is to be an easy way for kernel developers to provide debug information, it may be a bit "rough around the edges".
When the kernel was loaded, the initialization routine for the kernel tracing subsystem registered /sys/kernel/debug/tracing as a debugfs access point for itself, deferring any further initialization until it's actually accessed for the first time (minimizing the resource usage of the tracing subsystem in case it turns out it's not needed). When you cd'd into the directory, this deferred initialization was triggered and the tracing subsystem readied itself for use. In effect, the original /sys/kernel/debug/tracing was initially a mirage with no substance, and it only became "real" when (and because) you accessed it with your cd command.
debugfs does not use any real disk space at all: all the information contained within it will vanish when the kernel is shut down.
/sys/fs/cgroup
/sys/fs/cgroup is a tmpfs-type RAM-based filesystem, used to group various running processes into control groups. It does not use real disk space at all. But if this filesystem is getting nearly full for some reason, it might be more serious than just running out of disk space: it might mean that
a) you're running out of free RAM,
b) some root-owned process is writing garbage to /sys/fs/cgroup, or
c) something is causing a truly absurd number of control groups to be created, possibly in the style of a classic "fork bomb" but with systemd-based services or similar.
Bottom line
A disk usage probe should have /sys excluded because nothing under /sys is stored on any disk whatsoever.
If you need to monitor /sys/fs/cgroup, you should provide a dedicated probe for it that will provide more meaningful alerts than a generic disk space probe.
|
I've faced a really strange issue today, and am totally helpless about it.
Some of the servers I manage are monitored with Nagios. Recently I saw a disk usage probe failing with this error:DISK CRITICAL - /sys/kernel/debug/tracing is not accessible: Permission denied I wanted to investigate and my first try was to check this directory permissions, and compare these with another server (who's working well). Here are the commands I ran on the working server and you'll see that as soon as I cd into the directory, its permissions are changed:
# Here we've got 555 for /sys/kernel/debug/tracing
root@vps690079:/home/admin# cd /sys/kernel/debug
root@vps690079:/sys/kernel/debug# ll
total 0
drwx------ 30 root root 0 Jul 19 13:13 ./
drwxr-xr-x 13 root root 0 Jul 19 13:13 ../
…
dr-xr-xr-x 3 root root 0 Jul 19 13:13 tracing/
drwxr-xr-x 6 root root 0 Jul 19 13:13 usb/
drwxr-xr-x 2 root root 0 Jul 19 13:13 virtio-ports/
-r--r--r-- 1 root root 0 Jul 19 13:13 wakeup_sources
drwxr-xr-x 2 root root 0 Jul 19 13:13 x86/
drwxr-xr-x 2 root root 0 Jul 19 13:13 zswap/# I cd into the folder, and it (./) becomes 700!!
root@vps690079:/sys/kernel/debug# cd tracing/
root@vps690079:/sys/kernel/debug/tracing# ll
total 0
drwx------ 8 root root 0 Jul 19 13:13 ./
drwx------ 30 root root 0 Jul 19 13:13 ../
-r--r--r-- 1 root root 0 Jul 19 13:13 available_events
-r--r--r-- 1 root root 0 Jul 19 13:13 available_filter_functions
-r--r--r-- 1 root root 0 Jul 19 13:13 available_tracers
…# Next commands are just a dumb test to double-check what I'm seeing
root@vps690079:/sys/kernel/debug/tracing# cd ..
root@vps690079:/sys/kernel/debug# ll
total 0
drwx------ 30 root root 0 Jul 19 13:13 ./
drwxr-xr-x 13 root root 0 Sep 27 10:57 ../
…
drwx------ 8 root root 0 Jul 19 13:13 tracing/
drwxr-xr-x 6 root root 0 Jul 19 13:13 usb/
drwxr-xr-x 2 root root 0 Jul 19 13:13 virtio-ports/
-r--r--r-- 1 root root 0 Jul 19 13:13 wakeup_sources
drwxr-xr-x 2 root root 0 Jul 19 13:13 x86/
drwxr-xr-x 2 root root 0 Jul 19 13:13 zswap/Have you got any idea what could causes this behavior?
Side note, using chmod to re-etablish permissions does not seems to fix the probe.
| "cd" into /sys/kernel/debug/tracing causes permission change |
Compression algorithms are declared in lib/decompress.c. Gzip is defined in lib/decompress_inflate.c and doesn't get any special status; it'll only be there if CONFIG_DECOMPRESS_GZIP is y when the kernel is compiled.
The list of available compression algorithms is the compressed_formats structure. Since it's defined as static, it isn't available in other source files. The only function that uses it is thus the decompress_method function in lib/decompress.c itself. So the only way to get a kernel to use the table of supported algorithms is to attempt to decompress something that starts with the appropriate two-byte magic sequence, and see if that function returns the algorithm name.
You can tell which decompression functions are supported by searching the list of kernel symbols (/proc/kallsyms). The functions aren't identified as such, so you'll need to bake in the list of symbol names.
</proc/kallsyms cut -d " " -f 3 |
grep -xF -e gunzip -e bzip2 -e unlzma -e unxz -e unlzo -e unlz4 |
If /proc/config.gz is unavailable, how do I know what decompression algorithms the running kernel is capable of using on a compressed cpio initramfs?
Is the gzip algorithm always available, even when CONFIG_DECOMPRESS_GZIP is not y when building the kernel?
| How do I know what decompression algorithms are compiled-in into the linux kernel? |
This is Answer
cat /sys/block/sda/sizeAbove file will returns some number like 312581808, then this number need to multiply by 512 standard block size then u ll get long int value in bytes, then u can convert to GB.
|
How can I get hard disk capacity, usage, etc. using the /proc or /sys filesystems?
If it is possible, please tell me which file(s) I need to process to get that information.
| How to get hard disk information from /proc and/or /sys |
You need to add mount --make-rslave /mnt/"$i" after your first mount command, to set the correct propagation flags for those mount points.
They protect the host from changes made inside the chroot environment, and help prevent blocking situations like yours.
|
Background: I am exploring how to copy an ordinary LVM-on-LUKS Debian 9 ("Stretch") installation from a thumb drive (the "source drive") onto a ZFS-formatted drive (the "target drive") in order to achieve a ZFS-on-LUKS installation. My process is based on this HOWTO.* I think the ZFS aspect is irrelevant to the issue I would like help with, but I am mentioning it just in case it matters.
As part of my process, while Stretch is running from the source drive, I mount the target ZFS root (/) filesystem at /mnt. I then recursively bind:/dev to /mnt/dev
/proc to /mnt/proc
/sys to /mnt/sys.I then chroot into /mnt.
(In the future, when I am chrooted into /mnt, I intend to run update-initramfs, update-grub, etc, to configure the contents of the /boot partition.)
I then exit the chroot, and my trouble begins. I find that I can unmount /mnt/dev and /mnt/proc, but not /mnt/sys. The latter refuses to unmount because it contains /mnt/sys/fs/cgroup/systemd, which the system for some reason thinks is "in use". Reformatting the ZFS drive and rebooting fixes the problem, but hugely slows the iterations of my learning and documentation process.
My questions are:
- How can I unmount /mnt/sys after the chroot, without rebooting?
- Is the failure (umount: /mnt/sys/fs/cgroup/systemd: target is busy) expected? If not, against which piece of software should I file a bug report: umount, cgroups, systemd, the Linux kernel, or something else?
Here is (I think) a minimal working example. (If you are having difficulty reproducing this and think I might have missed out a step, let me know.) First, the boilerplate:
# Activate the ZFS kernel module
/sbin/modprobe zfs# Set variables
BOOT_POOL=bpool
ROOT_POOL=rpool
DIRS_TO_COPY=(boot bin etc home lib lib64 opt root sbin srv usr var)
FILES_TO_COPY=(initrd.img initrd.img.old vmlinuz vmlinuz.old)
VIRTUAL_FILESYSTEM_DIRS=(dev proc sys)## Partition target drive
# 1MB BIOS boot partition
sgdisk -a2048 -n1:2048:4095 -t1:EF02 $1 -c 1:"bios_boot_partition"
wait
# 510MB partition for /boot ZFS filesystem
sgdisk -a2048 -n2:4096:1052671 -t2:BF07 $1 -c 2:"zfs_boot_partition"
wait
# Remaining drive space, except the last 510MiB in case of future need:
# partition to hold the LUKS container and the root ZFS filesystem
sgdisk -a2048 -n3:1052672:-510M -t3:8300 $1 -c 3:"luks_zfs_root_partition"
wait# Before proceeding, ensure /dev/disk/by-id/ knows of these new partitions
partprobe
wait# Create the /boot pool
zpool create -o ashift=12 \
-O atime=off \
-O canmount=off \
-O compression=lz4 \
-O normalization=formD \
-O mountpoint=/boot \
-R /mnt \
$BOOT_POOL "$1"-part2
wait# Create the LUKS container for the root pool
cryptsetup luksFormat "$1"-part3 \
--hash sha512 \
--cipher aes-xts-plain64 \
--key-size 512
wait# Open LUKS container that will contain the root pool
cryptsetup luksOpen "$1"-part3 "$DRIVE_SHORTNAME"3_crypt
wait# Create the root pool
zpool create -o ashift=12 \
-O atime=off \
-O canmount=off \
-O compression=lz4 \
-O normalization=formD \
-O mountpoint=/ \
-R /mnt \
$ROOT_POOL /dev/mapper/"$DRIVE_SHORTNAME"3_crypt
wait# Create ZFS datasets for the root ("/") and /boot filesystems
zfs create -o canmount=noauto -o mountpoint=/ "$ROOT_POOL"/debian
zfs create -o canmount=noauto -o mountpoint=/boot "$BOOT_POOL"/debian# Mount the root ("/") and /boot ZFS datasets
zfs mount "$ROOT_POOL"/debian
zfs mount "$BOOT_POOL"/debian# Create datasets for subdirectories
zfs create -o setuid=off "$ROOT_POOL"/home
zfs create -o mountpoint=/root "$ROOT_POOL"/home/root
zfs create -o canmount=off -o setuid=off -o exec=off "$ROOT_POOL"/var
zfs create -o com.sun:auto-snapshot=false "$ROOT_POOL"/var/cache
zfs create "$ROOT_POOL"/var/log
zfs create "$ROOT_POOL"/var/mail
zfs create "$ROOT_POOL"/var/spool
zfs create -o com.sun:auto-snapshot=false -o exec=on "$ROOT_POOL"/var/tmp
zfs create "$ROOT_POOL"/srv
zfs create -o com.sun:auto-snapshot=false -o exec=on "$ROOT_POOL"/tmp# Set the `bootfs` property. ***TODO: IS THIS CORRECT???***
zpool set bootfs="$ROOT_POOL"/debian "$ROOT_POOL"# Set correct permission for tmp directories
chmod 1777 /mnt/tmp
chmod 1777 /mnt/var/tmpAnd here's the core part of the issue:
# Copy Debian install from source drive to target drive
for i in "${DIRS_TO_COPY[@]}"; do
rsync --archive --quiet --delete /"$i"/ /mnt/"$i"
done
for i in "${FILES_TO_COPY[@]}"; do
cp -a /"$i" /mnt/
done
for i in "${VIRTUAL_FILESYSTEM_DIRS[@]}"; do
# Make mountpoints for virtual filesystems on target drive
mkdir /mnt/"$i"
# Recursively bind the virtual filesystems from source environment to the
# target. N.B. This is using `--rbind`, not `--bind`.
mount --rbind /"$i" /mnt/"$i"
done# `chroot` into the target environment
chroot /mnt /bin/bash --login# (Manually exit from the chroot)# Delete copied files
for i in "${DIRS_TO_COPY[@]}" "${FILES_TO_COPY[@]}"; do
rm -r /mnt/"$i"
done# Remove recursively bound virtual filesystems from target
for i in "${VIRTUAL_FILESYSTEM_DIRS[@]}"; do
# First unmount them
umount --recursive --verbose --force /mnt/"$i" || sleep 0
wait
# Then delete their mountpoints
rmdir /mnt/"$i"
wait
doneAt this last step, I get:
umount: /mnt/sys/fs/cgroup/systemd: target is busy
(In some cases useful info about processes that
use the device is found by lsof(8) or fuser(1).)In case it helps: findmnt shows the full sys tree mounted twice: once at /sys and identically at /mnt/sys.
* Debian Jessie Root on ZFS, CC BY-SA 3.0, by Richard Laager and George Melikov.
| unmount sys/fs/cgroup/systemd after chroot, without rebooting |
I solved the problem by adding cameron to the gpio group:
sudo usermod -aG gpio cameron
gpio export 18 out
echo 1 > /sys/class/gpio/gpio18/valueNow everything works.
|
This is on a Raspberry Pi.
Here's the output of sudo ls -lL /sys/class/gpio/gpio18:
-rwxrwx--- 1 root gpio 4096 Mar 8 10:50 active_low
-rwxrwx--- 1 root gpio 4096 Mar 8 10:52 direction
-rwxrwx--- 1 cameron cameron 4096 Mar 8 10:50 edge
drwxrwx--- 2 root gpio 0 Mar 8 10:50 power
drwxrwx--- 2 root gpio 0 Mar 8 10:50 subsystem
-rwxrwx--- 1 root gpio 4096 Mar 8 10:50 uevent
-rwxrwx--- 1 cameron cameron 4096 Mar 8 10:50 valueSo looks like I should now have access to value, great. However:
cameron@raspberrypi~ $ echo 1 > /sys/class/gpio/gpio18/value
-bash: /sys/class/gpio/gpio18/value: Permission deniedWhat's going on? If I chmod 777 everything, then it works, but I shouldn't have to do that when I own the file.
| Unable to write to a GPIO pin despite file permissions on /sys/class/gpio/gpio18/value |
It's the device link in class directories that you aren't supposed to use. The idea is that /sys/class/net/eth0 is a symbolic link to somewhere under /sys/devices, and the device link merely links to a (grand-)*parent directory; instead of using the device link, you're supposed to walk back to a parent directory if needed.
Accessing files in /sys/class/net/eth0/ is fine.
If you're referring to the operational status found in /sys/class/net/eth0/operstate, there are a few more. The names are defined in net/core/net-sysfs.c and the constants in include/uapi/linux/if.h. They come from RFC 2863.
|
I'm creating a script for polling information about network interfaces. For this I get some data from /sysfs.
Everything went fine until I wanted to clarify all possible states of an interface (Which are they btw? I'm aware for now only about up, down and unknown). I went through /usr/src/linux/Documentation/sysfs-rules.txt and found this:Accessing /sys/class/net/eth0/device is a bug in the applicationIs there a reason for this?
Could someone explain me if I'm doing something wrong by getting information from /sysfs?
I don't iterate through all interfaces in /sysfs but get all network interfaces with getifaddrs(3). Perhaps there is another method to get iface status?
Thanks.
| Getting information from sysfs |
Linux has an abstraction that lets Host Controller Drivers share code. As a comment in drivers/usb/core/hcd.c says:
* USB Host Controller Driver framework
*
* Plugs into usbcore (usb_bus) and lets HCDs share code, minimizing
* HCD-specific behaviors/bugs.
*
* This does error checks, tracks devices and urbs, and delegates to a
* "hc_driver" only for code (and data) that really needs to know about
* hardware differences. That includes root hub registers, i/o queues,
* and so on ... but as little else as possible.
*
* Shared code includes most of the "root hub" code (these are emulated,
* though each HC's hardware works differently) and PCI glue, plus request
* tracking overhead. The HCD code should only block on spinlocks or on
* hardware handshaking; blocking on software events (such as other kernel
* threads releasing resources, or completing actions) is all generic.
*
* Happens the USB 2.0 spec says this would be invisible inside the "USBD",
* and includes mostly a "HCDI" (HCD Interface) along with some APIs used
* only by the hub driver ... and that neither should be seen or used by
* usb client device drivers.
*USB device address 1 is assigned to the root hub in register_root_hub(), as commented right above this function:
* register_root_hub - called by usb_add_hcd() to register a root hub
* @hcd: host controller for this root hub
*
* This function registers the root hub with the USB subsystem. It sets up
* the device properly in the device tree and then calls usb_new_device()
* to register the usb device. It also assigns the root hub's USB address
* (always 1).This is corroborated by usb.ids database that says that for vendor Id 1d6b the product Ids 1,2,3 correspond to 1.1, 2.0, 3.0 root hub, respectively.
What we have in the Linux device tree at this device is a kind of mixture of the USB host controller (a real device) and the USB root hub (also a real device), abstracted by the USB HCD framework discussed above.
Now, some modern systems with xHCI have also EHCI controllers that have Intel Corp. Integrated Rate Matching Hub always attached. These are not the root hubs, they have address 2, not 1. From an Intel manual, chapter 5.19.1:
The Hubs convert low and full-speed traffic into high-speed traffic. |
On any PC where USB host controller is connected to the PCI/PCIE bus I see the following:
$ cat /sys/bus/usb/devices/usb1/{idVendor,idProduct,manufacturer,product,serial}
1d6b
0002
Linux 4.14.157-amd64-x32 ehci_hcd
EHCI Host Controller
0000:00:1a.0I.e. the EHCI host controller, which in this example has the PCI device position 0000:00:1a.0, is represented with a bogus set of string descriptors and vendor/product identifiers. Looking up the vendor id 1d6b in usb.ids I find that it corresponds to Linux Foundation. (lsusb lists it as "Linux Foundation 2.0 root hub".) But the PCI device referenced by the serial is real and has the following properties:
$ cat /sys/bus/pci/devices/0000:00:1a.0/{vendor,device}
0x8086
0x8c2dLooking these ids up in pci.ids we can find that it's Intel 8 Series/C220 Series Chipset Family USB EHCI (the same as lspci would say). A real piece of hardware from a real HW manufacturer.
So why does Linux represent this Intel hardware with some strange set of ids? I do realize that PCI and USB vendor/product ids may collide, so it wouldn't be possible to start the USB device tree with ids from PCI namespace. But why the string descriptors?
My guess is that this is because the whole USB entity named "*HCI Host Controller" is a fictitious one. But on the other hand, it appears to have an address (always =1), which is never assigned to a newly-connected device on this bus. So it looks like there might be something real about this USB entity. But this reserved address might also be just a way of bookkeeping.
Is my guess correct? Is the host controller—as a USB entity—entirely fictitious? Does it never appear as an actual addressable device on the wire? Or is there something real to it, something we could actually send standard USB requests to, and not have their processing simply emulated by the kernel?
| Why does Linux list USB Host Controller' vendor as "Linux Foundation"? |
Use either of these instead:
grep -rn /sys/class/tty/* -e 0x40010000 2> /dev/nullgrep -Rn /sys/class/tty/ -e 0x40010000 2> /dev/nullThe glob in the first command is needed in order to have it follow the symlinks that aren't specified on the command line as the contents of /sys/class/tty are all symlinks to the contents of /sys/devices/virtual/tty and /sys/devices/platform/serial####/tty.
The -R in the second command follows the symlinks by default with no glob being needed.
I added 2> /dev/null to send the Input/output error and Permission denied messages to /dev/null as the output is easier to read when all of that isn't returned.
|
I want to search for a string inside the /sys/class/tty/* directories. So I tried with:
# grep -rn path -e patternbut it returns nothing. Example:
# cat /sys/class/tty/ttySTM0/iomem_base
0x40010000# ls -l /sys/class/tty/ttySTM0/iomem_base
-r--r----- 1 root root 4096 Jan 17 10:37 /sys/class/tty/ttySTM0/iomem_base# grep -rn /sys/class/tty/ -e 0x40010000
#If I use the same syntax inside another directory it seems to work:
# grep -rn /opt -e Could
# /opt/logs/joku1_log.txt:29:Could not read interface wlan0 flags: No such deviceIs there some caveats for such a research?
My goal is to find which tty has a specific iomem_base address.
| Grep inside /sys file returns nothing |
I had the same problem, and I found that you have to set $LIMIT to 0 to remove that limit:
echo "$MAJOR:$MINOR 0" > blkio.throttle.write_bps_deviceThis removes the entry from the cgroup. If you then cat blkio.throttle.write_bps_device, you will not see the entry any more.
|
Values of a specific parameter (for example, blkio.throttle.write_bps_device) for all devices are stored in a single file. echo "$MAJOR:$MINOR $LIMIT" > blkio.throttle.write_bps_device inserts/updates a value to $LIMIT. It does not clear the file, as you might think. So I see no way to delete a value. Also this configuration interface seems to violate the rule "one item per file."
| How to delete a device parameter for a cgroup? |
Answering so I can close this question full credit to @ridgy and @dirkt for their help. With the command:
udevadm info -n video0 -q pathOr similarly with ls -l /sys/class/video4linux/, a path of the form /devices/pci0000:00/0000:00:10.0/usb7/7-2/7-2:1.0/video4linux/video0 can be found. That in combination with the listing of the video devices using either ls /dev/video* or v4l2-ctl --list-devices allows a map between the usb port and video device to be created.
|
I am using a library (librealsense) that only outputs the bus and port number as such (9.1). It uses libusb internally. The issue is from this identifier in libusb I want to know what physical device it belongs to in /dev/video0. For instance, 9.1 -> /dev/video0 and 7.2 -> /dev/video2 when two cameras are plugged in in ports 9.1 and 7.2.
Is this possible? How do I acquire what devices paths belong to a bus and port? Any partial answer would be helpful.
| How to map /sys/bus/usb/devices to /dev/video*? |
The /sys directory is generally where the sysfs filestystem is mounted, which contains information about devices and other kernel information.
The files in /sys/block contain information about block devices on your system. Your local system has a block device named sda, so /sys/block/sda exists. Your Amazon instance has a device named xvda, so /sys/block/xvda exists.
The /sys/block/<dev>/stat file provides several statistics about the state of block device <dev>. It consists of a single line of text containing 15 decimal values separated by whitespace:
Name units description
---- ----- -----------
read I/Os requests number of read I/Os processed
read merges requests number of read I/Os merged with in-queue I/O
read sectors sectors number of sectors read
read ticks milliseconds total wait time for read requests
write I/Os requests number of write I/Os processed
write merges requests number of write I/Os merged with in-queue I/O
write sectors sectors number of sectors written
write ticks milliseconds total wait time for write requests
in_flight requests number of I/Os currently in flight
io_ticks milliseconds total time this block device has been active
time_in_queue milliseconds total wait time for all requests
discard I/Os requests number of discard I/Os processed
discard merges requests number of discard I/Os merged with in-queue I/O
discard sectors sectors number of sectors discarded
discard ticks milliseconds total wait time for discard requestsSo, each block device will have its own statistics file, hence the different values.
See kernel docs for more details.
|
On my local machine, I have /sys/block/sda1/stat.
On an Amazon machine, I have /sys/block/xvda1/stat.
When I run cat /sys/block/sda1/stat or cat /sys/block/xvda1/stat both give 11 fields of output.
What is the difference between /sys/block/sda1/stat and /sys/block/xvda1/stat files?
| What is the difference between /sys/block/sda1/stat and /sys/block/xvda1/stat? |
Each loaded module has an entry in /sys/module. But there are also kernel components with an entry in /sys/module that are not loaded as modules. Each kernel component¹ that can be built as a module has an entry in /sys/module, whether it is compiled and loaded as a module or compiled as part of the main kernel image.
lsmod gets the list of loaded modules from /proc/modules.
I think that only loaded modules have an initstate file in their /sys/module directory, so you can use that too.
¹ That's each component of the loaded kernel. The kernel doesn't know or care what modules you may have in files on your hard disk. The kernel doesn't care what modules were built at the same time of the kernel image, either; it may show that via /proc/config but it doesn't use that information for anything.
|
I'm wondering if I can use the directory listing of /sys/module instead of lsmod to get a list of currently loaded modules.
Is that the list of loaded modules only? Or maybe that combined with /sys/module/*/initstate?
| Are Modules listed under /sys/module all the Loaded Modules? |
The generic way to do this for any kind of file systems is bind mount.
This example is using /tmp. To do that on /sys you may replace /tmp/sysall by /sys:
mkdir /tmp/sysall
mkdir -p /tmp/mychroot/sys/class/gpiomount -t sysfs sysfs /tmp/sysall/
mount --bind /tmp/sysall/class/gpio /tmp/mychroot/sys/class/gpio
umount /tmp/sysall/ |
I wonder if it is possible to mount only part of sysfs for usage in chroot. Example I would require only /sys/class/gpio and rest is not required.
mount -t sysfs sys/some/folder /mnt/temp_sys | Mounting only a specific part of sysfs |
It is not related to any bootloader at all.
When a driver uses the kernel's common firmware loading infrastructure to load a firmware file, the kernel can either load the file directly from the standard /lib/firmware directory tree, or it can optionally start an user-space process to handle the firmware load.
This user-space process used to be part of the hotplug subsystem, then a part of udev, but I think it's currently deprecated and the in-kernel version is the primary means of loading firmware for any drivers.
If the entire firmware load operation takes more than the number of seconds specified in /sys/class/firmware/timeout, the operation will be considered failed. As a result, the driver that requested the firmware will most likely fail too.
More details can be found in the Documentation/firmware_class directory of the Linux kernel source code package.
|
I found a file /sys/class/firmware/timeout, and this file contains just one word 60. Is this timeout related to bootloader like GRUB timeout? What is the practical use of it?
| What is firmware timeout? |
I found an answer: sudo udevadm trigger
Source: http://ptspts.blogspot.com/2009/09/how-to-refresh-devdisk-on-linux.html
Update #1: It appears the sudo may be unnecessary. So: udevadm trigger
Update #2: It appears that sudo is necessary to propagate a changed Btrfs filesystem label. (While this is not the question I originally asked, I figure it is worth mentioning here.) So, if udevadm trigger changes nothing, then it may worth trying sudo udevadm trigger.
|
On Linux, the command lsblk -o partlabel will display the partlabel for block devices.
I have used gdisk to change a partlabel.
After the change, lsblk is still reporting the old value of the partlabel.
(Aside: The paths /dev/disk/by-partlabel/* are also still using the old partlabel values.)
Is there some way to refresh the cache so that lsblk will report the new value of the partlabel?
I'm not sure exactly where the cache is. It may be udev, sysfs, or somewhere else.
By contrast, blkid correctly reports the new partlabel. However, I'm hoping I can avoid switching to blkid (for various reasons).
(Aside: A reboot will probably update the partlabel values. But I'd prefer to avoid rebooting, if possible.)
| How to update/refresh changed partlabels as reported by lsblk? |
The files red, green, and blue are char devices that allow ASCII decimal values to be written to them.
For example, to change the device to bright red, one would do the following*:
#!/bin/bashecho 9 >red
echo 0 >green
echo 0 >blue* note that this must be run as root
|
I have one of these:Basically, it's a USB device with three LEDs (red, green, and blue).
The Linux kernel has supported this device through the usbled module for quite some time now. However, I am not sure how to actually control the device from a Bash script. The /sys directory contains the following files:
root@desktop:/sys/devices/pci0000:00/0000:00:13.0/usb5/5-3/5-3:1.0# ls
bAlternateSetting bInterfaceSubClass ep_81 red
bInterfaceClass blue green subsystem
bInterfaceNumber bNumEndpoints modalias supports_autosuspend
bInterfaceProtocol driver power uevent | Using Bash to write to a device in /sys? |
Unless I get a better answer, I'm going to take this as my solution. It's very indirect but appears to work. Basically, I judged from the fact that udevd was able to make the path in /dev/disk/by-path, it must be in sysfs because to my knowledge that's all udev really does: Takes sysfs information and performs configured actions utilizing it.
After rummaging around it looks like those links get created by the contents of the ID_PATH variable which is set by way of the /lib/udev/id_path bash script. Inside that I found a case statement that basically lays out how it determines transport by checking for the existence of various directories directly underneath the sysfs entry for the given block device's source controller:
*/rport-[0-9]*:[0-9]*-[0-9]*/*)
handle_fc "$D"
;;
*/end_device-[0-9]*:[0-9]*:[0-9]*/*)
handle_sas "$D"
;;
*/fw-host[0-9]*/*)
handle_firewire "$D"
;;
*/session[0-9]*/*)
handle_iscsi "$D"
D=
;;
*/host[0-9]*/[0-9]*:[0-9]*:[0-9]*:[0-9]*)
handle_scsi "$D"
;;
*/usb[0-9]*/[0-9]*/*)
handle_usb "$D"
;;
*/pci[0-9]*:[0-9]*)
handle_pci "$D"
;;
*/serio[0-9]*)
handle_serio "$D"
;;
*/platform/*)
handle_platform "$D"
;;
*/devices)
D=
;;I tested this out on the command line by replicating the Fibre Channel test and got positive results:
## INTERNAL DRIVE:
[root@localhost sde]# ls -ld /sys/block/sda/device/../../../rport* 2>/dev/null | wc -l
0## FIBRE CHANNEL BLOCK DEVICE:
[root@localhost sde]# ls -ld /sys/block/sde/device/../../../rport* 2>/dev/null | wc -l
4Basically, I take the short name of the device (sda, sdb, sde, etc), enter the physical device, then .. until I'm up at the block device's source controller. If the controller's sysfs entry has rport* directories as immediate children, then that means the block device is coming in via fibre channel.
This only replicates the check for the first switch case (*/rport-[0-9]*:[0-9]*-[0-9]*/*)) for iscsi, I was also able to replicate the success by looking for "session[0-9]" directories on the controller:
[root@files2 ~]# ls -ld /sys/block/sda/device/../../../session[0-9]
drwxr-xr-x. 6 root root 0 Oct 15 13:50 /sys/block/sda/device/../../../session1
[root@files2 ~]#My script is going to be written in Python but it looks like checking for these directories is sufficient. I'm going to go ahead and mark this as my solution (once it lets me anyways).
|
I'm writing a script, and I'm interested in being able to identify the transport class (fc - "fibre channel", scsi, iscsi, etc.) for a given block device. I can retrieve this information via ls -l /dev/disk/by-path on RHEL, but I'd rather query sysfs if that's at all possible (for a variety of reasons, including portability). For example:
[root@localhost sde]# ls -l /dev/disk/by-path
total 0
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:01:00.0-scsi-0:2:0:0 -> ../../sda
lrwxrwxrwx 1 root root 10 Jul 21 16:39 pci-0000:01:00.0-scsi-0:2:0:0-part1 -> ../../sda1
lrwxrwxrwx 1 root root 10 Jul 21 16:39 pci-0000:01:00.0-scsi-0:2:0:0-part2 -> ../../sda2
lrwxrwxrwx 1 root root 10 Jul 21 16:39 pci-0000:01:00.0-scsi-0:2:0:0-part3 -> ../../sda3
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:01:00.0-scsi-0:2:1:0 -> ../../sdb
lrwxrwxrwx 1 root root 10 Jul 21 16:39 pci-0000:01:00.0-scsi-0:2:1:0-part1 -> ../../sdb1
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:01:00.0-scsi-0:2:2:0 -> ../../sdc
lrwxrwxrwx 1 root root 10 Jul 21 16:39 pci-0000:01:00.0-scsi-0:2:2:0-part1 -> ../../sdc1
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:1a:00.0-fc-0x500601663ee0025f:0x0000000000000000 -> ../../sdd
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:1a:00.0-fc-0x500601663ee0025f:0x0015000000000000 -> ../../sde
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:1a:00.0-fc-0x5006016e3ee0025f:0x0000000000000000 -> ../../sdf
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:1a:00.0-fc-0x5006016e3ee0025f:0x0015000000000000 -> ../../sdg
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:1a:00.1-fc-0x500601653ee0025f:0x0000000000000000 -> ../../sdj
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:1a:00.1-fc-0x500601653ee0025f:0x0015000000000000 -> ../../sdk
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:1a:00.1-fc-0x5006016d3ee0025f:0x0000000000000000 -> ../../sdh
lrwxrwxrwx 1 root root 9 Jul 21 16:39 pci-0000:1a:00.1-fc-0x5006016d3ee0025f:0x0015000000000000 -> ../../sdiBut looking in /sys/block/sde I don't see anything particularly useful:
[root@localhost sde]# ls -l /sys/block/sde
total 0
-r--r--r-- 1 root root 4096 Oct 14 16:51 dev
lrwxrwxrwx 1 root root 0 Oct 14 16:51 device -> ../../devices/pci0000:00/0000:00:07.0/0000:1a:00.0/host5/rport-5:0-2/target5:0:0/5:0:0:21
drwxr-xr-x 2 root root 0 Jul 21 12:39 holders
drwxr-xr-x 3 root root 0 Jul 21 12:39 queue
-r--r--r-- 1 root root 4096 Oct 14 16:51 range
-r--r--r-- 1 root root 4096 Oct 14 16:51 removable
-r--r--r-- 1 root root 4096 Oct 14 16:51 size
drwxr-xr-x 2 root root 0 Jul 21 12:39 slaves
-r--r--r-- 1 root root 4096 Oct 14 16:51 stat
lrwxrwxrwx 1 root root 0 Oct 14 16:51 subsystem -> ../../block
--w------- 1 root root 4096 Oct 14 16:51 ueventAny help is appreciated, even if it just pushes me in the right direction. My ideal solution is to use only sysfs data.
| Can you identify transport via sysfs? |
1) What handles /sys/class/gpio ? A kernel module ? a driver ?It's a kernel interface similar to the /proc directory.2) is it possible to have more complicated module parameters in a kernel module, with some directory structure ? Like a 'delays' directory containing the params for delaysYes; some things in /proc and /sys do use directory hierarchies. If you want to modify or expand them, though, you have to modify the kernel.
#3 has a similar answer -- to make changes you need to change the relevant kernel code.4) How does the gpio thing creates new/deletes files in /sys/class/gpio when you write to [un]export ?These are not files on disk, they're just system interfaces.1 When you go to read data from a procfs or sysfs file, what you are really doing is making a request for information from the kernel. The data is then formatted and returned. It probably isn't stored anywhere in the form you see it, although parts of it may be stored in the kernel.
When you write to such a file -- not all of them allow this -- you're sending a request to the kernel to do something specific. This can include, e.g., activating or expanding the GPIO interface.1. read and write calls are always system calls anyway, since normal files are normally on disk, and the kernel is needed to access hardware. Hence using a filesystem style API here is natural; even if they are not "real files", accessing whatever resource they represent must involve system calls.
|
I was making (my first) kernel module to play with the gpio pins of my pandaboard and interrupts.
Already "built-in", I noticed you can do (briefly)
cd /sys/class/gpio
echo 138 > export # a file gpio138 appears
echo out > gpio138/direction
echo 1 > gpio138/valueto turn some voltage high or low on connector pins.
Similarly on a kernel module you have module parameters and you can do echo 3 > /sys/module/my_module/parameters/delay_seconds for instance
My questions :What handles /sys/class/gpio ? A kernel module ? a driver ?
Whatever 1. is, is it possible to have more complicated module parameters in a kernel module, with some directory structure ? Like a 'delays' directory containing the params for delays, ... /sys/module/my_module/parameters/delays/delay_led1_seconds
Can you have the parameters somewhere else than in the path /sys/module/my_module/parameters/... ? (/sys/class/a_name/... for instance)
How does the gpio thing creates new/deletes files in /sys/class/gpio when you write to [un]export ? | Kernel module parameters vs /sys/class/... explanation |
Is is as simple as comparing /proc/filesystems with lsmod?No:
$ comm -31 <(lsmod | awk 'NR!=1 {print $1}' |sort) \
<(</proc/filesystems awk '{print $NF}' |sort) | fmt
anon_inodefs autofs bdev cgroup cpuset debugfs devpts devtmpfs ext2 ext3
fuseblk fusectl hugetlbfs mqueue nfs4 pipefs proc pstore ramfs rootfs
rpc_pipefs securityfs sockfs sysfs tmpfsMany of these are not built into the kernel on that system. autofs is provided by a modules called autofs4 while nfs4 is provided by a module called nfs. The ext4 module provides ext2 and ext3 as well as ext4; fuse provides both fuseblk and fusectl. rpc_pipefs (not to be confused with pipefs) is provided by sunrpc.
Yet your system is able to load a module for a filesystem on demand: when you run mount -t foo …, if foo isn't a supported filesystem type, Linux attempts to load a module that provides this filesystem. The way this works is that the kernel detects that foo isn't a supported filesystem, and it calls modprobe to load a module called fs-foo. The mechanism is similar to pci:… aliases to load the driver for a PCI hardware peripheral by its PCI ID and usb:… which is similar to USB —see How to assign USB driver to device and Debian does not detect serial PCI card after reboot for more explanations. The fs-… module aliases are recorded in /lib/$(uname -r)/modules.alias. This file is generated when you build the kernel.
Under normal conditions, you can use this to determine which filesystems are provided by modules. By elimintation, the filesystems that are not provided by modules are built into the kernel. There are rare edge cases where this approach wouldn't work, for example if you've modified or erased your modules.alias file, or if a filesystem is provided both by a module and in a compiled-in form. I don't know of a way to cope with these cases short of writing some kernel code and loading it as a module.
for fs in $(</proc/filesystems awk '{print "fs-" $NF}' |sort); do
/sbin/modprobe -n $fs 2>/dev/null || echo "$fs is built in"
done |
On a running linux system, what is a portable (among linux distributions) way to find out what filesystems the current kernel has compiled-in (not through modules) support for?
Consider for example my current Ubuntu x86_64 kernel: 3.11.0-24-generic #41-Ubuntu. It has for instance no /proc/config.gz, which would be my first thought otherwise.
The reason I'm interested is that I'd like to (programmatically) build a rescue environment with the current kernel and an initial ramdisk that the kernel will be able to load/mount.
Is is as simple as comparing /proc/filesystems with lsmod?
If so: Do the modules always have the exact same name (first column from lsmod output) as the filesystem name (last column in /proc/filesystems)?
Is there perhaps a more modern way such as /sys instead of /proc to look for info?
My current approach is as follows. Can someone confirm that it is correct, or advise how to do it instead?:
for fscand in $(awk '{print $NF}' /proc/filesystems)
do
if test $(lsmod | grep -c -e '^'${fscand}'[^a-z0-9_-]') -eq 0
then
candlist="${fscand} ${candlist}"
fi
donefor fscand in $candlist
do
echo $fscand is compiled-in
done | How do I find out what filesystem drivers are compiled-in into the linux kernel? |
# strace hdparm -i /dev/sda
…
ioctl(3, HDIO_GET_IDENTITY, 0x7fffa930c320) = 0
brk(0) = 0x1c42000
brk(0x1c63000) = 0x1c63000
write(1, "\n", 1
) = 1
write(1, " Model=…So hdparm gets its information from the HDIO_GET_IDENTITY ioctl, not from sysfs. That doesn't mean that the information can't be accessed from sysfs, of course.
Next we can look up HDIO_GET_IDENTITY in the kernel source. LXR is convenient for that. The relevant hit shows a call to ata_get_identity. This function looks up the model in the device description at the offset ATA_ID_PROD in the device description.
Looking at where else ATA_ID_PROD is used, and with sysfs in mind, we find a hit in ide-sysfs.c, in a function called model_show. This function is referenced by the macro call just below DEVICE_ATTR_RO(model), so if the ata driver is exposing the IDE interface, there's a file called model in the device's sysfs directory that contains this information.
If the ata driver is exposing the SCSI interface, tracing the kernel source is a lot more complicated, because the code uses different ways of extracting the information from the hardware. But as it turns out there is also a model field in the device's sysfs directory.
As for where the device's sysfs directory is, there are several ways to access it. The sysfs.txt file in the kernel documentation documents this, not very well. The simplest way to access it is via /sys/block which contains an entry for each block device:
$ cat /sys/block/sda/device/modelThere are a lot of symbolic links in /sys. The “physical” location of that directory depends on how the disk is connected to the system; for example it has the form /sys/devices/pci…/…/ata…/host…/target…/… for an ATA device with a SCSI interface that's connected to a PCI bus.
|
[gala@arch ~]$ sudo !!
sudo hdparm -i /dev/sda/dev/sda: Model=KINGSTON SHFS37A120G, FwRev=603ABBF0, SerialNo=50026B725B0A1515
Config={ HardSect NotMFM HdSw>15uSec Fixed DTR>10Mbs RotSpdTol>.5% }
RawCHS=16383/16/63, TrkSize=0, SectSize=0, ECCbytes=4
BuffType=unknown, BuffSize=unknown, MaxMultSect=1, MultSect=1
CurCHS=16383/16/63, CurSects=16514064, LBA=yes, LBAsects=234441648
IORDY=on/off, tPIO={min:120,w/IORDY:120}, tDMA={min:120,rec:120}
PIO modes: pio0 pio1 pio2 pio3 pio4
DMA modes: mdma0 mdma1 mdma2
UDMA modes: udma0 udma1 udma2 udma3 udma4 udma5 *udma6
AdvancedPM=yes: unknown setting WriteCache=enabled
Drive conforms to: unknown: ATA/ATAPI-2,3,4,5,6,7 * signifies the current active modeWhere does hdparm read the Model field from? Somewhere from sysfs ? Where from?
| Get block device model name and manufacturer from pseudo-fs |
A CPU is “possible” if there's room for it in the kernel memory. The number of possible CPU is the maximum number of CPU that can be brought online, including ones that are hotplugged after boot.
The documentation of this part of sysfs is in How CPU topology info is exported via sysfs:possible: CPUs that have been allocated resources and can be brought online if they are present. [cpu_possible_mask]But the more detailed documentation of cpu_possible_mask is in CPU hotplug in the Kernel:Bitmap of possible CPUs that can ever be available in the system. This is used to allocate some boot time memory for per_cpu variables that aren’t designed to grow/shrink as CPUs are made available or removed. Once set during boot time discovery phase, the map is static, i.e no bits are added or removed anytime. Trimming it accurately for your system needs upfront can save some boot time memory.This parameter can be configured through command line options. In the likely case that your hardware doesn't support plugging in another CPU without rebooting and you don't intend to hibernate your system and make it wake up with more CPUs, you can save a small amount of kernel memory by passing possible_cpus=16 on the kernel command line. On a typical PC or server, the amount is probably too small for it to be worth the effort.
In the absence of command line options, I think you need to read the source to figure out what's going on. If the kernel is compiled without CPU hotplug support (CONFIG_HOTPLUG_CPU), it just looks how many CPU are present at boot time. If the kernel has CPU hotplug support, according to a comment for prefill_possible_map in the source code:If the BIOS specified disabled CPUs in ACPI/mptables use that.
The user can overwrite it with possible_cpus=NUM
Otherwise don't reserve additional CPUs.I haven't verified that this is what the code does.
Note that the principle of what “possible CPUs” means applies to all architectures, but the ways to determine the number of CPUs are architecture-specific. In my answer I assume x86.
|
I have an AMD CPU with 8 cores and 2 threads per core. Linux (correctly) shows this as 16 "cpus". However, sysfs actually shows 32 "possible" cpus, with 16 of them not present and offline:
$ cat /sys/devices/system/cpu/possible
0-31$ cat /sys/devices/system/cpu/present
0-15$ cat /sys/devices/system/cpu/online
0-15$ cat /sys/devices/system/cpu/offline
16-31To be clear, there's nothing wrong here; there are indeed 16 logical CPUs present and online. What I'm not clear on is why Linux detects an addition 16 logical CPUs that are not present but possible.
I think these are the relevant kernel docs: https://www.kernel.org/doc/html/latest/core-api/cpu_hotplug.html. But I don't see any indication of how the number of possible CPUs is chosen. (Note that it's much lower than the kernel_max number of CPUs, which is 8191 on my system.)
(A little additional background: I have some code that needs to parse these values. Doing the right thing seems straightforward, but I'd like to have a clear docstring explaining why the number of possible CPUs can exceed the number of present CPUs on an ordinary desktop computer.)
| How does Linux detect number of "possible" CPUs |
The size entry returns the nr_sects field of the block device structure. Traditionally, in Unix disk size contexts, “sector” or “block” means 512 bytes, regardless of what the manufacturer of the underlying hardware might call a “sector” or “block”. I can't find authoritative documentation, but looking at the Linux source code (e.g. 1) 2) it looks like the nr_sects field is indeed expressed in units of 512 bytes.
You can approach it another way: since there is no file reporting the unit, it has to be a constant unit, otherwise applications wouldn't know what the value means. (The queue subdirectory is not necessarily present, it depends on the block device.)
|
Is the file located under:
/sys/block/<xxx>/sizeConstantly referencing to 512 byte block count, or is there any special cases where the block count changes?
I'm curious because:
thinkpad :: /sys/block/sdf % cat queue/physical_block_size
4096
thinkpad :: /sys/block/sdf % cat queue/logical_block_size
4096
thinkpad :: /sys/block/sdf % cat size
1540864015408640 * 512 bytes / 1000000000 = ~8GB -> the size of my device, its correct but the device is a 4K block device.
| sysfs block size count |
The /sys (sysfs) filesystem is somewhat special; many operations are not possible, for example creating or removing a file. Changing the permissions and ownership of a file or setting an ACL is permitted; that allows the system administrator to allow certain users or groups to access certain kernel entry points.
There is no special case that restricts a file that's initially read-only for everyone from being changed to being writable for some. That's what Vim does when it is thwarted in its initial attempt to save.
The permissions are the only thing that prevent the file from being written. Thus, if they're changed, the file content changes, which for a module parameter changes the parameter value inside the module.
Normally this doesn't have any security implication since only root can change the permissions on the file and root can change the value through /dev/kmem or by loading another module. It's something to keep in mind if root is restricted from loading modules or accessing physical memory directly by a security framework such as SELinux; the security framework needs to be configured to forbid problematic permission changes under /sys. If a user is given ownership of the file, they'll be able to change the permissions; to avoid this, if a specific user needs to have permission to read a parameter, don't chown the file to that user, but set an ACL (setfacl -m u:alice:r /sys/…).
|
I wrote the following simple linux kernel module to test the param feature:
#include<linux/module.h>int a = 5;
module_param(a, int, S_IRUGO);int f1(void){ printk(KERN_ALERT "hello world\n");
printk(KERN_ALERT " value passed: %d \n", a);
return 0;
}void f2(void){ printk(KERN_ALERT "value of parameter a now is: %d \n", a);
printk(KERN_ALERT "bye bye qworld\n");}module_init(f1);
module_exit(f2);MODULE_AUTHOR("l");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("experimanting with parameters");Now when I try to echo a value to it, I get the "Permission Desnied" error, as expected:
[root@localhost param]# insmod p.ko
[root@localhost param]# dmesg -c
[ 7247.734491] hello world
[ 7247.734498] value passed: 5
[root@localhost param]# echo 32 >/sys/module/
Display all 145 possibilities? (y or n)
[root@localhost param]# echo 32 >/sys/module/p/parameters/a
bash: /sys/module/p/parameters/a: Permission deniedSo far so good.
However, I can write to the file a using vim.
It does try to warn me with the follwing messages at the status line:
"/sys/module/p/parameters/a"
"/sys/module/p/parameters/a" E667: Fsync failed
WARNING: Original file may be lost or damaged
don't quit the editor until the file is successfully written!
Press ENTER or type command to continueBut I force the write with ! and get out of vim, and to my surprise the value of the parameter is re-written!
[root@localhost param]# vim /sys/module/p/parameters/a
[root@localhost param]# cat /sys/module/p/parameters/a
32(Oriuginal value was 5 and I wrote 32 using vim).
Not only that, the value of the parameter in the module is changed as well!!:
[root@localhost param]# rmmod p.ko
[root@localhost param]# dmesg -c
[ 7616.109704] value of parameter a now is: 32
[ 7616.109709] bye bye qworld
[root@localhost param]# What does this mean? READ Only permissions can just be overruled by a userland application like vim? What is the use of permission bits then..?
| Why am I able to write a module parameter with READ ONLY permissions? |
I don’t think there’s any way to add /sys or /proc entries outside the kernel. For /sys it wouldn’t make much sense anyway — it’s a direct representation of kobject data structures.
You can however provide similar interfaces from userspace, for example using FIFOs; see mkfifo for details. You can see an implementation of this in sysvinit with its initctl FIFO.
|
Kernel space device drivers usually implement directories and file that show through /sys or /proc. Can the long running user space programs do this as well?
I have a daemon or long running program that needs to be able to be queried for some data and have some data set by external programs while it runs.
I could do a full blown sockets interface, but that's a lot of overhead for the program and the external requestors.
As the linux kernel developers found, using the "everything is a file" model was useful for tweaking kernel setting. I'd like to do the same.
Some may think the /sys directory is the sacred space of the kernel, but I don't see an important line between what is what is the "system" and some other services/servers/applications.
Using FUSE...
I've decided to use FUSE, the 'File system in USErspace' package libfuse3.so.
(After writing a wrapper for it...) I can define an array of structs, one per access variable/file:
struct fileObj files[] = {
{"mode", mode, getFunc, putFunc},
{"numbProcs", numbProcs, getFunc, putFunc},
{"svrHostPort", hostPort, getFunc, putFunc},
{"somethingWO", jakeBuf, NULL, putFunc}, // Write only file (why?)
{"timestamp", NULL, getTimestampFunc, NULL}, // Returns timestamp, R/O
{0}
};The mountpoint for the FUSE filesystem is '/ssm/fuse'... The 'ls -l' shows that each entry in the 'files' array shows up as a file, some R/O, some R/W, one W/O. The 'getTimestampFunc in the 'get' function position shows that a special function can be associated with a file to perform calculate repsonses.
ribo@box:~/c$ ls -l /ssm/fuse
total 0
-rw-r--r-- 1 ribo ribo 10 Dec 28 17:17 mode
-rw-r--r-- 1 ribo ribo 1 Dec 28 17:17 numbProcs
--w------- 1 ribo ribo 3 Dec 28 17:17 somethingWO
-rw-r--r-- 1 ribo ribo 5 Dec 28 17:17 svrHostPort
-r--r--r-- 1 ribo ribo 32 Dec 28 17:17 timestamp
ribo@box:~/c$ cat /ssm/fuse/timestamp
18/12/28 17:17:27ribo@box:~/c$cat /ssm/fuse/mode
hyperSpeedribo@box:~/c$ echo slow >/ssm/fuse/mode
ribo@box:~/c$ cat /ssm/fuse/mode
slowThe 'echo >' shows passing a value into the program. So its easy for me to peek and poke various parameters of the program as it runs.
| Can user space programs provide/implement sysfs or procfs files to pass data to and from a program? |
I have not read the source code that populates operstate, but generally, reading a file in sysfs executes some code on the kernel side that returns the bytes you're reading. So, without you reading operstate, it has no "state". The value is not stored anywhere.How to watch for sysfs file changeSince these are not actually files, the concept "change" doesn't exist.
There's probably a better way to achieve what you want! netlink was designed specifically for the task of monitoring networking state; it's easy to interface. For example, this minimally modified sample code from man 7 netlink might already solve your problem:
struct sockaddr_nl sa; memset(&sa, 0, sizeof(sa));
sa.nl_family = AF_NETLINK;
// Link state change notifications:
sa.nl_groups = RTMGRP_LINK; fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
bind(fd, (struct sockaddr *) &sa, sizeof(sa));Generally, if this is not about ethernet-level connectivity but, say, connectivity to some IP network (or, the internet), systemd/NetworkManager is the route you'd go on a modern system instead.
|
How to watch for sysfs file changes (like /sys/class/net/eth0/statistics/operstate) and execute a command on content change?inotify does not work on sysfs
I don't want to poll. I want to set a listener with a callback routine once | How to attach a listener to sysfs files? |
tree behaves that way because it doesn’t dereference symlinks by default. The -l option will change that:
tree -l /sys/class/hwmon/but you’ll have fun making sense of all the output.
|
If I understand correctly, in Linux, everything is a path, right down to each piece of hardware. I am trying to get information about how my sensors are structured, so I thought I would just use tree to map out all the things in my hwmon directory. However, tree does not behave the same with this directory as I am accustomed to.
When I run tree on a normal directory, I get the subdirectory structure without using the -R or -L flags:
$ tree /home
/home
└── boss
├── clones
├── Desktop
├── Documents
│ ├── modules.txt
│ ├── old_docs
│ │ └── assorted
│ └── prepscript.txt
├── Downloads
├── Music
├── Pictures
├── Public
├── Templates
└── Videos12 directories, 2 filesbut I try to do the same with HWmon, it only goes one level deep, even if I do use the -R flag and even though there is stuff deeper:
$ tree /sys/class/hwmon/
/sys/class/hwmon/
├── hwmon0 -> ../../devices/pci0000:40/0000:40:01.3/0000:43:00.0/hwmon/hwmon0
├── hwmon1 -> ../../devices/pci0000:00/0000:00:01.3/0000:09:00.0/hwmon/hwmon1
├── hwmon2 -> ../../devices/pci0000:40/0000:40:03.1/0000:44:00.0/hwmon/hwmon2
├── hwmon3 -> ../../devices/pci0000:00/0000:00:18.3/hwmon/hwmon3
├── hwmon4 -> ../../devices/pci0000:00/0000:00:19.3/hwmon/hwmon4
├── hwmon5 -> ../../devices/virtual/thermal/thermal_zone0/hwmon5
└── hwmon6 -> ../../devices/platform/nct6775.656/hwmon/hwmon67 directories, 0 files
$ tree /sys/class/hwmon/hwmon0
/sys/class/hwmon/hwmon0
├── device -> ../../../0000:43:00.0
├── fan1_input
├── name
├── power
│ ├── async
│ ├── autosuspend_delay_ms
│ ├── control
│ ├── runtime_active_kids
│ ├── runtime_active_time
│ ├── runtime_enabled
│ ├── runtime_status
│ ├── runtime_suspended_time
│ └── runtime_usage
├── pwm1
├── pwm1_enable
├── pwm1_max
├── pwm1_min
├── subsystem -> ../../../../../../class/hwmon
├── temp1_auto_point1_pwm
├── temp1_auto_point1_temp
├── temp1_auto_point1_temp_hyst
├── temp1_crit
├── temp1_crit_hyst
├── temp1_emergency
├── temp1_emergency_hyst
├── temp1_input
├── temp1_max
├── temp1_max_hyst
├── uevent
└── update_interval3 directories, 27 filesWhat causes this difference in behavior, and can I just get a simple tree of all the devices?
| Why can't tree fully list /sys/class/hwmon? And how could I do that? |
I dug around a bit, and the reason behind your "LCD cooler" turned out to be incredibly interesting, in my opinion:
First off all, apparently LCD devices being listed as coolers under acpi are a thing, and not just a strange feature of your laptop - there are some more examples of those floating around online. If you do acpi -c yourself, you can list your coolers' states.
After some googling, it turns out that the sysfs driver is responsible for the thermal management. From its documentation:The generic thermal sysfs provides a set of interfaces for thermal
zone devices (sensors) and thermal cooling devices (fan, processor...)
to register with the thermal management solution and to be a part of
it.So we're looking at a driver that can both read thermal information from sensors, and control the cooling devices.
The documentation explains what the possible types for cooling devices are:type:
String which represents the type of device, e.g: for generic ACPI: should be "Fan", "Processor" or "LCD"Now that's quite interesting. Apparently "LCD" somehow is a type of cooling device.
Doing some more digging, I managed to find a paper by the developers of sysfs. It describes that finding a good thermal management solution became increasingly more necessary, due to handheld devices popping up. This ultimately lead to the development of sysfs.
In section 6 of the paper, they talk about Intel's Menlow Platform, which is a handheld platform (~5 inches screen size). The paper states that "relying only on the ACPI standards was not enough because sensors available in the platform were capable of doing more things than in ACPI 2.0."
There we have it. sysfs was invented, with its first practical use being on Menlow. The authors list multiple components of the sysfs thermal management, one of which is:ACPI thermal management, which has its thermal zone driver (ACPI
thermal driver) and cooling device drivers (processor, fan, and
video driver) registered with the thermal sysfs driverVideo driver!
The most important part follows in section 6.5:The following cooling devices are registered with the thermal sysfs
driver on Menlow:
[...]
ACPI video throttles the LCD device by reducing the backlight brightness levels.ACPI can reduce the backlight brightness of your screen, to make it produce less heat. Therefore, what does this make your screen? A cooling device! Weeell, sort of.
So here's the solution to your mystery ;)
If you have the time and interest for it, I'd suggest reading the paper. It's written in a nicely understandable fashion, so there's lots to learn.
Links:sysfs documentation
sysfs paper |
I have Compaq CQ60-120ec notebook. I discovered that there is a directory /sys/class/thermal/cooling_device2.
The type said LCD. I tried to control the cooling device, and it dimmed my backlight on the laptop. But I have question I cannot find aywhere on the internet. Why it is showing up as thermal device? Why not as acpi backlight?
Please, if you know why is this as it is, don't blame me that I don't know linux. I know linux fairly well, but this thing is making question marks in my dreams.
| Sysfs LCD backlight as thermal device |
The sysfs code was partially split in version 3.14 (2014) into a kernfs common part that would make it suitable for other subsystems to have a virtual filesystem, so we have to look at sysfs and kernfs.
Though there is no apparent serialization in the sysfs code, the kernfs layer above is using a mutex in kernfs_file_direct_read and kernfs_fop_write to ensure only a single read or write can happen at a time for the same file. There's also some locking when mmap() is used.
So your scenario should be safe.
|
Program A periodically (20 times/s) over-writes the first (and only) line of a sysfs file (F).
Program B periodically (20 times/s) opens the same sysfs file (F), reads the first line and closes it.
Since F is a shared resource and in the above scenario that does not have any synchronization between the two programs, there should be a possibility that B reads an incompletely written line in the file.
Is this true of sysfs files also or does the kernel serialize its access?
| Shared access of sysfs |
TL;DR: This exact feature is gone forever, because of laptops' poor quality and buggy precious, proprietary, NDA-ed firmware. But there is a workaround.
According to this thread on Linux kernel bug tracker, firmware in way too many laptops initializes its internal lid state variable to zero on boot - meaning closed. Despite the fact that nobody can turn the laptop on with the lid closed (this is always checked by firmware before power-on), resulting in an obvious mismatch between the real state and the firmware's reported state.
For this reason kernel completely disregards this statically reported state from firmware. And to maintain its own state, it relies solely on firmware's ACPI interrupt events reporting changes in state after the device is booted, and assumes it's open, unless proven otherwise.
Root users can check the kernel state directly by calling the appropriate input device. While the C code is simple, you can still use an existing utility evtest as shown in the answer by Stuart P. Bentley:
evtest --query "/dev/input/EVENT_N" "EV_SW" "SW_LID" && echo "open" || echo "closed"Unprivileged users can query the state only via systemd's logind over D-Bus (since v240):
dbus-send --system --print-reply=literal \
--dest="org.freedesktop.login1" "/org/freedesktop/login1" \
"org.freedesktop.DBus.Properties.Get" \
string:"org.freedesktop.login1.Manager" string:"LidClosed" | \
awk 'NR == 1 { print $3 == "true" ? "closed" : "open" }'or
busctl get-property "org.freedesktop.login1" "/org/freedesktop/login1" \
"org.freedesktop.login1.Manager" "LidClosed" | \
awk 'NR == 1 { print $2 == "true" ? "closed" : "open" }' |
ACPI procfs is deprecated in new kernel versions. In sysfs, which is supposed to replace it, I don't know of any clean way to read the state of the lid button. What is the new way of doing this?
| sysfs alternative to /proc/acpi/button/lid/LID/state |
The output of dmidecode is based on SMBIOS data.
Here is apparently-latest version of the SMBIOS specification, as of this writing.
The lower half of page 70 describes the data structure for the port connector information. The only meaningful values there are the DMI structure handle (a simple 16-bit number), internal & external connector type values, and two strings describing the connector identifier on the system board and on the exterior of the chassis, respectively.
Only the handle number would be unique to a particular connector, so only it might be used as an identifier that could tie a particular USB device to a SMBIOS/DMI connector information. But it doesn't seem that there is anything on the USB hardware side that could refer to these numbers to indicate which connector belongs to which device.
Also, usb1 and usb2 in the /sys/bus/usb/devices listing don't refer to individual connectors, but different USB buses. A USB 3.x system will always have at least two buses: one bus to handle the USB 2 and older speeds, and another bus for the USB 3+ speeds. This reflects the fact that the older speeds use one set of data wires, and the newer super-fast transfer modes of USB3.x will use a different set of data wires. Each bus will usually have its own root hub, which can have a varying number of USB connectors.
So, to tie a specific DMI connector information structure to a particular USB port device, the USB hub descriptor would have to have a data field that would specify the appropriate DMI structure handle.
Alternatively, the PCI device information of the USB controller would have to include a list of DMI handles belonging to that controller, but that would only allow the identification of which set of USB ports belongs to which controller, not unique identification of a specific port.
Unfortunately, I cannot find any data field on the USB or PCI bus information that would contain such DMI handles or equivalent port descriptions. So I'm afraid the answer seems to be "no, it is not generally possible to tie the physical port identifiers to individual Linux USB bus/port objects at this time."
Some name-brand systems might have some vendor-specific bus data extensions that would in fact include this information, but as long as there is no widely-adopted standard practice that could be relied on, the general answer would remain a "no, that information is not available."
|
Having had a bit of an internet-scour, I think the answer may be "No", but:
Can I find the USB port description (as per dmidecode) corresponding to the USB device from sysfs?
We can enumerate all USB hubs and devices by listing /sys/bus/usb/devices. For example:
lrwxrwxrwx 1 root root 0 May 18 09:40 1-2 -> ../../../devices/pci0000:00/0000:00:14.0/usb1/1-2
lrwxrwxrwx 1 root root 0 May 18 09:40 1-2:1.0 -> ../../../devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2:1.0
lrwxrwxrwx 1 root root 0 May 18 09:36 2-0:1.0 -> ../../../devices/pci0000:00/0000:00:14.0/usb2/2-0:1.0
lrwxrwxrwx 1 root root 0 May 18 09:36 2-3 -> ../../../devices/pci0000:00/0000:00:14.0/usb2/2-3
lrwxrwxrwx 1 root root 0 May 18 09:36 2-3:1.0 -> ../../../devices/pci0000:00/0000:00:14.0/usb2/2-3/2-3:1.0
lrwxrwxrwx 1 root root 0 May 18 09:36 usb1 -> ../../../devices/pci0000:00/0000:00:14.0/usb1
lrwxrwxrwx 1 root root 0 May 18 09:36 usb2 -> ../../../devices/pci0000:00/0000:00:14.0/usb2…And we can list all built-in USB ports on the machine by doing dmidecode -t connector. For example it shows (among many other connectors):
Handle 0x000D, DMI type 8, 9 bytes
Port Connector Information
Internal Reference Designator: USB REAR
Internal Connector Type: Proprietary
External Reference Designator: Rear: USB-1
External Connector Type: Access Bus (USB)
Port Type: USB[...]Handle 0x0014, DMI type 8, 9 bytes
Port Connector Information
Internal Reference Designator: USB 3.0 REAR
Internal Connector Type: Proprietary
External Reference Designator: Rear: USB 1
External Connector Type: Access Bus (USB)
Port Type: USB(On my machine, it looks like each USB port appears twice, in the guise of "USB" and "USB 3.0".)
I’d love to be able show the connector description ("Rear: USB 1") corresponding to a particular USB device— but there does not seem to be a reliable way to relate /sys/bus/USB devices to dmidecode connectors— Is there?
(In my particular case, it would be tempting to relate "usb1" from the bus to "USB 1" from Dmidecode… but I’m willing to bet that that’s a coincidence.)
Edit: Or if not dmidecode, some other tool which could provide an external description of the port.
| Can I relate a USB device from /sys to a particular USB connector from Dmidecode? |
OK I think your question title is a bit unintentionally misleading, since in the text you're saying you've already found the device and are asking how to programmatically do so. One question that comes to mind is how you manually found it and why you couldn't just script around it. I'll answer the question as best I can in its current form, apologies in advance if I miss the mark.
Stuff like this is incredibly variable and device-specific. It's considerations like this that require drivers/software adapters even in higher level software. So you should probably get used to the idea that this script will do this one particular thing rather than abstracting out to some generic process (which is what I'm guessing you're trying to do).
As a bit of background: Each bus-like system (USB, SCSI, PCI, etc) needs some form of addressing devices. With lspci these are the values you see on the leftmost of each line in the default output.
Abbreviated example:
[root@hypervisor pyadmin]# lspci
00:00.0 Host bridge: Intel Corporation 5400 Chipset Memory Controller Hub (rev 20)
00:1d.1 USB controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #2 (rev 09)
00:1d.2 USB controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #3 (rev 09)
04:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E1 (rev 01)
04:01.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E2 (rev 01)
07:05.0 Fibre Channel: QLogic Corp. ISP2422-based 4Gb Fibre Channel to PCI-X HBA (rev 02)
07:06.0 Fibre Channel: QLogic Corp. ISP2422-based 4Gb Fibre Channel to PCI-X HBA (rev 02)
08:00.0 Ethernet controller: Broadcom Corporation NetXtreme BCM5754 Gigabit Ethernet PCI Express (rev 02)The PCI addresses are the 08:00.0, 07:06.0, etc.
As you said, the sysfs directory you're looking at is for one of the modules (usbled) so you're looking at the information sysfs has on that module, which includes devices that use the module (or vice versa, if you like). The 1-1.2:1.0 you're looking at represents the device and is being referenced by it's USB Address (in USB terminology the "endpoint").
So if you already know the module, I would basically filter out the known values and only search for dentry's that contain both colons and periods, as there's very little chance of another dentry in that particular sysfs directory ever being created with a name like that if it's not a connected device.
I know that's a little all over the place, but I'm pretty sure your answer's up there somewhere.
|
I have one of these and I am trying to write a Bash script for finding the device path in /sys.
My approach goes something like this:start in /sys/modules/usbled since this is the name of the kernel module loaded when the device is plugged in
cd to drivers/usb:usbled, which appears to be the bus and name of the driver for the device (according to usbled.c:229)
???I get stuck on the last step since the directory contains:
$ ls
1-1.2:1.0 bind module new_id remove_id uevent unbindNow, I happen to know in this case that the 1-1.2:1.0 directory contains the char devices necessary to control the LEDs. However, how does my script know this? Is there any particular naming convention behind the directory? What if there are multiple devices of the same type plugged in?
| Finding a char device in /sys using a Bash script? |
You'll likely need to add a UDEV rule to detect this devices presences. Once the device is detected, UDEV can create the corresponding /dev/sdb1 to go along with it.
These docs from OpenSUSE should get you started in the creation of this rule.Chapter 13. Dynamic Kernel Device Management with udevRegarding your question:"... but don't I need to be able to find the parent node in /sys for that? And I can't find anything..."I would expect that if the kernel has successfully detected /dev/sdb1, which it has since you're getting those messages in your dmesg log, then you'd have corresponding entries under /sys.
I would investigate the /sys more thoroughly, there is likely a device handle hiding in there that corresponds to /dev/sdb1. You can walk around the tree using this command: udevadm info -a -p /sys/class/... you'll need to add on the appropriate device in place of the dots (...).
Example
$ udevadm info -a -p /sys/class/ata_device/dev1.0 Udevadm info starts with the device specified by the devpath and then
walks up the chain of parent devices. It prints for every device
found, all possible attributes in the udev rules key format.
A rule to match, can be composed by the attributes of the device
and the attributes from one single parent device. looking at device '/devices/pci0000:00/0000:00:1f.2/ata1/link1/dev1.0/ata_device/dev1.0':
KERNEL=="dev1.0"
SUBSYSTEM=="ata_device"
DRIVER==""
ATTR{gscr}==""
ATTR{class}=="ata"
ATTR{ering}=="[4294667.658000000]Unknown"
ATTR{spdn_cnt}=="0"
ATTR{pio_mode}=="XFER_UDMA_7, XFER_UDMA_6, XFER_UDMA_5, XFER_UDMA_4, XFER_MW_DMA_4, XFER_PIO_6, XFER_PIO_5, XFER_PIO_4, XFER_PIO_3, XFER_PIO_2, XFER_PIO_1, XFER_PIO_0"
ATTR{dma_mode}=="XFER_UDMA_7, XFER_UDMA_6, XFER_UDMA_5, XFER_UDMA_4, XFER_UDMA_3, XFER_UDMA_2, XFER_UDMA_1, XFER_UDMA_0, XFER_MW_DMA_4, XFER_MW_DMA_3, XFER_MW_DMA_2, XFER_SW_DMA_2, XFER_PIO_6, XFER_PIO_5, XFER_PIO_4, XFER_PIO_3, XFER_PIO_2"
ATTR{xfer_mode}=="XFER_UDMA_7, XFER_UDMA_6, XFER_UDMA_5, XFER_UDMA_4, XFER_UDMA_3, XFER_UDMA_2, XFER_UDMA_1, XFER_UDMA_0, XFER_MW_DMA_4, XFER_MW_DMA_3, XFER_MW_DMA_2, XFER_SW_DMA_2, XFER_PIO_6, XFER_PIO_5, XFER_PIO_4, XFER_PIO_3, XFER_PIO_2" looking at parent device '/devices/pci0000:00/0000:00:1f.2/ata1/link1/dev1.0':
KERNELS=="dev1.0"
SUBSYSTEMS==""
DRIVERS=="" looking at parent device '/devices/pci0000:00/0000:00:1f.2/ata1/link1':
KERNELS=="link1"
SUBSYSTEMS==""
DRIVERS=="" looking at parent device '/devices/pci0000:00/0000:00:1f.2/ata1':
KERNELS=="ata1"
SUBSYSTEMS==""
DRIVERS=="" looking at parent device '/devices/pci0000:00/0000:00:1f.2':
KERNELS=="0000:00:1f.2"
SUBSYSTEMS=="pci"
DRIVERS=="ahci"
ATTRS{irq}=="40"
ATTRS{subsystem_vendor}=="0x17aa"
ATTRS{broken_parity_status}=="0"
ATTRS{class}=="0x010601"
ATTRS{consistent_dma_mask_bits}=="64"
ATTRS{dma_mask_bits}=="64"
ATTRS{local_cpus}=="00000000,00000000,00000000,0000000f"
ATTRS{device}=="0x3b2f"
ATTRS{msi_bus}==""
ATTRS{local_cpulist}=="0-3"
ATTRS{vendor}=="0x8086"
ATTRS{subsystem_device}=="0x2168"
ATTRS{numa_node}=="-1"
ATTRS{d3cold_allowed}=="1" looking at parent device '/devices/pci0000:00':
KERNELS=="pci0000:00"
SUBSYSTEMS==""
DRIVERS=="" |
When I connect my Samsung 390G (a cheap cell phone!) to Ubuntu 13.04, dmesg seems to indicate that the storage device thereon is recognizable:
[Sun Dec 29 01:26:10 2013] scsi16 : usb-storage 2-1.2:1.0
[Sun Dec 29 01:26:11 2013] scsi 16:0:0:0: Direct-Access SAMSUNG MMC Storage 2.31 PQ: 0 ANSI: 2
[Sun Dec 29 01:26:11 2013] sd 16:0:0:0: Attached scsi generic sg2 type 0
[Sun Dec 29 01:26:11 2013] sd 16:0:0:0: [sdb] 61497344 512-byte logical blocks: (31.4 GB/29.3 GiB)
[Sun Dec 29 01:26:11 2013] sd 16:0:0:0: [sdb] Write Protect is off
[Sun Dec 29 01:26:11 2013] sd 16:0:0:0: [sdb] Mode Sense: 0f 0e 00 00
[Sun Dec 29 01:26:11 2013] sd 16:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
[Sun Dec 29 01:26:11 2013] sdb: sdb1
[Sun Dec 29 01:26:11 2013] sd 16:0:0:0: [sdb] Attached SCSI removable disk
[Sun Dec 29 01:26:11 2013] sd 16:0:0:0: [sdb] Synchronizing SCSI cacheBut the problem is that no device shows up for this (i.e. no /dev/sdb or /dev/sdb1). I'm speculating that I need to do some udev rulemaking here, but don't I need to be able to find the parent node in /sys for that? And I can't find anything -- not completely sure where to look, but so far my reasonable-sounding guesses haven't yielded anything.
Note for reference that this device does mount as a drive in Windows Explorer, so I'm confident that the phone works as expected.
| Kernel recognizes USB device but then I can't find it in /sys or /dev |
It's actually very simple. All cgroup mounts must be done on top of a directory. Before you had,
cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,name=systemd)
cgroup on /sys/fs/cgroup/pids type cgroup (rw,nosuid,nodev,noexec,relatime,pids)
cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (rw,nosuid,nodev,noexec,relatime,net_cls,net_prio)
cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)
cgroup on /sys/fs/cgroup/memory type cgroup (rw,nosuid,nodev,noexec,relatime,memory)
cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio)
cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,nosuid,nodev,noexec,relatime,perf_event)
cgroup on /sys/fs/cgroup/rdma type cgroup (rw,nosuid,nodev,noexec,relatime,rdma)
cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpu,cpuacct)
cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset)
cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)When you unmounted all these, you left the underlying directories there. Alas, these can be removed by remounting /sys/fs/cgroup as rw and simply deleting them.
sudo mount -o remount,rw /sys/fs/cgroup
# Delete the symlinks
sudo find /sys/fs/cgroup -maxdepth 1 -type l -exec rm {} \;
# Delete the empty directories
sudo find /sys/fs/cgroup/ -links 2 -type d -not -path '/sys/fs/cgroup/unified/*' -exec rmdir -v {} \;
sudo mount -o remount,ro /sys/fs/cgroupAfter which you should just see your beautiful and clean cgroup2 remaining,
$ ls /sys/fs/cgroup
unified |
I just unmounted cgroup version 1, leaving just a single cgroup2 mount on my system.
$ mount | grep -i cgroup
tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,size=4096k,nr_inodes=1024,mode=755)
cgroup2 on /sys/fs/cgroup/unified type cgroup2 (rw,nosuid,nodev,noexec,relatime,nsdelegate)I was under the impression everything in /sys/fs/cgroup that was not /sys/fs/cgroup/unified is an artifact of cgroup 1. How come these remain though after unmounting cgroup version 1?
$ ls -lh
drwxr-xr-x 2 root root 40 Dec 25 18:57 blkio
lrwxrwxrwx 1 root root 11 Dec 25 18:57 cpu -> cpu,cpuacct
lrwxrwxrwx 1 root root 11 Dec 25 18:57 cpuacct -> cpu,cpuacct
drwxr-xr-x 2 root root 40 Dec 25 18:57 cpu,cpuacct
drwxr-xr-x 2 root root 40 Dec 25 18:57 cpuset
drwxr-xr-x 2 root root 40 Dec 25 18:57 devices
drwxr-xr-x 2 root root 40 Dec 25 18:57 freezer
drwxr-xr-x 2 root root 40 Dec 25 18:57 memory
lrwxrwxrwx 1 root root 16 Dec 25 18:57 net_cls -> net_cls,net_prio
drwxr-xr-x 2 root root 40 Dec 25 18:57 net_cls,net_prio
lrwxrwxrwx 1 root root 16 Dec 25 18:57 net_prio -> net_cls,net_prio
drwxr-xr-x 2 root root 40 Dec 25 18:57 perf_event
drwxr-xr-x 2 root root 40 Dec 25 18:57 pids
drwxr-xr-x 2 root root 40 Dec 25 18:57 rdma
drwxr-xr-x 2 root root 40 Dec 25 18:57 systemd
dr-xr-xr-x 13 root root 0 Dec 26 21:37 unifiedAre these remaining temp dirs that are not kernel interfaces?
$ find . | grep -v unified
./freezer
./cpuset
./cpu
./cpuacct
./cpu,cpuacct
./rdma
./perf_event
./blkio
./memory
./devices
./net_prio
./net_cls
./net_cls,net_prio
./pids
./systemdHow does these empty directories work with cgroups v1?
| Why, after unmounting cgroup v1, do I still have empty directories under /sys/fs/cgroup? |
The __ATTR macro expands to the following [1]:
#define __ATTR(_name, _mode, _show, _store) { \
.attr = {.name = __stringify(_name), \
.mode = VERIFY_OCTAL_PERMISSIONS(_mode) }, \
.show = _show, \
.store = _store, \
}Note the use of the macro VERIFY_OCTAL_PERMISSIONS. That macro expands to the following [2]:
#define VERIFY_OCTAL_PERMISSIONS(perms) \
(BUILD_BUG_ON_ZERO((perms) < 0) + \
BUILD_BUG_ON_ZERO((perms) > 0777) + \
/* USER_READABLE >= GROUP_READABLE >= OTHER_READABLE */ \
BUILD_BUG_ON_ZERO((((perms) >> 6) & 4) < (((perms) >> 3) & 4)) + \
BUILD_BUG_ON_ZERO((((perms) >> 3) & 4) < ((perms) & 4)) + \
/* USER_WRITABLE >= GROUP_WRITABLE */ \
BUILD_BUG_ON_ZERO((((perms) >> 6) & 2) < (((perms) >> 3) & 2)) + \
/* OTHER_WRITABLE? Generally considered a bad idea. */ \
BUILD_BUG_ON_ZERO((perms) & 2) + \
(perms))What version of BUILD_BUG_ON_ZERO you get depends on a macro that I didn't track down, but you should note the comment in the above macro: "OTHER_WRITABLE? Generally considered a bad idea".
Although I didn't trace the call path, my guess is that the code filters/ignores o+w.
All that said, why would you want a non-privileged user to be able to interact directly with a piece of hardware?
[1] http://elixir.free-electrons.com/linux/v4.14/source/include/linux/sysfs.h#L101
[2] http://elixir.free-electrons.com/linux/v4.14/source/include/linux/kernel.h#L940
|
I want to write a driver to pass some info to a device, and to do so I've made a sysfs entry. It works fine, but the problem is that I don't have the permissions to write to it unless I am logged in as admin. I'd like it to have open read and write permissions.
The way I was advised to write the driver, I used the following macro to set up the sysfs attribute:
__ATTR(status_vector,0660,status_vector_is_read,status_vector_is_written);The problem is obvious, I've used 660 as the permission instead of 666.
However, when I try putting the permission as 666, or using the defined S_IWUGO | S_IRUGO, I get an error. I am able to set open read permissions, but not write. Apparently this person had the same problem, but I don't see any answer given on that thread.
I could always just set the permissions using chmod, but that seems clunky and annoying of a solution, Id rather learn how to actually write a driver properly. Why am I not allowed to set S_IWUGO?
| How to give Sysfs attribute write permissions? |
There are some issues with hardware/driver as explained on this LKML thread. Quoting just a little part of the reply mail:The reason is that most drivers don't even probe the link or negotiate link speed and flow control until the device is brought up. Many don't even power up the PHY when the device is down, in order to save power.
So the behavior you observe is completely expected.Even when you have link(cable connected) it will prompt you the -EINVAL error. Power management configurations may issue this error too on an interface that is already plugged and up.
mii-tool and ethtool should be more reliable on giving you information about link state of the ethernet interface(maybe ip l l).
|
box101:~ # cat /sys/class/net/eno1/carrier
cat: /sys/class/net/eno1/carrier: Invalid argumentWhat the...? OK, so what does strace say?
...
open("/sys/class/net/eno1/carrier", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=4096, ...}) = 0
fadvise64(3, 0, 0, POSIX_FADV_SEQUENTIAL) = 0
read(3, 0x19c8000, 65536) = -1 EINVAL (Invalid argument)
...So let me get this straight... The file opens perfectly, yet reading from it is somehow an error?
What's more annoying is that on box103, the exact same command works perfectly! On box101, I can read every single file in that directory except carrier.
Can anyone explain what the hell is going on here?
| Reading from sysfs returns EINVAL |
/sys is an implimentation of the sysfs (system file system) which is a virtual file system (it doesn't exist on disk) various system internals can be read here, in a similar way /proc and the procfs shows process information. /sys/class shows information that relate to a class of device/attribute.
You can read an overview in this linux.org article. [Link updated from @John P's comment below. 21 Oct 2017] |
On Linux (Ubuntu 11.10 on a ARM processor in my case) I was looking for a way to measure CPU temperature. I found out that a
cat /sys/class/thermal/thermal_zone0/tempdid the trick. Now I wonder: what is the /sys/class filesystem meant for?
| /sys/class filesystem on Linux |
You can only write non-negative integers to this file because it is a special file and the kernel rejects any other input. It isn't a special file in the sense of having a special file type, but it's a special file because it's on a special filesystem. When you access a “normal” filesystem, the kernel stores the file contents on a disk without interpreting them. But when you access files under /proc (procfs) or /sys (sysfs), the data isn't stored on a disk, the access invokes custom kernel code. For a file like /sys/class/backlight/intel_backlight/brightness, this custom code wants an integer between 0 and some hardware-dependent maximum, and if you try to write anything else the write call fails with the error status EINVAL.
|
If I pipe a string consisting only of a positive integer into /sys/class/backlight/intel_backlight/brightness, it works. But if I pipe a string containing anything else I've tried, I get an error message:
$ sudo su -c "echo 10 >/sys/class/backlight/intel_backlight/brightness"
$ sudo su -c "echo -- -1 >/sys/class/backlight/intel_backlight/brightness"
bash: line 0: echo: write error: Invalid argument
$ sudo su -c "echo aa >/sys/class/backlight/intel_backlight/brightness"
bash: line 0: echo: write error: Invalid argument
$ sudo su -c "echo 10.2 >/sys/class/backlight/intel_backlight/brightness"
bash: line 0: echo: write error: Invalid argumentI first thought this was some special kind of file but it appears to be a regular file:
$ file /sys/class/backlight/intel_backlight/brightness
/sys/class/backlight/intel_backlight/brightness: ASCII textWhat's going on?
| How come I can only pipe positive integers into this file? |
You will have to patch the kernel.
Files in /sys and /proc are purely virtual, you cannot change their permissions using normal Linux utilities.
|
I'm trying to make /sys/fs/selinux/enforce always contain "1", and prevent it from being changed.
I've been able to do this on /etc/selinux/config by running chattr +i /etc/selinux/config
However, when i try this on a file in the selinux sysfs I get the following error:
chattr: Inappropriate ioctl for device while reading flags on /sys/fs/selinux/enforceI'm assuming this is due to the sysfs files being different from actual files.
Any known way to accomplish the same outcome?
| Any way to make sysfs file immutable? |
I think I found the reason behind this.
The same device is exposed to USB subsystem as two devices with different interfaces.
like in the entry Sysfs=/devices/pci0000:00/0000:00:14.0/usb3/3-3/3-3.4/3-3.4:1.2/0003:2965:5023.0006/input/input7, the device exposes Interface 2 of the hardware as seen from the string 3-3.4:1.2 where the last digit is InterfaceNumber.
If we look at the output of cat /sys/devices/pci0000:00/0000:00:14.0/usb3/3-3/3-3.4/3-3.4:1.2/0003:2965:5023.0006/input/input7/device, we can see that DRIVER=hid-generic which says that this interface of the hardware exposes this device as USBHID generic.
However, for the other entry whose interface is 0 as seen in /devices/pci0000:00/0000:00:14.0/usb3/3-3/3-3.4/3-3.4:1.0/0003:2965:5023.0004/input/input13 , the output of cat /sys/devices/pci0000:00/0000:00:14.0/usb3/3-3/3-3.4/3-3.4:1.0/0003:2965:5023.0004/input/input13/device shows that DRIVER=hid-multitouch which means that this interface of the hardware exposes it as HID MULTITOUCH.
Therefore, the two entries for the same hardware.
|
I have one USB touchscreen connected to my hardware setup but using cat /proc/bus/input/devices gives me two entries for the same device :
I: Bus=0003 Vendor=2965 Product=5023 Version=0110
N: Name="Kortek Kortek Touch"
P: Phys=usb-0000:00:14.0-3.4/input2
S: Sysfs=/devices/pci0000:00/0000:00:14.0/usb3/3-3/3-3.4/3-3.4:1.2/0003:2965:5023.0006/input/input7
U: Uniq=S20131028
H: Handlers=mouse1 event7 js0
B: PROP=0
B: EV=1b
B: KEY=30000 0 0 0 0 0 0 0 0
B: ABS=3
B: MSC=10I: Bus=0003 Vendor=2965 Product=5023 Version=0110
N: Name="Kortek Kortek Touch"
P: Phys=usb-0000:00:14.0-3.4/input0
S: Sysfs=/devices/pci0000:00/0000:00:14.0/usb3/3-3/3-3.4/3-3.4:1.0/0003:2965:5023.0004/input/input13
U: Uniq=S20131028
H: Handlers=mouse2 event13
B: PROP=2
B: EV=b
B: KEY=400 0 0 0 0 0 0 0 0 0 0
B: ABS=a608000 3why are there two different entries for this same device ?
| Multiple entries in /proc/bus/input/devices for same device |
The values are given in kHz (see the documentation). So 60000 is 60 MHz, 396000 is 396 MHz.
|
I was trying to get frequecy from my device at run time. I used this device node
sudo cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq It gave me 60000.
I tried this one
cat /sys/devices/system/cpu/cpu*/cpufreq/cpuinfo_cur_freqI get 396000.
What is the unit of these values. Is it 60000 Hz or Mhz?
| What is the unit of this value |
/sys is a special filesystem. You can't just create it and put files in it. It's like /proc, a fake filesystem provided by the kernel.
Geting /sys working requires 2 things:In your kernel configuration, you need to have CONFIG_SYSFS=y.
You need to mount it with mount -t sysfs none /sys (assuming you're running from an initramfs since you mention cpio).So the directory itself should be there so you can mount on top of it, but that's it, nothing inside it.
|
my rootfs.cpio has only following files:
[root@localhost extract]# ls
dev init tmpdev has console only.
init is cross-compiled from the program given at the end:
Then I make a my image and run linux. It runs fine but when init comes it shows error similar to the following :
Failed to open /sys/class/gpio/gpio251/direction
Failed to open /sys/class/gpio/gpio251/valueSo, I manually created these folders and files and now it looks like this:
[root@localhost extract]# ls
dev init tmp sysinside sys I created required folders and files(empty).
But even then code is not executing and kernel panics.
Background
This code I took from a complete file system, which had all the directories expected in a linux system. I took this code cross compiled separately, and renamed it to init.
And expecting to work(Light an LED eg).
Another approach
bash> echo 240 > /sys/class/gpio/export
bash> echo out > /sys/class/gpio/gpio240/direction
bash> echo 1 > /sys/class/gpio/gpio240/valueThis approach is described GPIO DRIVER. So after manually creating these required files and I cross-compiled it and renamed it to init. And then made rootfs.cpio and created my OS image.
But this also did not work.
Questions
Why is the code not executing properly in my own file system (partial)?
Does the code depends upon some other files or dynamic libraries (which are present in complete file system)? Why is my manually created files not working?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
int main( )
{
extern char *optarg;
char *cptr;
int gpio_value = 0;
int nchannel = 0; int c;
int i; opterr = 0;int argc=5;
char *argv;
char *argv2[] = {"gpio-demo", "-g", "255", "o", "0"}; argv = argv2;
while ((c = getopt(argc, argv, "g:io:ck")) != -1) {
switch (c) {
case 'g':
gl_gpio_base = (int)strtoul(optarg, &cptr, 0);
if (cptr == optarg)
usage(argv[0]);
break;
case 'i':
gpio_opt = IN;
break;
case 'o':
gpio_opt = OUT;
gpio_value = (int)strtoul(optarg, &cptr, 0);
if (cptr == optarg)
usage(argv[0]);
break;
case 'c':
gpio_opt = CYLON;
break;
case 'k':
gpio_opt = KIT;
break;
case '?':
usage(argv[0]);
default:
usage(argv[0]); }
} if (gl_gpio_base == 0) {
usage(argv[0]);
} nchannel = open_gpio_channel(gl_gpio_base);
signal(SIGTERM, signal_handler); /* catch kill signal */
signal(SIGHUP, signal_handler); /* catch hang up signal */
signal(SIGQUIT, signal_handler); /* catch quit signal */
signal(SIGINT, signal_handler); /* catch a CTRL-c signal */
switch (gpio_opt) {
case IN:
set_gpio_direction(gl_gpio_base, nchannel, "in");
gpio_value=get_gpio_value(gl_gpio_base, nchannel);
fprintf(stdout,"0x%08X\n", gpio_value);
break;
case OUT:
set_gpio_direction(gl_gpio_base, nchannel, "out");
set_gpio_value(gl_gpio_base, nchannel, gpio_value);
break;
case CYLON:
#define CYLON_DELAY_USECS (10000)
set_gpio_direction(gl_gpio_base, nchannel, "out");
for (;;) {
for(i=0; i < ARRAY_SIZE(cylon); i++) {
gpio_value=(int)cylon[i];
set_gpio_value(gl_gpio_base, nchannel, gpio_value);
}
usleep(CYLON_DELAY_USECS);
}
case KIT:
#define KIT_DELAY_USECS (10000)
set_gpio_direction(gl_gpio_base, nchannel, "out");
for (;;) {
for (i=0; i<ARRAY_SIZE(kit); i++) {
gpio_value=(int)kit[i];
set_gpio_value(gl_gpio_base, nchannel, gpio_value);
}
usleep(KIT_DELAY_USECS);
}
default:
break;
}
close_gpio_channel(gl_gpio_base);
return 0;
} | Accessing GPIO after kernel boots |
/sys/class/hwmon/hwmon2 is a symlink to /sys/devices/platform/soc/3f205000.i2c/i2c-0/0-0044/hwmon/hwmon2 (technically, /../../devices/platform/soc/3f205000.i2c/i2c-0/0-0044/hwmon/hwmon2).
/sys/devices contains the sysfs files, by device, for all the devices in the system. This allows them to have a unique path and name based on their “location” (as a platform device, a PCI device etc.).
/sys/class gives access to a subset of those files, by class. This allows them to be found by purpose (vaguely defined). For example, a program interested in all hardware monitors can look at everything under /sys/class/hwmon. Because this is only a different view of the “devices” hierarchy (or a subset thereof), the “class” tree consists mostly of symlinks pointing into the “devices” tree.
|
I have a Raspberry Pi that is running the 'bookworm' version of the OS; the 64-bit version of the OS if that makes any difference. I've installed one of the SHT3X temperature & humidity sensors, and it is apparently working fine. It's connected via I2C interface (channel 0, /dev/i2c-0 I believe). I can read temp & humidity from the files in sysfs; I believe the sensor is working correctly.
I have found that there are two identical folders in sysfs that contain the same output and control files for the SHT3X device:
folder 1: /sys/devices/platform/soc/3f205000.i2c/i2c-0/0-0044/hwmon/hwmon2
$ ls -l
total 0
lrwxrwxrwx 1 root root 0 Jun 2 21:55 device -> ../../../0-0044
-rw-r--r-- 1 root root 4096 Jun 2 21:55 heater_enable
-r--r--r-- 1 root root 4096 Jun 2 21:55 humidity1_alarm
-r--r--r-- 1 root root 4096 Jun 2 21:55 humidity1_input
-rw-r--r-- 1 root root 4096 Jun 2 21:55 humidity1_max
-rw-r--r-- 1 root root 4096 Jun 2 21:55 humidity1_max_hyst
-rw-r--r-- 1 root root 4096 Jun 2 21:55 humidity1_min
-rw-r--r-- 1 root root 4096 Jun 2 21:55 humidity1_min_hyst
-r--r--r-- 1 root root 4096 Jun 2 21:55 name
lrwxrwxrwx 1 root root 0 Jun 2 21:55 of_node -> ../../../../../../../../firmware/devicetree/base/soc/i2c@7e205000/sht3x@44
drwxr-xr-x 2 root root 0 Jun 2 21:55 power
-rw-r--r-- 1 root root 4096 Jun 2 21:55 repeatability
lrwxrwxrwx 1 root root 0 Jun 2 21:55 subsystem -> ../../../../../../../../class/hwmon
-r--r--r-- 1 root root 4096 Jun 2 21:55 temp1_alarm
-r--r--r-- 1 root root 4096 Jun 2 21:55 temp1_input
-rw-r--r-- 1 root root 4096 Jun 2 21:55 temp1_max
-rw-r--r-- 1 root root 4096 Jun 2 21:55 temp1_max_hyst
-rw-r--r-- 1 root root 4096 Jun 2 21:55 temp1_min
-rw-r--r-- 1 root root 4096 Jun 2 21:55 temp1_min_hyst
-rw-r--r-- 1 root root 4096 Jun 2 21:52 uevent
-rw-r--r-- 1 root root 4096 Jun 2 21:55 update_intervalfolder 2: /sys/class/hwmon/hwmon2
$ ls -l
total 0
lrwxrwxrwx 1 root root 0 Jun 2 21:55 device -> ../../../0-0044
-rw-r--r-- 1 root root 4096 Jun 2 21:55 heater_enable
-r--r--r-- 1 root root 4096 Jun 2 21:55 humidity1_alarm
-r--r--r-- 1 root root 4096 Jun 2 21:55 humidity1_input
-rw-r--r-- 1 root root 4096 Jun 2 21:55 humidity1_max
-rw-r--r-- 1 root root 4096 Jun 2 21:55 humidity1_max_hyst
-rw-r--r-- 1 root root 4096 Jun 2 21:55 humidity1_min
-rw-r--r-- 1 root root 4096 Jun 2 21:55 humidity1_min_hyst
-r--r--r-- 1 root root 4096 Jun 2 21:55 name
lrwxrwxrwx 1 root root 0 Jun 2 21:55 of_node -> ../../../../../../../../firmware/devicetree/base/soc/i2c@7e205000/sht3x@44
drwxr-xr-x 2 root root 0 Jun 2 21:55 power
-rw-r--r-- 1 root root 4096 Jun 2 21:55 repeatability
lrwxrwxrwx 1 root root 0 Jun 2 21:55 subsystem -> ../../../../../../../../class/hwmon
-r--r--r-- 1 root root 4096 Jun 2 21:55 temp1_alarm
-r--r--r-- 1 root root 4096 Jun 2 21:55 temp1_input
-rw-r--r-- 1 root root 4096 Jun 2 21:55 temp1_max
-rw-r--r-- 1 root root 4096 Jun 2 21:55 temp1_max_hyst
-rw-r--r-- 1 root root 4096 Jun 2 21:55 temp1_min
-rw-r--r-- 1 root root 4096 Jun 2 21:55 temp1_min_hyst
-rw-r--r-- 1 root root 4096 Jun 2 21:52 uevent
-rw-r--r-- 1 root root 4096 Jun 2 21:55 update_intervalAnd there's more; e.g.:
folder 3: /sys/devices/platform/soc/3f205000.i2c/i2c-0/0-0044/hwmon/hwmon2/subsystem/hwmon2
I realize there are symlinks involved, but is there a true/immutable location for these files in sysfs? I've read some references on sysfs 1, 2, but found no explanation for this apparent duplication. Can someone explain the apparent redundancy, and if there is an immutable location for the files?
| Why is this folder duplicated in `sysfs`? |
/sys/devices/system/node/node0 represents a NUMA hardware node that may accept a command to go into an offline state independent of the rest of the system. So it can be the subject of udev events, which can trigger actions based on udev rules.
/sys/kernel/mm represents no particular hardware: it is just a place for general memory management parameters of the kernel. It is present as soon as the kernel starts up and cannot go away, so there will be no udev events referencing it. And when there are no udev events, udev rules cannot be triggered.
Alternatively, you can say that only things under /sys/devices can have udev rules associated with them. /sys/kernel is not under /sys/devices.
Using udev rules to manipulate general memory management parameters would be rather unusual. /etc/sysctl.conf[.d] would be a more standard place for customizing them.
|
I'm testing udev rules with a file /etc/udev/rules.d/10-test.rules.
This line:
DEVPATH=="/devices/system/node/node0", ATTR{hugepages/hugepages-1048576kB/nr_hugepages}="4"makes /sys/devices/system/node/node0/hugepages/hugepages-1048576kB/nr_hugepages be 4.
But this line:
DEVPATH=="/kernel/mm", ATTR{hugepages/hugepages-1048576kB/nr_hugepages}="4"does not affect /sys/kernel/mm/hugepages/hugepages-1048576kB/nr_hugepages.
Neither does this line:
DEVPATH=="/kernel", ATTR{mm/hugepages/hugepages-1048576kB/nr_hugepages}="4"(Even rebooting does not work.)
Why?
| Why does udev rule not work on `DEVPATH=="/kernel"`? |
Every directory can be a mountpoint, like / is a mountpoint, and /sys is too, or often /home is a separate mountpoint.
|
The mount point for debugfs is /sys/kernel/debug, and the mount point for sysfs is /sys/, why can these 2 mount points be overlapped without interference?
| Why can the mount points of debugfs and sysfs be overlapped? |
As rightly asserted by Tilman in comments, sysfs and ioctl both provide userland access to kernel data structures.
Since the kernel does not need system calls to access to its own data, neither is the sysfs tree built resorting to ioctl calls, nor any user action on its files will translate into ioctl calls.You write " … information is already available by simply reading files…" and this is, I believe, the answer for your final question :
Why can it appear simpler to resort to the sysfs interface ?First because considered in front of your basic ASCII terminal running some shell, the sysfs tree gives access to (binary) kernel data via the most basic cat and echo commands.
Thanks to other basic shell commands, (ls, cd) you can also, following the symlinks get some deep understanding of the relationships between kernel objects.
On top of this the user can take benefits from some (at least minimal) control over the validity of the changes you would wish to commit.This indeed makes sysfs the right way to go when, under console, wishing to tune your system, write scripts or rules, confortabely debug some driver from userspace (the initial destination of sysfs… just think that before… /dev/mem was your only friend for that later purpose.)
All right then, however, there are cases you just don't care of all these facilities, cases where accessing kernel objects via the sysfs interface would just constrain you to… write (much) more code : When writing a C program :
Just imagine : You want to open some file, transcode your data, manage additional error conditions, deal with race conditions ? When a simple ioctl system call is enough (providing you know what you are doing of course).
So you had the answer to your question : When should you prefer this or that way ? Simply because for you, here and now, achieving what you want to achieve will be much simpler using this rather than that.
|
My assumption is that sysfs is built using ioctl queries, meaning all the information you would want (or at least most of it) is already available by simply reading files on sysfs. I notice some programs (e.g., hdparm) still use ioctl calls rather than simply hitting sysfs , and I'm curious if there's a reason for that. Is sysfs unreliable? If you're only interested in hardware info, is there a reason to use ioctl over sysfs?
| Is there ever a reason to query ioctl for hardware info when we have sysfs? |
No one else has answered this but I've come up with a solution, so answer:
I think the most correct way is to use /sys/class/block/*, which contains (symlinks to) available block devices.
It also has their partitions, which you will want to ignore and can identify by the existence of a partition file. This file is undocumented, so YMMV.
If you want them later you can get a specific devices partitions by looking for directories with a partition file. eg /sys/devices/**/sda/*/partition. The file also contains the partition number. Doing it this way means you don't have to know anything about device/partition kernel naming schemes, so I recommend it.
Note that /sys/block doesn't have partitions, at least on my system, but you're not supposed to rely on that.
After getting available block devices you probably want to do something with them, so to get their device files you can read major:minor from the undocumented dev file and simply search for the matching device in /dev.
If you want their sizes you can use the undocumented size file, which contains the device size / 512. Always 512. Partitions have this too. Partitions also have a start field, which is partition start / 512 on the disk. These are "documented" in this forgotten patch, which if to be believed means these files have been stable and undocumented for about 20 years now. So.. ü§∑‚Äç‚ôÄÔ∏è
If you want device models you can use the similarly undocumented ../../model file, relative to the device in /sys/devices/. This might be documented here but I honestly can't tell if thats supposed to apply here or not.
You could also get the name of the device directory, ie /sys/devices/**/sda is the full path to a block device, and the name, sda, probably exists in /dev.
But I wouldn't rely on this, technically /dev could have fancy names for things, so I recommend searching dev for matching major:minor to be agnostic to device filenames.Some information about this is documented here, but
|
What APIs/interfaces are available for this? I think I want sysfs, but according to what various kernel documentation exists, that interface can be summed up as "you're not allowed to use any of this, implementation details.", and what little it does allow you to use is completely undocumented.
Specifically I want to find connected block devices(which apparently i'm not allowed to know exist, being an implementation detail?), and I'd like to know what attributes block devices have(that I can depend on existing across versions), and their contents.
Just stuff thats actually helpful in using sysfs, and yet completely undocumented.
| How to get connected block devices on Linux |
Programmatically, you could first stat("/dev/input/accelerometer0", &stat_struct) to find out the major and minor device numbers.
Then use libudev's udev_device_new_from_devnum() to get a struct udev_device for your accelerometer, and then udev_device_get_syspath() to get the pathname of its sysfs directory.
|
I have an input class device (accelerometer) bound to a driver which exposes sysfs attributes that I need to access from userland. Using a udev rule, I have provided an alias that unambiguously identifies my device, i.e. ll /dev/input yields:
lrwxrwxrwx 1 root root 6 May 18 13:47 accelerometer0 -> event0
drwxr-xr-x 2 root root 60 May 18 13:47 by-path
crw-rw---- 1 root input 13, 64 May 18 13:47 event0
crw-rw---- 1 root input 13, 65 May 18 13:47 event1
crw-rw---- 1 root input 13, 66 May 18 13:47 event2So far, so good: I can open("/dev/input/accelerometer0") in my userland code and start streaming the data. But to, for example, change the data rate, I need to write to the pollrate_ms attribute in the related sysfs directory. An ls /sys/class/input/ yields:
event0 event1 event2 input0 input1 input2I happen to know that pollrate_ms resides in input0/device, but I need to figure this out programatically, especially since future updates might cause that numbering to change.
I know that I can use libudev to enumerate /sys/class/input and then use a for loop to explore each of those directories until I find the one containing pollrate_ms. It just seems like that's a lot of work compared to how easy it was to unambiguously identify the device via a udev rule.
Am I missing out on an easy way or should I just suck it up?
| How to find sysfs directory for a specific device? |
mknod /dev/mtdblock0 c 31 0
You created a character device. You wanted a block device. So use b instead of c in the mknod command.
Block device numbers and character device numbers are independent. Block device 31:0 is unrelated to character device 31:0. Your kernel has no driver for character device 31:0, hence the “No such device or address” error.
|
I've got some sort of home entertainment system running an old version of Linux 2.6. It has a SATA > USB bridge system and a couple of USB ports. What I want to do is use it as Network Attached Storage.
Now, luckily, it has an open and accessible telnet server running.
The problem is, I can't find where the kernel, nor the init system are. The box is running BusyBox.
The board has a single flash chip on it. But, under sysfs in block/ I see multiple flash chips:
/sys/block # ls
...
mtdblock0 mtdblock2 mtdblock4
mtdblock1 mtdblock3Why is that btw?
Now, I want to create a /dev entry for them so I can dump each of them to a USB flash drive and analyze them.
So I did this:
/sys/block # cat /sys/block/mtdblock0/dev
31:0And ..
mknod /dev/mtdblock0 c 31 0Which exited with 0, then I try to read raw data to test the device:
/sys/block # cat /dev/mtdblock0
cat: /dev/mtdblock0: No such device or addressWhy is that? dd is saying the same. There is entries in /proc/devices:
/sys/block # cat /proc/devices
Character devices:
1 mem{ ... }Block devices:
1 ramdisk
7 loop
8 sd
31 mtdblock{ ... } | Failing to create /dev entry from sysfs, No such device or address |
As far as I can tell, this file is public by default.
Check if there are startup scripts that restrict permissions on your system, either with traditional file permissions or with a security framework such as SELinux or AppArmor.
If you want to leave most directories opaque but allow access to this one file, you can add a sudo rule. To allow all users in somegroup to run the command sudo cat /sys/class/net/eth0/statistics/rx_bytes, run visudo and add a rule like
%somegroup ALL = NOPASSWD: cat /sys/class/net/eth0/statistics/rx_bytes |
I know that I can use
cat /sys/class/net/eth0/statistics/rx_bytesto see the amount of received bytes. Sadly I only can run this command as root.
When I am another user, I get cat: /sys/class/net/eth0/statistics/rx_bytes: Permission denied
Is there an easy way to allow non-root users to read this file? Currently a non-root is not allowed to access any of the directories in path.
I also tried to use ifconfig, but there I get this error
Warning: cannot open /proc/net/dev (No such file or directory). Limited output. | Allow non-root user go get network traffic statistics |
One solution would be a script, which changes permissions on that files using chmod and then setting you system so it would start the script on system bootup.
|
My current primary question motivator:
$ ls -l /sys/devices/platform/samsung
total 0
-rw-r--r-- 1 root root 4096 27. jaan 14:17 battery_life_extender
drwxr-xr-x 3 root root 0 19. jaan 18:40 leds
-r--r--r-- 1 root root 4096 26. jaan 23:37 modalias
-rw-r--r-- 1 root root 4096 27. jaan 12:57 performance_level
drwxr-xr-x 2 root root 0 24. jaan 00:35 power
drwxr-xr-x 4 root root 0 19. jaan 18:40 rfkill
lrwxrwxrwx 1 root root 0 27. jaan 13:03 subsystem -> ../../../bus/platform
-rw-r--r-- 1 root root 4096 27. jaan 13:03 uevent
-rw-r--r-- 1 root root 4096 26. jaan 23:37 usb_chargeI'd like to modify these without sudo. During a desktop session that. Privileged startup script is perfectly OK.
It's feeling like the solution is to have some sort of generic insmod parameters?
| Is there a generic approach to automatically make some sysfs controls ch{own,mod} user-accessible? |
The contents of that phys_port_id file is generated upon request (when a process reads it) by the phys_port_id_show() function in the Linux kernel.
You can see that it returns EOPNOTSUPP if the driver for the network interface doesn't implement a ndo_get_phys_port_id operation. If you look for ndo_get_phys_port_id in the drivers/net/ethernet directory, you'll find that not many Ethernet drivers (Broadcom bnx2x, Intel i40e and a handful of others) implement it (probably because not many Ethernet hardware devices provide that information which as detailed by @ChrisDavies is only relevant for NICs with more than one port).
You can tell what driver drives your eth0 ethernet device with:
readlink /sys/class/net/eth0/device/driverOr ls -l /sys/class/net/eth0/device/driver if the readlink applet is not enabled in your build of busybox.
|
I customized the system using Kernel 6.4.0 and Busybox, but I don't know why the three files starting with phys_ cannot be accessed, and other files in the same folder can.
# pwd
/sys/class/net/eth0
# ls
addr_assign_type carrier_up_count gro_flush_timeout napi_defer_hard_irqs proto_down tx_queue_len
addr_len dev_id ifalias netdev_group queues type
address dev_port ifindex operstate speed uevent
broadcast device iflink phys_port_id statistics
carrier dormant link_mode phys_port_name subsystem
carrier_changes duplex mtu phys_switch_id testing
carrier_down_count flags name_assign_type power threaded
#
#
#
# cat dev_
dev_id dev_port
# cat dev_port
0
# cat phys_port_id
cat: read error: Operation not supported
#
# ls -lt dev_port
-r--r--r-- 1 root root 4096 Oct 27 14:50 dev_port
# ls -lt phys_port_id
-r--r--r-- 1 root root 4096 Oct 27 15:36 phys_port_id | cat: read error: Operation not supported for /sys/class/net/eth0/phys_* |
Looking at the Linux 5.4.97 kernel source, I see drivers/spi/spidev.c. In that file, I see the function that handles write requests:
ssize_t
spidev_write(struct file *filp, const char __user *buf,
size_t count, loff_t *f_pos)
{
struct spidev_data *spidev;
ssize_t status = 0;
unsigned long missing; /* chipselect only toggles at start or end of operation */
if (count > bufsiz)
return -EMSGSIZE; spidev = filp->private_data; mutex_lock(&spidev->buf_lock);
missing = copy_from_user(spidev->tx_buffer, buf, count);
if (missing == 0)
status = spidev_sync_write(spidev, count);
else
status = -EFAULT;
mutex_unlock(&spidev->buf_lock); return status;
}Note the call to mutex_lock() and mutex_unlock(). A process calling write() on the character device will acquire the mutex, write all of its data, then unlock the mutex. If there was some other writer that came along during that process, that writer would block on the call to mutex_lock() until the existing writer called mutex_unlock().
Any writer that writes is guaranteed to write the entire buffer without interleaving from other writers.
|
I am wondering what happens when two processes write to a character device file at the same time.
Currently, I am mostly worried about /dev/spidev0.0 on a Raspberry pi.
If I assume correctly that it's the drivers task to deal with concurrent writes,
does the driver see which processes have written which data?
Or does the driver only see only continous data stream where all the concurrent writes get mixed in?
| Concurrent write access to character device file |
It depends on the kobject field and its serialisation functions. It’s not always easy to find those, but for USB they’re conveniently grouped. bInterfaceNumber is declared thus:
usb_intf_attr(bInterfaceNumber, "%02x\n");The second argument is the format string, so it shows a hex value. The line below shows that bAlternateSetting is displayed as a decimal value.
All sysfs entries are supposed to be documented, and bInterfaceNumber is described as
What: /sys/bus/usb/devices/usbX/bInterfaceNumber
Description:
Interface number, in hexadecimal. |
I am looking at files in sysfs, specifically in /sys/bus/usb/devices
The files contains small numbers, expressed as two characters, for example "00"
All of the examples that I have contain numbers that are "09" or lower.
I am writing a script to interpret these, and it is not clear to me whether I should expect "0A" or "10" as the next value (ie, is it decimal or hex?)
I've seen that these are views of kernel kobjects, but I haven't been able to find the source for where they're serialized.
Can you please tell me if those numbers (for example, in bInterfaceNumber) are meant to be decimal or hex, or if it varies on a case-by-case basis. If it does vary, where in the source code can I go to check for specific files in sysfs?
If it is relevant, my computers are mostly Ubuntu, a mix of 20.04 and 22.04. I went looking at the usb-devices script as a point of comparison and there have been changes between the versions that make me less confident of what it's trying to do.
| Are numbers in sysfs presented in decimal or hex? |
No, file system monitoring is a kernel function, and systemd just uses this function.
The sysfs file system is a mapping of kernel objects to file names, and does not support inotify.
The best way to monitor interface up/down events is through netlink (the ip mon command shows what events are available there), but the systemd configuration language does not provide a keyword for that.
If the service in question is dependent on having a network connection, it may be possible to declare a dependency on that, but I'm not sure the teardown semantics of the component stack are well defined, that is a glaring hole in the specification.
|
I'm trying to get a systemd service to restart when some ethernet cable gets plugged in, by monitoring changes to the /sys/class/net/eth0/carrier_up_count system file.
I tried creating a systemd path service:
[Path]
PathModified=/sys/class/net/eth0/carrier_up_count
Unit=restart-other-service.servicebut, while I can see that the carrier_up_count indeed changes when I plug the cable in, this path service never gets triggered.
I assume this happens because systemd path services actually monitors when files are open and closed for writing, and the /sys/ files are always open (I can see that the last modified timestamp of the file doesn't change even though the contents of the file does).
I also tried using a systemd socket service with ListenSpecial=/sys/class/net/eth0/carrier_up_count, but the service failed:
Got unexpected poll event (0x9) on socket.
Failed with result 'resources'.Is there a way to get systemd to monitor changes on the files in /sys/ ? I guess I could just create a cronjob that reads the target file periodically but it feels like there should be a better way.
| Watching for /sys/class/net file changes using systemd |
If you have systemd, it does that automatically (and some extra mount points as well, including /dev/, /dev/shm, /dev/pts, /run and even /tmp).
If you have a different init system, you'll have to do that according to its documentation, most likely manually using /etc/fstab or/and scripts.
Here's what gets mounted on Fedora 38 with systemd automatically without any configuration files:
debugfs on /sys/kernel/debug type debugfs (rw,nosuid,nodev,noexec,relatime,seclabel)
devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,seclabel,gid=5,mode=620,ptmxmode=000)
devtmpfs on /dev type devtmpfs (rw,nosuid,noexec,relatime,seclabel,size=32889888k,nr_inodes=8222472,mode=755)
fusectl on /sys/fs/fuse/connections type fusectl (rw,nosuid,nodev,noexec,relatime)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
pstore on /sys/fs/pstore type pstore (rw,nosuid,nodev,noexec,relatime,seclabel)
ramfs on /run/credentials/systemd-sysctl.service type ramfs (ro,nosuid,nodev,noexec,relatime,seclabel,mode=700)
ramfs on /run/credentials/systemd-tmpfiles-setup-dev.service type ramfs (ro,nosuid,nodev,noexec,relatime,seclabel,mode=700)
ramfs on /run/credentials/systemd-tmpfiles-setup.service type ramfs (ro,nosuid,nodev,noexec,relatime,seclabel,mode=700)
selinuxfs on /sys/fs/selinux type selinuxfs (rw,nosuid,noexec,relatime)
sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime,seclabel)
tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev,seclabel)
tmpfs on /run type tmpfs (rw,nosuid,nodev,seclabel,size=13156600k,nr_inodes=819200,mode=755)
tmpfs on /run/user/1000 type tmpfs (rw,nosuid,nodev,relatime,seclabel,size=6578296k,nr_inodes=1644574,mode=700,uid=1000,gid=1000)
tmpfs on /tmp type tmpfs (rw,nosuid,nodev,relatime,seclabel,size=49337248k)
tmpfs on /var/tmp type tmpfs (rw,nosuid,nodev,relatime,seclabel) |
If you build a custom GNU/Linux system for an embedded device, do you need to execute
mount -t proc proc /proc
mount -t sysfs sysfs /syssomewhere in init process or is this done automatically by the kernel? I've read contradicting statements about this. An embedded Linux book advises to run the commands in init scripts while I've read somewhere that Systemd is not doing this as it is done by the kernel before userspace is created.
What is actually true? Who mounts /proc and /sys?
| Who mounts /proc and /sys in GNU/Linux systems? |
This specific error isn’t particularly important, it’s a “trick” used to break the build if a given value is determined to be zero. To understand why the build is failing, you need to look at the next error message, which should includenote: in expansion of macro ‘BUILD_BUG_ON_ZERO’followed by the expression which caused the error.
In your case, the build is failing because you’re specifying a world-writable mode, 0666; you should set at most 0664.
|
Thank you for reading this question.
I was trying to compile a kernel module that works with sysfs, and while executing make I ended up with this error. Can somebody please help me understand what this error means?
/usr/src/linux-headers-4.19.0-9-common/include/linux/build_bug.h:29:45: error: negative width in bit-field ‘<anonymous>’
#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:(-!!(e)); }))followed by
/usr/src/linux-headers-4.19.0-9-common/include/linux/kernel.h:1051:3: note: in expansion of macro ‘BUILD_BUG_ON_ZERO’
BUILD_BUG_ON_ZERO((perms) & 2) + \
^~~~~~~~~~~~~~~~~
/usr/src/linux-headers-4.19.0-9-common/include/linux/sysfs.h:103:12: note: in expansion of macro ‘VERIFY_OCTAL_PERMISSIONS’
.mode = VERIFY_OCTAL_PERMISSIONS(_mode) }, \
^~~~~~~~~~~~~~~~~~~~~~~~
/home/bkkarthik/Workspace/tasks/task09/helloworld.c:76:45: note: in expansion of macro ‘__ATTR’
static struct kobj_attribute id_attribute = __ATTR(id, 0666, id_show, id_store);I am relatively new to Linux kernel programming, I am not aware of what information you need to assess this situation. Please feel free to ask for further information if needed. Thanks in advance :)
| negetive width in bit field '<anonymous>' while running 'make' |
Use watch around cat or a while loop instead:
watch cat /sys/devices/platform/applesmc.768/lightwhile sleep 0.5; do cat /sys/devices/platform/applesmc.768/light; doneThe file is not being appended to with new values, it is being replaced so inorder to reread the values you need to reread the file. Thus tail will not work as it is waiting for more lines to be appended to the file.
In python you could try skipping to the beginning of the opened file, but that will likely just allow you to reread the old value again. Closing and reopening the file should work as you want it to however.
|
Once upon a time, I cast this shellspell,
# tail -f /sys/devices/platform/applesmc.768/lightand it does produce,
(0,0)Those file I read is light sensor abstraction file of Macbook Pro.
Unfortunately, when I give some light into the sensor (in the same place as camera), It didn't update the value!
It does show the change when read manually,
# cat /sys/devices/platform/applesmc.768/light
(50,0)The quest is as to why?!
Cause I want to do some polling into the value and get the notification when it changed. Using python too doesn't work.
| Tail-ing /sys/devices/platform/applesmc.768/light not working |
/sys is a completely RAM-based filesystem for access to kernel data structures. This includes the GPIO interfaces.
All you need to do is open the pseudofile normally, and use a single write to write the data. If it succeeds, and all of the data (except possibly any trailing whitespace like newlines) was written, the kernel assures you it has accepted all of it. In other words:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>#define GPIO_EXPORT_PATH "/sys/class/gpio/export"static int gpio_export(int pin)
{
char buffer[32];
ssize_t written;
int fd;
char *const q = buffer + sizeof buffer;
char *p = buffer + sizeof buffer; if (pin < 0)
return errno = EINVAL; *(--p) = '\n'; do {
*(--p) = '0' + (pin % 10);
pin /= 10;
} while (pin > 0); do {
fd = open(GPIO_EXPORT_PATH, O_WRONLY);
} while (fd == -1 && errno == EINTR);
if (fd == -1)
return errno; do {
written = write(fd, p, (size_t)(q - p));
} while (written == -1 && errno == EINTR);
if (written == -1) {
const int saved_errno = errno;
close(fd);
return errno = saved_errno;
} if (close(fd))
return errno; /* Not all written?
* It is okay if the last char, '\n' was not written. */
if (written != (ssize_t)(q - p) &&
written != (ssize_t)(q - 1 - p))
return errno = EIO; /* Partial write, data not accepted! */ return errno = 0;
}Note that when we do the write(), we verify that all characters (except for the trailing newline) were written. This is the atomicity requirement you need. I also like to be careful, and verify that close() does not fail either. (Although it does not currently occur, it is the only way to report certain errors, so I like to be prepared for the time when those errors are reported. If they were to occur.)
|
I'd like to guarantee that what I write to a sysfs file (specifically the /sys/class/gpio files) is sync'd to the actual register. The code I had initially opened the file with the O_SYNC flag, which I assumed did this. However, in another piece of code, I tried using fsync(), but it failed with EINVAL, and man fsync tells me:
EROFS, EINVAL
fd is bound to a special file which does not support synchronizationI've checked the code for possible operations on a sysfs file, and did not find any sort of do_sync_write or do_fsync functions.
So, does the O_SYNC flag have any effect when opening a sysfs file? Shouldn't open return an error code when trying to open a file that does not support sync read/write with O_SYNC?
Regards,
Guilherme
| Synchronous I/O on sysfs files |
The multi-gen LRU documentation in the kernel describes the values as follows:Values
Components0x0001
The main switch for the multi-gen LRU.0x0002
Clearing the accessed bit in leaf page table entries in large batches, when MMU sets it (e.g., on x86). This behavior can theoretically worsen lock contention (mmap_lock). If it is disabled, the multi-gen LRU will suffer a minor performance degradation for workloads that contiguously map hot pages, whose accessed bits can be otherwise cleared by fewer larger batches.0x0004
Clearing the accessed bit in non-leaf page table entries as well, when MMU sets it (e.g., on x86). This behavior was not verified on x86 varieties other than Intel and AMD. If it is disabled, the multi-gen LRU will suffer a negligible performance degradation.The values are ored together, so 0x0007 means that all features are enabled, and 0x0001 means that multi-gen LRU is enabled but without clearing the accessed bit in large batches.
Any combination is valid, i.e. any value between 0x0000 and 0x0007. The expected value depends on your kernel configuration.
|
I wanted to check if the multi-generational LRU was active on my desktop, so I looked at the value of /sys/kernel/mm/lru_gen/enabled. It was set to 0x0007. I felt unsure what to make of this value, so I checked the value on a different device where I knew for sure that I had enabled it since I configured the kernel myself on there, and it gave me the value 0x0001. What do these two values mean, and what are the expected values if the multi-generational LRU is enabled and disabled? Are there any other valid values for this file?
| What do the different values of /sys/kernel/mm/lru_gen/enabled mean? |
Use udevadm info to query device attributes, then creat udev rule which would create symlink in /dev/ to easy access the device by your custom name. See https://wiki.archlinux.org/index.php/Udev#udev_rule_example
|
I'm running ubuntu linux and I have a bluetooth mouse that I would like to capture evdev events from. The problem is that the event device can potentially be different any time I connect the mouse: sometimes it's /dev/input/event17, sometimes /dev/input/event16, etc.
/dev/input/by-id and /dev/input/by-path aren't getting populated for this device. I've seen solutions that involve parsing /proc/bus/input/devices to find the event number, but I feel like there has to be an easier way. Isn't there a symlink out in /proc or /sys that will always point to the events for a specific device? Or Maybe some udev rule that I could configure?
| Is there a reliable path to specific device events? |
Yes, a kernel driver can control the data it exposes in sysfs/procfs based on user-id, and/or basically any information the kernel has access to.
When you read something from procfs or sysfs, the system call for reading the information basically ends calling a function in the respective driver. That function can see all the information on the user-space process that called for the read operation, and can certainly modify its output based on that, or based on anything else the kernel can access.
In the specific case of /sys/bus/pci/devices/<PCI device ID>/config, any attempts to read it will end up in function pci_read_config() in file drivers/pci/pci-sysfs.c which will check if the calling user-space process has CAP_SYS_ADMIN capability (which in most cases means the user is root). If the user does not have that capability, the function will restrict the readable PCI configuration data to the first (dev->cfg_size) bytes (128 bytes on CardBus).
In kernel versions 2.6.5 and below, the limit used to be 256 bytes, but in 2.6.6 it was tightened to (dev->cfg_size). On a modern system, the (dev->cfg_size) tends to be either 64 or 256 bytes according to the device in question.
You can demonstrate this with a simple lspci -v. If you run it as root, you will see the PCI/PCIe capabilities of each device. But if you run it as a regular user, you will get instead:
Capabilities: <access denied> |
On our 3.X series kernel, a proprietary PCI-Express device has a proprietary kernel driver. We're seeing some weird errors on trawling PCI capabilities. I can not find any great docs - does anyone know if the kernel driver can control what data is exposed in sysfs/procfs based on user-id?
Specifically, this call fails inside the vendor's utility:
c = pci_find_cap(mdev->pdev, VENDOR_EXT_CAP_ID, PCI_CAP_EXTENDED);After a lot of digging, I can replicate the failure using setpci looking for VENDOR_EXT_CAP_ID.
What I'm seeing is:FS permissions grant read access to user and root.
Open the file "config" in sysfs and read $data.
$data for user vs $data for root are different.I can't see a lot of docs on how this could be possible nor do we have a good escalation path with the Vendor. Has anyone seen this before?
| PCI-E, sysfs and user-id permission weirdness |
The advantage of option 2 is that you can validate the request in a single place. Say for a dishwasher you can ensure the door sensor says the door is closed before you turn on the water. Sure you can tell people to check the door status bit before they set the water on bit, but will they all do so?
A potential disadvantage of options 1 and 3 is permissions. It depends on how sophisticated the embedded device is, but you might want to have different userids doing different things, for example a home router might have a different uid running an http server doing the web UI and a different daemon operating the front panel LEDs. Whilst it is possible for gpio drivers to have fine grained access control, most have an all or nothing approach. With option 2 you can decide which users can access which facilities at a fine level.
The downside of option 2 is it is more complicated, and usually requires code in the kernel.
|
I believe I could not fully understand the benefits of writing device drivers in embedded systems for some specific devices, such as GPIO, when there are alternative ways of doing the same job.You can access the GPIOs via sysfs and device tree.Write a new device tree overlay and enable it
Go to the /sys/class/gpio
Export required pin and start using it (via simple shell calls or inside the c/c++ app)Write your own driver.Code the real functionalities.
Expose the driver to a node (like /dev/tty) in userspace.
Write another c/c++ code to access the driver (also it can be accessed via simple shell calls)
If you need any new functionalities, first change the driver then your code. (Why?)Use directly /dev/mem;Include mman.h and use /dev/mem object to set or get the GPIO status.So,1 -> is going to be deprecated and slow. (Ok, absolutely beneficial for fast prototyping)
2 -> How is that faster than 1? 1st one is also another GPIO driver, isn't it?
3 -> Isn't it best and fastest way?I asked several questions above but here is my biggest question; why shouldn't I go straight with the 3rd solution?
| Driver development vs sysfs access vs mmap for GPIOs |
No, it is not a strict subset. It is not even a subset.
Here is a demonstration, on a desktop PC running a major GNU/Linux distribution without any customisations that should affect the result, that there is at least one datum present in sysfs that is not present in procfs:
$ grep -ir `cat /sys/block/sda/device/model | cut -f1 -d' '` /sys 2>/dev/null
/sys/devices/pci0000:00/0000:00:1f.2/ata3/host2/target2:0:0/2:0:0:0/model:SanDisk [...]
Binary file /sys/devices/pci0000:00/0000:00:1f.2/ata3/host2/target2:0:0/2:0:0:0/vpd_pg83 matches$ grep -ir `cat /sys/block/sda/device/model | cut -f1 -d' '` /proc 2>/dev/null
Binary file /proc/26887/task/26887/cmdline matches
Binary file /proc/26887/cmdline matchesThis also demonstrates, incidentally, that on that PC at least, the set of all data exposed by procfs is not a subset of the data exposed by sysfs.
| Is the information that the Linux kernel provides to the user via sysfs a strict subset of the information that the Linux kernel provides to the user via procfs?
If not, then which information is provided via sysfs that is not provided via procfs?
| Is sysfs a strict subset of procfs? [duplicate] |
Those symlinks link to modules using the given module. You can see them using lsmod too. For example, on my system, lsmod shows (among many others)
ip6_tables 32768 1 ip6table_natThis means that the ip6_tables module is loaded, and that it’s used by the ip6table_nat. This is also represented under /sys/modules:
$ ls -l /sys/module/ip6_tables/holders
total 0
lrwxrwxrwx. 1 root root 0 Jan 4 09:29 ip6table_nat -> ../../ip6table_nat |
What exactly is under the /sys/module/<module_name>/holders directory? From what I see it's all symlinks. But symlinks representing what?
| What's inside Linux kernel sysfs holders directory? |
Your syntax translates to every 15 seconds, if you want every 15 minutes, IMO the most readable way is:
OnCalendar=*:0/15An answer most similar to what you use in your question is:
OnCalendar=*:0,15,30,45More information:http://www.freedesktop.org/software/systemd/man/systemd.time.html |
I'm trying to make a systemd timer that runs every 15 minutes. Right now I have: timer-fifteen.timer:
[Unit]
Description=15min timer[Timer]
OnBootSec=0min
OnCalendar=*:*:0,15,30,45
Unit=timer-fifteen.target[Install]
WantedBy=basic.target timer-fifteen.target:
[Unit]
Description=15min Timer Target
StopWhenUnneeded=yesThis runs over and over again without stopping. Does it need to be *:0,15,30,45:* instead? How can I make this work?
| systemd timer every 15 minutes |
if myjob.service contains no [Install] block, then it is sufficient to just disable the timer. The timer was the only thing starting the .service file, so with the .timer disabled, nothing will start the .service file.
Also remember to run systemctl --user stop myjob.timer. Disabling the timer prevents it from being started on the next boot, but it does not stop the timer currently running.
|
I've successfully migrated a few of my cron jobs over to systemd. I followed some guides and have taken the standard approach of creating 3 files:
myjob.timer - systemd timer unit
myjob.service - systemd service unit
myjob.shAs you can probably guess, at a certain time myjob.timer is triggered, which runs myjob.service which in turn executes myjob.sh.
I have the same setup for all of my timers and now that I see everything is working fine I want to disable myjob.timer, which is just a tester.
Do I just do:
systemctl --user disable myjob.timeror do I also have to do:
systemctl --user disable myjob.serviceWhat is the correct thing to do? I'm quite new to systemd, so I'd like to learn how to do stuff the proper way. I'm guessing that it's correct to disable both units in order to keep the system free of excess baggage running.
| Which is the correct way to disable a systemd timer unit? |
The state of currently active timers can be shown using
systemctl list-timers:
$ systemctl list-timers --all
NEXT LEFT LAST PASSED UNIT ACTIVATES
Wed 2016-12-14 08:06:15 CET 21h left Tue 2016-12-13 08:06:15 CET 2h 18min ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service1 timers listed. |
I am testing a systemd timer and trying to override its default timeout, but without success. I'm wondering whether there is a way to ask systemd to tell us when the service is going to be run next.
Normal file (/lib/systemd/system/snapbackend.timer):
# Documentation available at:
# https://www.freedesktop.org/software/systemd/man/systemd.timer.html[Unit]
Description=Run the snapbackend service once every 5 minutes.[Timer]
# You must have an OnBootSec (or OnStartupSec) otherwise it does not auto-start
OnBootSec=5min
OnUnitActiveSec=5min
# The default accuracy is 1 minute. I'm not too sure that either way
# will affect us. I am thinking that since our computers will be
# permanently running, it probably won't be that inaccurate anyway.
# See also:
# http://stackoverflow.com/questions/39176514/is-it-correct-that-systemd-timer-accuracysec-parameter-make-the-ticks-slip
#AccuracySec=1[Install]
WantedBy=timers.target# vim: syntax=dosiniThe override file (/etc/systemd/system/snapbackend.timer.d/override.conf):
# This file was auto-generated by snapmanager.cgi
# Feel free to do additional modifications here as
# snapmanager.cgi will be aware of them as expected.
[Timer]
OnUnitActiveSec=30minI ran the following commands and the timer still ticks once every 5 minutes. Could there be a bug in systemd?
sudo systemctl stop snapbackend.timer
sudo systemctl daemon-reload
sudo systemctl start snapbackend.timerSo I was also wondering, how can I know when the timer will tick next? Because that would immediately tell me whether it's in 5 min. or 30 min. but from the systemctl status snapbackend.timer says nothing about that. Just wondering whether there is a command that would tell me the delay currently used.
For those interested, there is the service file too (/lib/systemd/system/snapbackend.service), although I would imagine that this should have no effect on the timer ticks...
# Documentation available at:
# https://www.freedesktop.org/software/systemd/man/systemd.service.html[Unit]
Description=Snap! Websites snapbackend CRON daemon
After=snapbase.service snapcommunicator.service snapfirewall.service snaplock.service snapdbproxy.service[Service]
# See also the snapbackend.timer file
Type=simple
WorkingDirectory=~
ProtectHome=true
NoNewPrivileges=true
ExecStart=/usr/bin/snapbackend
ExecStop=/usr/bin/snapstop --timeout 300 $MAINPID
User=snapwebsites
Group=snapwebsites
# No auto-restart, we use the timer to start once in a while
# We also want to make systemd think that exit(1) is fine
SuccessExitStatus=1
Nice=5
LimitNPROC=1000
# For developers and administrators to get console output
#StandardOutput=tty
#StandardError=tty
#TTYPath=/dev/console
# Enter a size to get a core dump in case of a crash
#LimitCORE=10G[Install]
WantedBy=multi-user.target# vim: syntax=dosini | Is there a way to know when a systemd timer will run next? |
Every 2 hours at 30 minutes past the hour should be
OnCalendar=00/2:30
# iow hh/r:mm00/2 - the hh value is 00 and the repetition value r is 2 which means the hh value plus all multiples of the repetition value will be matched (00,02,04..14,16..etc)
30 - the mm value, 30 will match 30 minutes past each hour
I left the date and the seconds out since, per the same man page:date specification may be omitted, in which case the current day [...] is implied [...]If the second component is not specified, ":00" is assumed. |
There are several good references on systemd timers including this one:
systemd.time
Unfortunately, it still isn't clear to me how to create a timer that will run periodically, but at a specific number of minutes after the top of the hour.
I want to create a timer that runs 30 minutes past the hour, every 2 hours. So it would run at 14:30 (2:30 pm), 16:30, 18:30, 20:30, etc.
I tried several things that did not work, including this:
OnCalendar=*-*-* *00/2:30And this:
OnCalendar=*-*-* *:00/2:30I did not find the time specification to produce the desired result.
Also, it does not have to run exactly at that moment, so I was thinking about using:
AccuracySec=5m | systemd timer every 2 hours at 30 minutes past the hour? |
Yes, you can write directly to the target directory.
You can't really use a pipe directly as part of an ExecStart= command, since systemd doesn't really implement a full shell. But you can invoke a shell explicitly, which would make it work. For example:
ExecStart=/bin/sh -c '/usr/bin/atom | /Path/To/Script/Todays_Dir Todo.md'But it turns out this is a bit awkward, since Todays_Dir would end up having to run cat to write to the full path of its argument. In effect, you don't really need a pipe here, you just need to determine the name of a directory and run atom with the proper redirect.
Consider instead just implementing everything in a script and running it directly from the systemd unit.
Something like:
#!/bin/bash
set -e # exit on error
dated_dir=$HOME/Documents/Journals/$(date +%Y/%-m/%-d)
mkdir -p "${dated_dir}"
exec atom >"${dated_dir}/ToDo.md"And then in the systemd unit:
ExecStart=/Path/To/Script/GenerateMarkdownToTodaysDir.shThe exec at the end of the shell script makes the shell replace itself with the atom program, so that systemd will end up running atom directly after setup. For this case it's not that important, so it could be omitted (especially if you're interested in doing some kind of post-processing after the atom run.)
|
I'm trying to set up a systemd service in order to launch a set of files on a daily basis (different types of journals) from directories based off the date. For example, a todo list for today would be located in:
~/Documents/Journals/2019/1/23/ToDo.md Now the easiest thing to do is to put it in a separate directory, say today, and then have a bash script move it to the appropriate spot after the last modified time is no longer when it was created, or when the size of the file is larger than the template file. But while that would be easier, I was wondering if it would be possible to write a script to return the directory of the file to be piped through the executed command in the service. Something along the lines of:
ExecStart=/usr/bin/atom | /Path/To/Script/Todays_Dir Todo.md which would take the file as an argument and return the directory/file path based off the date (the same way the directory and files are being created).
Is this possible, or should I just stick to the already proposed solution?
| Pipe output of script through Exec in systemd service? |
For the simple use case, use WantedBy=timers.target. See man systemd.special:timers.target
A special target unit that sets up all timer units (see
systemd.timer(5) for details) that shall be active after boot.
It is recommended that timer units installed by applications get
pulled in via Wants= dependencies from this unit. This is best
configured via WantedBy=timers.target in the timer unit's
"[Install]" section.Timers get a dependency of Before=timers.target by default. And, if you check man bootup, you'll see that basic.target pulls in timers.target as a dependency. So I think WantedBy=basic.target would appear to work OK for most cases (same for default.target, which is usually multi-user.target or graphical.target, both of which come after basic.target). But:timers.target is pulled-in by basic.target asynchronously. This
allows timers units to depend on services which become only available
later in boot.So a more complicated timer that depends on some other service unit would be better off depending on timers.target rather than any of the others.
|
In various examples, I have seen all of these different choices suggested:WantedBy=timers.target
WantedBy=multi-user.target
WantedBy=basic.target
WantedBy=default.target
WantedBy=mytimer.target (custom user-defined name)However, in the examples I have found, no further explanation is offered.
The following pages also don't offer any explanation of WantedBy:https://www.freedesktop.org/software/systemd/man/systemd.timer.html
https://www.freedesktop.org/software/systemd/man/systemd.time.htmlI want to understand one simple* method I can use when needed to write a systemd timer instead of a cron job.
* Setting up a cron job is 1 line. Systemd timers involve writing two files and running one or two systemctl commands. But that fact alone is not necessarily what makes systemd timers harder than cron in my experience -- it's the multitude of options and the (seeming) lack of clear documentation with simple examples that are fully explained.
| I'm writing a systemd timer. What value should I use for WantedBy? |
The transient files end up in /run/user/ and do not seem to ever be removed until the user logs out (for systemd-run --user) or until a reboot, when /run is recreated.
For example, if you create a command to run once only at a given time:
systemd-run --user --on-calendar '2017-08-12 14:46' /bin/bash -c 'echo done >/tmp/done'You will get files owned by you in /run:
/run/user/1000/systemd/user/run-28810.service
/run/user/1000/systemd/user/run-28810.service.d/50-Description.conf
/run/user/1000/systemd/user/run-28810.service.d/50-ExecStart.conf
/run/user/1000/systemd/user/run-28810.timer
/run/user/1000/systemd/user/run-28810.timer.d/50-Description.conf
/run/user/1000/systemd/user/run-28810.timer.d/50-OnCalendar.confFor non --user the files are in /run/systemd/system/
You can remove the files, do a systemctl [--user] daemon-reload and
then list-timers will show only the Unit name, with their last history if they have already run. This information is probably held within systemd's internal status or journal files.
|
I've created a systemd job using systemd-run --on-calendar .... Now I've replaced it with proper .timer and .service files, but I'm not able to remove the old one. I can stop it and disable it, but when I call systemctl list-timers it still appears with its arbitrary name run-r0d0dc22.... I also looked for its .timer file, but I couldn't find them.
| Removing a timer created with "systemd-run --on-calendar" |
Is it possible to have it run at multiple moments by declaring it in
the same timer?Yes.
See this excerpt from man systemd.timer (my emphasis):
OnCalendar= Defines realtime (i.e. wallclock) timers with calendar event expressions. See systemd.time(7) for more information on the syntax of calendar event expressions. Otherwise, the semantics are similar to OnActiveSec= and related settings. Note that timers do not necessarily expire at the precise time configured with this setting, as it is subject to the AccuracySec= setting below. May be specified more than once.
Here is a working example that I use:
[Timer]
OnCalendar=Mon-Sun *-*-* 23:00:00
OnCalendar=Mon-Sun *-*-* 06:00:00 |
I'm using a systemd timer and unit to automatically trigger a backup job. But currently it runs only at one moment in the evening. Is it possible to have it run at multiple moments by declaring it in the same timer?
This is how it's now:
[Unit]
Description=Run luky-borg-backup every night[Timer]
OnCalendar=21:00
AccuracySec=1h
Persistent=yes[Install]
WantedBy=timers.targetShould be something like this:
[Unit]
Description=Run luky-borg-backup every night[Timer]
OnCalendar=10:00,21:00
AccuracySec=1h
Persistent=yes[Install]
WantedBy=timers.target | timer with multiple oncalendar moments |
systemd timer units can take multiple OnCalendar= specifications, so when you're creating your override to run at 3am, you're actually adding that time (making it run twice daily, at midnight and 3am.)
When you list the timer, it will show you the next schedule for it and, unless you're running that command between midnight and 3am, what you'll see is the original run at midnight, possibly giving you the impression that your configuration didn't work. (When you set it to hourly you'll likely see a change, unless you run the command between 11pm and midnight.)
To change the cron daily runs so they run at 3am using an override file, simply clear the previous definition (daily) first, which you can do by setting OnCalendar= to an empty value.
[Timer]
OnCalendar=
OnCalendar=*-*-* 03:00:00systemd man page for timer units actually documents this, though you'll find it under OnActiveSec= and friends, which says:If the empty string is assigned to any of these options, the list of timers is reset, and all prior assignments will have no effect. | I use systemd-cron which creates unit files under /lib/systemd. The unit file for cron-daily.timer has
[Timer]
OnCalendar=dailyThis triggers the scripts at midnight. I want them to trigger at 3am instead.
If I create override.conf in the cron-daily.timer.d directory under /etc/systemd/system to have
[Timer]
OnCalendar=*-*-* 03:00:00and run daemon-reload, restart the timer and run systemctl list-timers it still wants to run at 00:00:00. However, if I change my override.conf to have
[Timer]
OnCalendar=hourlythen it wants to run hourly as expected. Why can I not override the service to run at a specific time?
| Cannot override systemd timer with specific time [duplicate] |
An answer to this question is to swap User=nobody not with User=ziga but with User=root in /etc/systemd/system/battery.service. Somehow even if user ziga has all the privileges of using sudo command it can't execute systemctl hibernate inside of the bash script. I really don't know why this happens. So the working files are as follows:
/etc/systemd/system/battery.service
[Unit]
Description=Preko skripte preveri stanje baterije in hibernira v kolikor je stanje prenizko[Service]
Type=oneshot
ExecStart=/home/ziga/Dropbox/workspace/operacijski/archlinux/hibernate/hibernatescript
User=root
Group=systemd-journal/etc/systemd/system/battery.timer
[Unit]
Description=Periodical checking of battery status every two minutes[Timer]
OnBootSec=2min
OnUnitActiveSec=2min [Install]
WantedBy=battery.service/home/ziga/Dropbox/workspace/operacijski/archlinux/hibernate/hibernatescript
#!/bin/sh
/usr/bin/acpi -b | /usr/bin/awk -F'[,:%]' '{print $2, $3}' | (
read -r status capacity
if [ "$status" = Discharging ] && [ "$capacity" -lt 7 ]; then
/usr/bin/systemctl hibernate
fi
)I tried it and it allso works with User=ziga or User=nobody but we need to change /usr/bin/systemctl hibernate into sudo /usr/bin/systemctl hibernate in the last script. So it looks like User variable somehow doesn't even matter... Oh and you can as well remove absolute names from the last script and change first line from #!/bin/sh to #!/bin/bash. I also changed WantedBy=timers.target to WantedBy=battery.service in /etc/systemd/system/battery.timer.
There you go. The best cron alternative to hibernate laptops on low battery. =)
|
I am on Arch Linux where I am trying to create a systemd timer as a cron alternative for hibernating my laptop on low battery. So I wrote these three files:
/etc/systemd/system/battery.service
[Unit]
Description=Preko skripte preveri stanje baterije in hibernira v kolikor je stanje prenizko[Service]
Type=oneshot
ExecStart=/home/ziga/Dropbox/workspace/operacijski/archlinux/hibernate/hibernatescript
User=nobody
Group=systemd-journal/etc/systemd/system/battery.timer
[Unit]
Description=Periodical checking of battery status every two minutes[Timer]
OnUnitActiveSec=2min [Install]
WantedBy=timers.target/home/ziga/Dropbox/workspace/operacijski/archlinux/hibernate/hibernatescript
#!/bin/sh
/usr/bin/acpi -b | /usr/bin/awk -F'[,:%]' '{print $2, $3}' | (
read -r status capacity
if [ "$status" = Discharging ] && [ "$capacity" -lt 50 ]; then
/usr/bin/systemctl hibernate
fi
) And then to enable timer I executed:
sudo systemctl enable battery.timer
sudo systemctl start battery.timerAnd somehow it isn't working. Script works on its own. This means that if I execute command below, my computer hibernates just fine.
/home/ziga/Dropbox/workspace/operacijski/archlinux/hibernate/hibernatescriptADD1:
After enabling and starting timer I ran some checks and this is what I get:
[ziga@ziga-laptop ~]$ systemctl list-timers
NEXT LEFT LAST PASSED UNIT ACTIVATES
n/a n/a n/a n/a battery.timer battery.serv
Tue 2016-06-28 00:00:00 CEST 42min left Mon 2016-06-27 00:01:54 CEST 23h ago logrotate.timer logrotate.se
Tue 2016-06-28 00:00:00 CEST 42min left Mon 2016-06-27 00:01:54 CEST 23h ago shadow.timer shadow.servi
Tue 2016-06-28 00:00:00 CEST 42min left Mon 2016-06-27 00:01:54 CEST 23h ago updatedb.timer updatedb.ser
Tue 2016-06-28 22:53:58 CEST 23h left Mon 2016-06-27 22:53:58 CEST 23min ago systemd-tmpfiles-clean.timer systemd-tmpfand
[ziga@ziga-laptop ~]$ systemctl | grep battery
battery.timer loaded active elapsed Periodical checking of battery status every two minutesADD2:
After applying solution from Alexander T my timer starts (check the code below) but script doesn't hibernate my laptop while it hibernates it if I execute it directly.
[ziga@ziga-laptop ~]$ systemctl list-timers
NEXT LEFT LAST PASSED UNIT ACTIVATES
Tue 2016-06-28 19:17:30 CEST 1min 43s left Tue 2016-06-28 19:15:30 CEST 16s ago battery.timer battery.service | using systemd timers instead of cron |
Add After=network-online.target to the [Unit] section of the timer.
Explanation:
Timers do accept all the relative ordering commands in the [Unit] section that are known for services. In fact both the [Unit] and [Install] sections are identical for timers and services. Form the official manuals:A unit configuration file whose name ends in ".timer" encodes information about a timer controlled and supervised by systemd, for timer-based activation.
This man page lists the configuration options specific to this unit type. See systemd.unit(5) for the common options of all unit configuration files. The common configuration items are configured in the generic [Unit] and [Install] sections. The timer specific configuration options are configured in the [Timer] section.That said you need to know about network-online.target that defines if a network is up.network-online.target is a target that actively waits until the nework is "up", where the definition of "up" is defined by the network management software. Usually it indicates a configured, routable IP address of some kind. Its primary purpose is to actively delay activation of services until the network is set up.Limitations
network-online.target is not checking for internet but for network connections. The LAN of course might not have internet access per se. If you cannot rely on the router or your ISP to provide a connection, you would have to make e.g. a special test-internet.service that pings some website and only is defined active after it succeeded once (and otherwise restarts on failure every 15s or so). That should be a Type=oneshot and RemainAfterExit=yes kind of service. But I assume that this is not what you asked for.
Scopes: system/user
Be careful, as network-online.target is a system scope unit.
Units in the user scope will not see it and fail to start. This can be fixed by creating a linked unit: systemctl --user link /lib/systemd/system/network-online.target. The path can vary, the location can be checked by running: systemctl show --property FragmentPath network-online.target
|
I'm using systemd-timer to periodically run a script which consumes a webservice.
Problem is, upon system resume or wake-up, internet connectivity would not get started right away but the timer gets fired and hence the script returns error (If the service waits for a couple of seconds, the script would run correctly and there would be no need to postpone the task until next run.)
1- How can I make it so that the timer (or the service associated with it), waits until net connectivity is available?
2- How can I make the timer (or service) not call the script when system is not online yet?
| How to make a systemd-timer depend on internet connectivity? |
This answer is a bit late but I'll leave it here in case others stumble on it.
I think that it's important to understand the underlying mechanism of how systemd overrides work. Your solution illustrates that you figured out the low level implementation details and how to manually create overrides, which is a good thing.
For the sake of completeness and propagating best practices, people should use the built-in systemctl functions to create overrides (as @muru mentioned in the comment). For example:
sudo systemctl edit systemd-tmpfiles-clean.timerFor example, this ensures permissions are properly set on the file and reduces the likelihood of introducing errors by relying on the underlying abstractions.
If you want to view the components that make up this unit, use systemctl cat as follows:
sudo systemctl cat systemd-tmpfiles-clean.timer # /usr/lib/systemd/system/systemd-tmpfiles-clean.timer
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.[Unit]
Description=Daily Cleanup of Temporary Directories
Documentation=man:tmpfiles.d(5) man:systemd-tmpfiles(8)[Timer]
OnBootSec=15min
OnUnitActiveSec=1d# /etc/systemd/system/systemd-tmpfiles-clean.timer.d/override.conf
[Timer]
# reset existing triggers
OnBootSec=
OnUnitActiveSec=
# add new triggers
OnBootSec=15min
OnUnitActiveSec=60min |
I'm trying to change the cleanup interval for Apache PrivateTmp files from the default 30 days to 6 hours. I read that to edit the time intervals, I should set up an override file in /etc/tmpfiles.d/tmp.conf rather than editing /usr/lib/tmpfiles.d/tmp.conf, so I created that file with the following lines:
# override the default cleanup intervals
v /tmp 1777 root root 6h
v /var/tmp 1777 root root 6hNow if I run systemd-tmpfiles --clean, the expected files are removed, so this part is working.
However, /usr/lib/systemd/system/systemd-tmpfiles-clean.timer has OnUnitActiveSec set to 1d. I assume this means my 6 hour cleanup interval will effectively be limited to once per day.
I can change that timer interval to 6h or less, but should I edit this file directly, or create an override file similar to /etc/tmpfiles.d?
Update: this question was marked as a duplicate, but I don't see anything in the linked question about whether I should be using an override file like with the tmp.conf file.
Solution: apparently I can't post this as an answer since the question has been marked as a duplicate. But this is how I created an override file to change the timer interval:
Copy the existing timer file to the corresponding override directory:
sudo cp /usr/lib/systemd/system/systemd-tmpfiles-clean.timer /etc/systemd/system
Edit the new copy (change the 1d value to 1h):
sudo nano /etc/systemd/system/systemd-tmpfiles-clean.timer
Load the new timer file:
sudo systemctl daemon-reload
Confirm that the new timer interval is loaded:
sudo systemctl list-timers
| How to edit the timer for systemd-tmpfiles-clean? |
It seems there is no problem with the Persistent option and suspend. The problem seems to be that Persistent=true only works if the timer has had a chance to trigger at least once, i.e. if LAST is not n/a. But my computer is normally suspended at midnight, so the timer has never triggered.
|
I have created a systemd user timer that expires daily, i.e. at midnight. The problem is that my computer is normally suspended at night. When I wake it up in the morning, I want the timer to trigger, but that doesn't happen. I discovered the Persistent option, but that only helps when the system is powered down, since it triggers expired timers when starting the services. Is there a solution to this other than e.g. running an hourly timer and saving a timestamp to a file somewhere?
Edit 2017-03-17:
I'm using systemd 231 on ubuntu 16.10.
What I want to is to run remind once a day, preferably when I wake up the computer in the morning.
| Systemd timer that expired while suspended |
Add Restart=always to the service unit, so systemd will keep bringing up the service if it crashes.
On a side note you should use OnUnitInactiveSec instead of OnUnitActiveSec.
OnUnitInactiveSec=10s (or 20s) will start the service 10 seconds after it stopped. This way you make sure it doesn't get called twice and possibly avoid banning for DOSing google
|
I have a script that updates my google drive. I made a systemd unit to run this script, and a timer that runs the unit every 10 seconds, which both work. However, when I get disconnected from internet, the script fails and systemd stops running the it even if the internet comes back on. Is there any way I can make systemd keep on running the script, or is there a way to have systemd run the script only if there is an internet connection?
Here are the files
/etc/systemd/system/grive.service:
[Unit]
Description=Syncronize google drive folder[Service]
User=my_name
ExecStart=/home/my_name/bin/update-grive/etc/systemd/system/grive.timer:
[Unit]
Description=Timer for how often to syncronize google drive folder[Timer]
OnUnitActiveSec=10s
OnBootSec=10s[Install]
WantedBy=timers.target/home/my_name/bin/update-grive:
#!/usr/bin/env bash
cd /home/my_name/gdrive
grive | How to run a script every 5 seconds only when connected to internet |
I resolved this problem by converting my 'user' timers into root/system timers.I disabled all of my .service and .timer files, and moved them out of my home directory into /etc/systemd/system.
I added the 'User=' section to each service file, so that my scripts were ran by the regular user and not as root.Now my timers aren't being triggered on system startup and I was also getting problems with sporadic triggering when I logged in via ssh. This has also been solved now that they are under control of the root account but run my scripts are still run as the PID of regular user, which preserves my files' ownership attributes. Problem solved.The OP posted this as an edit to the question, so I reproduced it here.
|
I've been migrating my crontabs to systemd's timer units. They all look similar to this:
.timer file:
[Unit]
Description=timer that uses myjob.service[Timer]
OnCalendar=*-*-* *:00:00
Unit=myjob.service[Install]
WantedBy=timers.target.service file:
[Unit]
Description=Script that runs myjob.sh[Service]
ExecStart=/home/user/myjob.shMy timers work but they also execute on system reboot. I would like my OnCalendar events to only run at the specified times, not whatever random time I reboot the PC. Any ideas?UPDATE:
I resolved this problem by converting my 'user' timers into root/system timers.I disabled all of my .service and .timer files, and moved them out of my home directory into /etc/systemd/system.
I added the 'User=' section to each service file, so that my scripts were ran by the regular user and not as root.Now my timers aren't being triggered on system startup and I was also getting problems with sporadic triggering when I logged in via ssh. This has also been solved now that they are under control of the root account but run my scripts are still run as the PID of regular user, which preserves my files' ownership attributes. Problem solved.
| Prevent systemd timer from running on startup |
To stop all currently running timers, you can simply use:
systemctl stop '*.timer'To restart the timers later, you’ll have to remember which ones were running at the time.
timers=$(systemctl list-units --type=timer --state=active --no-legend | awk '{print $1}')
systemctl stop $timers
# ...
systemctl start $timers(Apparently patterns for units don’t match inactive units, so systemctl start '*.timer' doesn’t work.)
|
I am writing a script that prepares my Linux system for benchmarking. Among other things I want to stop all systemd timer units, and revert this action afterwards.
In short, I need the equivalent of service crond stop/start.
All I have found so far is systemctl list-timers and then manually stop each one, and afterwards manually start each. Do you know of any better, more generic solutions?
| Temporarily stop all systemd timer units |
Update (2022-08-08): A bugfix has been merged now. Hopefully, the following workaround is no longer needed.
Update (2023-01-28): Unfortunately, the bugfix had to be reverted in the 252 release since it caused another regression. Thus, the problem is still open and the workaround below is still relevant.Until the Systemd bug is fixed, I used this workaround to get the timers in sync again:Touch all files with broken timestamps in /var/lib/systemd/timers
Reboot the machineNow, systemctl list-timers shows sane output again.
According to the Arch documentation, deleting the timestamp files should also be safe:If a timer gets out of sync, it may help to delete its stamp-* file in /var/lib/systemd/timers. These are zero length files which mark the last time each timer was run. If deleted, they will be reconstructed on the next start of their timer. |
When I run systemctl list-timers, the last executed dates are far in the future. For example, this is part of the output:
$ systemctl list-timers
NEXT LEFT LAST PASSED UNIT ACTIVATES
Sat 2017-08-19 02:29:16 CEST 6h left Wed 2017-08-16 02:50:57 CEST 2 days ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service
Sun 2092-06-29 22:30:00 CEST 74 years 10 months left Sun 2092-06-29 00:22:17 CEST 74 years 10 months left rsnapshot-daily.timer [emailprotected]
Mon 2092-06-30 00:00:00 CEST 74 years 10 months left Sun 2092-06-29 00:22:17 CEST 74 years 10 months left fstrim.timer fstrim.service
Mon 2092-06-30 00:00:00 CEST 74 years 10 months left Sun 2092-06-29 00:22:17 CEST 74 years 10 months left logrotate.timer logrotate.service
Mon 2092-06-30 00:00:00 CEST 74 years 10 months left Sun 2092-06-29 00:22:17 CEST 74 years 10 months left man-db.timer man-db.serviceWhen I checked my backup, which should be triggered by the rsnapshot-daily.timer job, I noticed that it stopped working about one week ago. Thus, it looks like the systemd timers are partly broken on my system.
I assume the problem will go away if I reboot my machine. Still, I am curious if it is a known problem and whether there any workarounds?
Restarting the timers did not make a difference (e.g., systemctl restart rsnapshot-daily.timer). The last executed dates are still in 2092.
I'm using systemd version 234.11-8 on Arch Linux.
| "systemctl list-timers" shows last executed dates that are far in the future |
You could use ExecStartPost=/bin/systemctl start some-other-service if the Type= is oneshot.
Read about the details in man systemd.service
To review a full list of directions, use man systemd.directives, which lists all the directions and where they are documented.
|
I converted some cron jobs to systemd.timer units and want to send a mail on each job failure and success.
The excellent ArchLinux wiki page provides information about this and the setup runs smoothly on failure. Now I want to add an email notification whenever the unit ran successful, but according to systemd.unit there is no configuration named OnSuccess=.
How to handle this use case?
| systemd run unit on success of another |
You're using an invalid time range. When using BEGIN..END, END must be later than BEGIN. Obviously, 00 is earlier than 05 so 05..00 errors out. You need
OnCalendar=*-*-* 05..23:*:00This will run your script every minute from 05:00 until 23:59. I assume that was your intent. If instead you wanted to run from 05:00 until 0:59 you would use
OnCalendar=*-*-* 00,05..23:*:00 |
I want a script to run minutely, but stop executing it during the nighttime.
I tried
OnCalendar=*-*-* 05..00:*:00but that lead to
Failed to parse calendar specification, ignoring: *-*-* 05..00:*:00
Timer unit lacks value setting. RefusingWhats wrong here?
| Systemd Timer every minute on specific hours (using a range of values) |
I think I figured this out on my own by reading the manual for systemd services (man systemd.service). The ExecStart= option doesn't directly support shell command lines, which I think is why the brace expansion was not being performed as intended. I got everything to work by passing my rsync command to sh -c in the ExecStart= line:
ExecStart=sh -c 'rsync -a --exclude={/dir_a,/dir_b} /home/trevor/test_dir/ /my_ssd/test_dir/'reference:
$ man systemd.service
...
Note that shell command lines are not directly supported. If shell
command lines are to be used, they need to be passed explicitly to a
shell implementation of some kind. Example: ExecStart=sh -c 'dmesg | tac'
... |
summary:
I am trying to set up a systemd timer to regularly backup a directory using the rsync command. I made an rsync command that works when run manually in a terminal, but it doesn't work correctly when run as a systemd timer.
detailed explanation:
As a simple example, I have following directory tree in /home/trevor/test_dir/:
dir_a/
file_a.png
dir_b/
file_b.png
dir_c/
file_c.pngI want to use rsync to copy this directory to my SSD for backup (mounted at /my_ssd/). But I want to exclude the directories dir_a and dir_b. So I run the command
rsync -a --exclude={/dir_a,/dir_b} /home/trevor/test_dir/ /my_ssd/test_dir/This command works when I run it from a terminal: it excludes the directories dir_a and dir_b, but keeps dir_c.
Next, I try to make a systemd service and timer to run that command routinely (note that I determined the following steps mostly from the systemd/Timers page on the Arch Linux Wiki). I make the following service file
/etc/systemd/system/backup_test.service:
[Unit]
Description=systemd backup test[Service]
Type=simple
ExecStart=rsync -a --exclude={/dir_a,/dir_b} /home/trevor/test_dir/ /my_ssd/test_dir/and the following timer file which will run the command every 30 seconds (for example)
/etc/systemd/system/backup_test.timer:
[Unit]
Description=systemd backup test timer[Timer]
OnCalendar=*:*:0/30
Persistent=true[Install]
WantedBy=timers.targetI start the timer using systemctl start backup_test.timer. The timer does run every 30 seconds, but the "exclude" part seems to be ignored, and the entire directory is copied.
debugging attempts:
I tried the rsync command with multiple --exclude options instead of the brace expansion, in other words I used --exclude=/dir_a --exclude=/dir_b instead of --exclude={/dir_a,/dir_b}. This actually made the command work. So I think the problem is that the brace expansion is not being done properly.
Next, I tried to test a simpler command with brace expansion, to see if the brace expansion itself was the problem. So I replaced the rsync command in the systemd service with touch /home/trevor/test{1,2}.txt. This command created a file literally named /home/trevor/test{1,2}.txt. So I'm pretty sure the problem is that the brace expansion is not handled correctly by the systemd service.
| rsync command doesn't work when run as a systemd service |
Yes, using After=, and Requires= is the correct approach for ordering services. You may also want to note that if a service specified in Requires fails, so will your service. From the manpage:
Often, it is a better choice to use Wants= instead of Requires= in order to
achieve a system that is more robust when dealing with failing services. |
Currently, I have this systemd timer (my.timer):
[Unit]
Description=My Timer[Timer]
OnActiveSec=30
Unit=my-subsequent.service[Install]
WantedBy=multi-user.targetThe timer is set to activate upon boot due to: systemctl enable my.timer and systemctl start my.timer.
Upon activation, the timer waits for 30 seconds, then it starts the service my-subsequent.service.
However, instead of having the timer activate upon boot, I would like it to wait for another service (my-preceding.service) to activate upon boot.
So that the chain is: boot > my-preceding.service > my.timer > my-subsequent.service.
How can I accomplish this?Edit:
I tried to find if I can use After= and Requires= in timers, but didn't find anything. This does however seem to work at first glance. Is it an acceptable solution?
[Unit]
Description=My Timer
After=my-preceding.service
Requires=my-preceding.service[Timer]
OnActiveSec=30
Unit=my-subsequent.service[Install]
WantedBy=multi-user.target | Systemd: How to get a timer to run after a required service? |
OnUnitActiveSec binds to the last activation time of break_reminder.service.OnUnitActiveSec=
Defines a timer relative to when the unit the timer unit is activating was last activated.(systemd.timer manpage)
So to reset the left time on break_reminder.timer, you'd need to reset the last activation timestamp of break_reminder.service.
Unfortunately there doesn't seem to be a way to reset this timestamp except by actually starting the service unit. (systemctl set-property isn't able to change the timestamp and it is neither affected by systemctl reset-failed, systemctl clean nor by systemctl daemon-reexec).
|
How can I reset the left time of a user systemd timer?
I have a user systemd service:
[Unit]
Description=Remind to a take break[Service]
ExecStart=/opt/scripts/break_reminder
Environment=PATH=/sbin:/bin:/usr/bin:/usr/sbin:/opt/scripts[Install]
WantedBy=default.targetand a user systemd timer
[Unit]
Description=Remind to a take break[Timer]
OnStartupSec=0min
OnUnitActiveSec=30min[Install]
WantedBy=timers.targetEdit:
Restarting the timer both by restart and stop + start isn't reseting the left time.
$ systemctl --user status break_reminder.timer
● break_reminder.timer - Remind to take break
Loaded: loaded (/home/adam/.config/systemd/user/break_reminder.timer; enabled; vendor pr>
Active: active (waiting) since Sun 2021-05-30 16:19:00 CEST; 3h 48min ago
Trigger: Sun 2021-05-30 20:24:05 CEST; 16min left
Triggers: ● break_reminder.serviceMay 30 16:19:00 archadam systemd[383]: Started Remind to take break.$ systemctl --user restart break_reminder.timer
$ systemctl --user status break_reminder.timer
● break_reminder.timer - Remind to take break
Loaded: loaded (/home/adam/.config/systemd/user/break_reminder.timer; enabled; vendor pr>
Active: active (waiting) since Sun 2021-05-30 20:07:24 CEST; 1s ago
Trigger: Sun 2021-05-30 20:24:05 CEST; 16min left
Triggers: ● break_reminder.serviceMay 30 20:07:24 archadam systemd[383]: Stopping Remind to take break.
May 30 20:07:24 archadam systemd[383]: Started Remind to take break.$ systemctl --user stop break_reminder.timer
$ systemctl --user status break_reminder.timer
○ break_reminder.timer - Remind to take break
Loaded: loaded (/home/adam/.config/systemd/user/break_reminder.timer; enabled; vendor pr>
Active: inactive (dead) since Sun 2021-05-30 20:07:32 CEST; 1s ago
Trigger: n/a
Triggers: ● break_reminder.serviceMay 30 20:07:24 archadam systemd[383]: Stopping Remind to take break.
May 30 20:07:24 archadam systemd[383]: Started Remind to take break.
May 30 20:07:32 archadam systemd[383]: break_reminder.timer: Deactivated successfully.
May 30 20:07:32 archadam systemd[383]: Stopped Remind to take break.$ systemctl --user start break_reminder.timer
$ systemctl --user status break_reminder.timer
● break_reminder.timer - Remind to take break
Loaded: loaded (/home/adam/.config/systemd/user/break_reminder.timer; enabled; vendor pr>
Active: active (waiting) since Sun 2021-05-30 20:07:39 CEST; 2s ago
Trigger: Sun 2021-05-30 20:24:05 CEST; 16min left
Triggers: ● break_reminder.serviceMay 30 20:07:39 archadam systemd[383]: Started Remind to take break. | How to reset left time of user systemd timer |
A quick search for [systemd users] found this answer as the first result for you:The systemd user instance is started after the first login of a user
and killed after the last session of the user is closed. Sometimes it
may be useful to start it right after boot, and keep the systemd user
instance running after the last session closes, for instance to have
some user process running without any open session. Lingering is used
to that effect. Use the following command to enable lingering for
specific user:
# loginctl enable-linger usernameEnable this as a group level does not appear to be supported. Instead, enable it for every member of the group.
|
Are systemd per user systemd-timer running for offline users ? If not, is it possible to allow them to be running for users within a specific group ? Will the target service of the timer be launched correctly as the user it is supposed to run for this way ?
| Run user's systemd timer while they don't have any open session |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.