mount -t devtmpfs
It is also interesting to see that /dev is a filesystem type that can be mounted wherever you want:
mkdir d
sudo mount -t devtmpfs none d
head -c 10 d/random
sudo umount d
CONFIG_DEVTMPFS_MOUNT=y
This option makes the kernel auto-mount devtmpfs on /dev.
drivers/base/Kconfig documents:
config DEVTMPFS_MOUNT
bool "Automount devtmpfs at /dev, after the kernel mounted the rootfs"
depends on DEVTMPFS
help
This will instruct the kernel to automatically mount the
devtmpfs filesystem at /dev, directly after the kernel has
mounted the root filesystem. The behavior can be overridden
with the commandline parameter: devtmpfs.mount=0|1.
This option does not affect initramfs based booting, here
the devtmpfs filesystem always needs to be mounted manually
after the rootfs is mounted.
With this option enabled, it allows to bring up a system in
rescue mode with init=/bin/sh, even when the /dev directory
on the rootfs is completely empty.
file_operations
Finally, you should create your own character device kernel module to see exactly what is going on.
Here is a minimal runnable example: How do character device or character special files work?
The most important step, is setting up the file_operations struct, e.g.:
static const struct file_operations fops = {
.owner = THIS_MODULE,
.read = read,
.open = open,
};
static int myinit(void)
{
major = register_chrdev(0, NAME, &fops);
return 0;
}
which contains function pointers that get called for each file-related system call.
It then becomes obvious that you override those file-related system calls to do whatever you want, and so this is how the kernel implements devices like /dev/zero.
Create /dev entries at automatically without mknod
The final mystery is how the kernel automatically creates /dev entries.
The mechanism can be observed by making a kernel module that does that yourself as shown at: https://stackoverflow.com/questions/5970595/how-to-create-a-device-node-from-the-init-module-code-of-a-linux-kernel-module/45531867#45531867 and comes down to a device_create call.