Answer: A filesystem is a method of organizing and storing data on a storage medium. It provides: a namespace (directory tree with names), metadata storage (permissions, timestamps, ownership), data block management (allocating disk space), and a consistent on-disk format. The Linux VFS (Virtual Filesystem Switch) provides a unified interface across different filesystem types.
Answer: An inode (index node) is a data structure that stores file metadata: file type, permissions, owner UID/GID, size, link count, timestamps (atime, mtime, ctime), and pointers to data blocks. Each file and directory has exactly one inode, identified by an inode number unique within the filesystem. The filename is stored in the directory entry (dentry), not the inode.
Answer: The inode does NOT store the filename(s). Filenames are stored in directory entries that map names to inode numbers. A single inode can have multiple filenames (hard links) pointing to it. Inode also doesn't store the file's path — only the directory hierarchy knows the path.
Answer: At filesystem creation, a fixed number of inodes is allocated (based on block device size and inode ratio). df -i shows inode usage. Running out of inodes means no new files can be created even if disk space is available. tune2fs -l /dev/sda1 | grep inode shows inode configuration.
Answer: The superblock is the filesystem's metadata record — stored at the beginning of the filesystem and at backup locations. Contains: magic number (filesystem type identification), block size, total blocks/inodes, free blocks/inodes, filesystem state (mounted cleanly or dirty), mount time, last fsck time, UUID, and filesystem feature flags. tune2fs -l /dev/sdX reads the superblock.
Answer: ext4 divides the disk into block groups. Each block group has its own: superblock copy (sparse), group descriptor (free blocks, free inodes), block bitmap (which blocks are used), inode bitmap, inode table, and data blocks. This limits the search for free blocks to the current group, improving locality and reducing fragmentation.
Answer: The block size (typically 4KB) is the smallest allocation unit. Small files waste less space with small blocks but large files need more block pointers. Large blocks improve large-file performance but waste space for small files. Set at mkfs time: mkfs.ext4 -b 4096 /dev/sda1. All reads and writes are in block-size multiples.
Answer: VFS is an abstraction layer in the kernel that provides a uniform API (open, read, write, stat, etc.) regardless of the underlying filesystem type. It defines: superblock object, inode object, dentry (directory entry) object, and file object. Each filesystem registers its implementations of these objects. Applications use the same syscalls for ext4, xfs, tmpfs, and NFS.
Answer: The dentry cache (dcache) is an in-memory cache of directory entries (name → inode mappings). Path lookup traverses the dcache before hitting disk. Dentries are kept in memory as long as they're referenced or until memory pressure evicts them. cat /proc/sys/fs/dentry-state shows dentry statistics.
Answer: In-memory cache of inode structures. When a file is opened, its inode is loaded from disk into the inode cache. Subsequent accesses to the same file (by the same or different processes) use the cached inode. Part of the slab allocator. slabtop shows ext4_inode_cache size.
Answer: unlink() removes the directory entry (name → inode mapping). The inode's link count is decremented. If the link count reaches zero AND no process has the file open, the inode is freed and all data blocks are returned to the free block list. If a process has the file open, the data remains accessible until all FDs are closed — this is why deleted files can still use disk space.
Answer: A directory is a special file whose data contains a list of entries, each mapping a name (up to 255 bytes) to an inode number. The directory itself has an inode. Every directory contains . (current directory, same inode as the directory) and .. (parent directory's inode). Creating/deleting files updates the directory's data blocks.
Answer: Journaling writes changes to a log (journal) before applying them to the main filesystem. If the system crashes, the journal is replayed on remount to ensure consistency — no need for full fsck. Without journaling, a crash mid-write can leave the filesystem in an inconsistent state. Ext4 journal modes: ordered (only metadata journaled, data ordered before), writeback (metadata only, less safe), journal (all data journaled, safe but slow).
Answer: Traditional filesystems use block pointers (indirect blocks). ext4 uses extents — a contiguous range of blocks described by (start block, length). A single extent can map up to 128MB. Stored inline in the inode for small files (4 extents fit). Benefits: fewer metadata lookups, better performance for large sequential files, reduced fragmentation.
Answer: Fragmentation occurs when file blocks are scattered across disk instead of being contiguous. Ext4 uses delayed allocation (buffers data in page cache before allocating blocks) and preallocation to minimize fragmentation. Defragment: e4defrag /path/to/file (per-file) or e4defrag / (entire filesystem).
fsync() vs fdatasync() and why do they matter for data durability?Answer: fsync(fd) flushes all dirty file data AND metadata (inode: size, mtime) to the storage device. fdatasync(fd) flushes data and only the metadata required to locate the data (size), skipping non-essential metadata (mtime). fdatasync is faster. Both guarantee data is on stable storage after return. Required for crash-consistent writes in databases.
Answer: Writes go to the page cache (dirty pages) and return immediately to the application. Background writeback threads flush dirty pages to disk. This makes writes appear fast but risks data loss on crash. dirty_expire_centisecs (default 3000 = 30s) and dirty_writeback_centisecs (default 500 = 5s) control writeback timing.
sync(), syncfs(), and fsync()?Answer: sync() requests flushing of all dirty buffers in the entire system — advisory, may return before completion. syncfs(fd) flushes the specific filesystem containing fd — more targeted. fsync(fd) guarantees that the specific file's data and metadata are on stable storage before returning. fsync is the only reliable durability guarantee.
Answer: Block devices (disks, SSDs) transfer data in fixed-size blocks and support random access. They can host regular filesystems (ext4, xfs). Character devices (keyboards, serial ports) transfer data byte-by-byte sequentially. Pseudo-filesystems like /dev contain both types. Block devices benefit from the kernel's block layer (I/O scheduling, buffering).
statvfs() and statfs()?Answer: Both return filesystem statistics (total blocks, free blocks, block size, total inodes, free inodes). statfs() is Linux-specific and returns filesystem type. statvfs() is POSIX-standard and returns ST_RDONLY, ST_NOSUID flags. df uses statvfs() internally.
Answer: ext4 is the default Linux filesystem. Key features: journaling (ordered/writeback/journal modes), extents (contiguous block ranges), delayed allocation, online defragmentation, 48-bit block addressing (1EB volume), large file/directory support (64-bit sizes), dir_index (HTree B-tree for large directories), journal checksums, metadata checksums (with metadata_csum feature).
Answer: XFS is a high-performance 64-bit journaling filesystem optimized for large files and high-throughput workloads. Key features: allocation groups (parallel metadata operations), delayed allocation, B-tree based directory structure, online resize (grow only), xfsrestore/xfsdump for backup, extremely scalable. Use over ext4 for: large files (databases), high-I/O workloads, very large filesystems.
Answer: Btrfs (B-tree filesystem) is a modern CoW (copy-on-write) filesystem with: snapshots (O(1), writable), checksumming of data and metadata, inline compression (zlib/lzo/zstd), RAID support (0/1/10/5/6), subvolumes (independent mountable namespaces), online scrub/balance/resize, and transparent compression. Default on SUSE/Fedora for some use cases.
Answer: ZFS (originally Sun/Oracle) is a combined filesystem + volume manager with: 128-bit addressing, end-to-end data integrity (checksums verified on read), RAID-Z (software RAID with no write hole), CoW snapshots and clones, ARC (adaptive replacement cache), online scrub, and deduplication. On Linux via ZFS-on-Linux (OpenZFS). Popular for storage servers due to its data integrity guarantees.
Answer: tmpfs is a virtual filesystem backed by RAM and swap. It dynamically uses only as much memory as its content requires (unlike a RAM disk which pre-allocates a fixed amount). Data is lost on unmount or reboot. Used for /tmp, /dev/shm, container image layers. mount -t tmpfs -o size=2G tmpfs /mnt/ram.
procfs (/proc)?Answer: procfs is a virtual filesystem (no disk storage) that exposes kernel and process information as files. /proc/<pid>/ contains per-process data; /proc/sys/ exposes kernel parameters. Files are generated on-demand when read. Used by system utilities (ps, top, lsof) to get process information without special privileges or syscalls.
sysfs (/sys)?Answer: sysfs exports the kernel's object model (devices, drivers, buses) as a hierarchical virtual filesystem. Each directory represents a kernel object (device, driver, class). Files represent attributes (read/write). Used by udev for device events, and for manual device configuration (e.g., /sys/class/net/eth0/speed).
devtmpfs and how does /dev work?Answer: devtmpfs is a virtual filesystem auto-populated by the kernel at boot with device nodes for all registered devices. udev (or mdev) then applies rules to rename devices, set permissions, and create symlinks (e.g., /dev/disk/by-uuid/). /dev/null, /dev/zero, /dev/random are pseudo-devices managed here.
debugfs (not debugfs the tool)?Answer: debugfs (CONFIG_DEBUG_FS) is a virtual filesystem (/sys/kernel/debug/) exposing kernel debugging information: ftrace, perf events, block tracing, and driver-specific debug data. Access restricted to root. Not related to the debugfs ext2/3/4 debugging tool.
overlayfs and how does it work?Answer: OverlayFS merges two directory trees: a read-only lowerdir and a writable upperdir, presenting a unified view. Reads: check upperdir first (copy-up), then lowerdir. Writes: copy the file from lower to upper on first write (copy-on-write). Deletions: create whiteout files in upper. Used by Docker, Podman, and container runtimes for layered images.
Answer: NFS (Network Filesystem) allows mounting remote directories over a network. Server exports directories (/etc/exports). Client mounts: mount -t nfs4 server:/export /mnt. Data is transferred via RPC over TCP/UDP. NFSv4 adds stateful connections, strong security (Kerberos), and compound operations. NFSv3 is stateless (no locking in protocol).
Answer: FUSE allows implementing filesystems in user-space programs rather than kernel modules. The kernel FUSE driver forwards VFS calls to the FUSE daemon via /dev/fuse. Examples: SSHFS (SSH as filesystem), S3FS (S3 as filesystem), GlusterFS, CephFS FUSE client. Slower than kernel filesystems (extra copy, context switches) but much easier to develop.
Answer: A hard link is a directory entry that maps a filename directly to an inode number. Multiple directory entries can point to the same inode. All hard links are equal — there is no "original" file. The inode stores a link count; data is freed only when the count reaches zero (all hard links deleted). Hard links share the same inode number: ls -li shows it.
Answer: A symbolic (soft) link is a special file whose data is a path string pointing to another file or directory. When the kernel traverses the path, it follows symlinks transparently (up to MAXSYMLINKS=40 hops to prevent loops). Symlinks have their own inode. The target path can be relative or absolute.
| Property | Hard Link | Symlink |
|---|---|---|
| Inode | Same inode as target | Own inode |
| Cross-filesystem | No (same device only) | Yes |
| Link directories | No (usually) | Yes |
| If target deleted | Data survives | Dangling link |
Shows in ls -l | No indicator | -> arrow |
stat size | File size | Length of path string |
| Performance | No extra lookup | One extra path lookup |
xxxxxxxxxxln source.txt link.txt # hard linkls -li source.txt link.txt # same inode numberstat source.txt # link count = 2xxxxxxxxxxln -s /path/to/target link_name # absolute pathln -s ../relative/target link_name # relative pathln -s /usr/bin/python3 /usr/local/bin/python # common usels -la link_name # shows -> targetAnswer: The symlink becomes a "dangling" or "broken" symlink. The link file still exists but accessing it returns ENOENT (No such file or directory). You can detect dangling symlinks:
xxxxxxxxxxfind /path -xtype l # find broken symlinksls -la symlink # shows -> nonexistentfile symlink # "broken symbolic link"readlink() and readlink command?xxxxxxxxxxreadlink -f /path/symlink # resolve full canonical pathreadlink symlink # show immediate targetrealpath symlink # same as readlink -freadlink(2) syscall reads the symlink's content (the path string) without following it.
Answer: Normally no — hard-linking directories is disallowed to prevent filesystem loops and make traversal predictable. Root can do it with ln but this is strongly discouraged. Exception: every directory already has two hard links — the entry in its parent directory and the . entry within itself. Subdirectories add another link via ...
lstat() vs stat()?Answer: stat(path) follows symlinks — returns info about the target file. lstat(path) does NOT follow symlinks — returns info about the symlink itself (type = S_IFLNK, size = path string length). Use lstat() when you want to check if a path IS a symlink.
Answer: An absolute symlink (/usr/lib/python3.10) works from anywhere but breaks if the prefix changes. A relative symlink (../lib/python3.10) is resolved relative to the symlink's directory — useful when the symlink and target will be moved together (e.g., in a --prefix install tree). For system-wide symlinks, absolute is typically safer.
unlink() work for symlinks?Answer: unlink() removes the directory entry for the symlink itself (the symlink file), not the target it points to. The symlink's inode is freed (link count 0). The target is unaffected. This is the correct behavior — use rm on a symlink to remove the link, not the target.
Answer: A symlink loop occurs when symlinks eventually point back to themselves (A → B → C → A). The kernel tracks the number of symlink traversals per open() call and returns ELOOP after MAXSYMLINKS (typically 40) hops. errno = ELOOP: Too many levels of symbolic links.
O_NOFOLLOW flag?Answer: open(path, O_NOFOLLOW) returns ELOOP if the final component of the path is a symlink — it does NOT follow it. Used in security-sensitive code to prevent TOCTOU (Time-of-Check-to-Time-of-Use) attacks where an attacker replaces a legitimate file with a symlink between the check and the open.
mount() syscall?xxxxxxxxxxmount(source, target, filesystemtype, mountflags, data);// Example:mount("/dev/sdb1", "/mnt/data", "ext4", MS_RELATIME, NULL);source: device or none for virtual filesystems. target: existing directory. mountflags: MS_RDONLY, MS_NOSUID, MS_NODEV, MS_NOEXEC, MS_REMOUNT, MS_BIND.
xxxxxxxxxxmount --bind /source/dir /dest/dir# In /etc/fstab:/source/dir /dest/dir none bind 0 0A bind mount makes a directory or file visible at another point in the filesystem tree. Same content, same inode, accessible at two paths. Used in containers to mount host directories, and by systemd for sandboxing service filesystems.
xxxxxxxxxxmount --rbind /source /dest # also bind-mounts all sub-mountsmount --make-rprivate /dest # propagation type--rbind includes all sub-mount-points within the source. Necessary when the source has sub-mounts you also need visible at the destination.
Answer: Controls how mount/umount events propagate between peer groups:
shared: events propagate both ways.
slave: events propagate from master to slave, not reverse.
private: no propagation.
unbindable: cannot be bind-mounted.
Set with: mount --make-shared /mnt, mount --make-private /mnt. Containers use private propagation to isolate their namespace.
/etc/fstab format?xxxxxxxxxx# device mountpoint fstype options dump passUUID=abc123 / ext4 defaults,errors=remount-ro 0 1UUID=def456 /boot ext4 defaults 0 2UUID=789abc /home xfs defaults,noatime 0 2tmpfs /tmp tmpfs nodev,nosuid,size=2G 0 0192.168.1.1:/ /nfs nfs4 defaults,_netdev 0 0
dump: 0 = don't backup, 1 = backup with dump. pass: 0 = no fsck, 1 = root (first), 2 = others (after root).
Answer:
nodev — don't interpret device files (no creating block/char devices that bypass permissions).
nosuid — ignore setuid/setgid bits (prevents privilege escalation from mounted media).
noexec — don't allow executing binaries from this mount.
ro — read-only.
Common for: /tmp (nodev,nosuid,noexec), /home (nosuid,nodev), USB media.
umount and what causes "device is busy"?Answer: umount /mnt detaches the filesystem. Fails with EBUSY if any process has open files or a current directory within the mount. Debug:
xxxxxxxxxxlsof +D /mnt # what files are openfuser -vm /mnt # what processes use the mountumount -l /mnt # lazy umount: detach immediately, clean up when last user exitsfindmnt and how is it used?xxxxxxxxxxfindmnt # tree of all mountsfindmnt /dev/sda1 # find mount for devicefindmnt -t tmpfs # find all tmpfs mountsfindmnt -O noexec # find mounts with noexec optionfindmnt --verify /etc/fstab # verify fstab entriesautofs and why is it useful?Answer: autofs automatically mounts filesystems on demand (when accessed) and unmounts them after idle timeout. Useful for NFS home directories (mount on login), removable media, and reducing load from unused mounts. Managed by the autofs daemon with map files. mount.nfs is called transparently when the mount point is accessed.
systemd-mount and .mount units?Answer: systemd .mount unit files define mounts managed by systemd. The filename encodes the mount point (e.g., home.mount for /home). Dependencies, ordering, and conditions can be specified. systemd-mount command creates transient mount units. .automount units implement automount behavior.
Answer:
read (r): can list directory contents (ls).
write (w): can create, delete, or rename entries within the directory (requires execute also).
execute (x): can traverse the directory (cd into it, access files within by name) even without read.
Lacking x on any directory in a path prevents accessing anything below it.
chmod 000 file do to root?Answer: Root ignores read/write permissions on files (but execute is different — root needs at least one execute bit set to execute a script/binary). Root CAN always read/write any file regardless of permissions. SELinux or capabilities may further restrict even root.
Answer: umask is a process attribute that masks out permission bits when creating files. Default: 022 (removes write for group and other). New files: 666 & ~022 = 644. New directories: 777 & ~022 = 755.
xxxxxxxxxxumask # show current umaskumask 027 # set (removes write for group, all for other)Answer: POSIX ACLs allow per-user and per-group permissions beyond the owner/group/other model:
xxxxxxxxxxsetfacl -m u:alice:rwx /path/file # give alice rwxsetfacl -m g:devs:rx /path/dir # give devs group r-xgetfacl /path/file # show ACLssetfacl -x u:alice /path/file # remove Alice's ACLsetfacl -d -m g:devs:rwx /path/dir # default ACL for new filesStored in extended attributes. ls -la shows + after permissions when ACLs are present.
Answer: When ACLs are present, the mask entry limits the effective permissions of named users and groups (but NOT the file owner or other). Example: if mask: r-x, a user with rwx in their ACL entry effectively only has r-x. Set by setfacl -m m::rx /path.
Answer: DAC (Discretionary Access Control) = standard Unix permissions — controlled by the file owner. SELinux (Security-Enhanced Linux) implements MAC (Mandatory Access Control) — policy enforced by the system regardless of user/owner wishes. Every process and file has a security context (type:role:domain). Policy defines which domains can access which types. ls -Z and ps -Z show contexts.
xxxxxxxxxxsetfattr -n user.comment -v "my note" /path/file # setgetfattr -n user.comment /path/file # getgetfattr -d /path/file # show allExtended attributes store arbitrary name-value pairs with files. Namespaces: user. (any user), trusted. (root), security. (SELinux, capabilities), system. (ACLs, POSIX). Stored in inode or separate blocks.
xxxxxxxxxxgetcap /usr/bin/ping # show file capabilitiessetcap cap_net_raw+ep /usr/bin/ping # set: e=effective, p=permittedFile capabilities allow a non-root executable to gain specific capabilities when run, replacing setuid root. cap_net_raw for ping, cap_net_bind_service for binding to ports < 1024. Stored in security.capability xattr.
Answer: On modern Linux, the sticky bit on a regular file has no standard effect. Historically on older Unix systems, it would keep the program text in swap space. On directories (the meaningful modern use): the sticky bit prevents users from deleting or renaming files they don't own (even if they have write permission on the directory). Used on /tmp and shared directories.
chattr and lsattr?xxxxxxxxxxchattr +i file # immutable: no write, delete, rename even by rootchattr +a file # append-only: can only appendchattr -i file # remove immutablelsattr file # show attributeschattr sets Linux-specific file attributes stored in the filesystem. Useful for protecting critical config files. Requires root. +i protects log files from accidental deletion.
Answer: File data read from disk is cached in the page cache (RAM). Subsequent reads return cached data (no disk I/O). Writes go to cache first (dirty pages), flushed by writeback threads. The page cache uses most available RAM; memory pressure causes eviction. echo 3 > /proc/sys/vm/drop_caches frees pagecache, dentries, and inodes (for testing — never in production).
Answer: The kernel (and storage devices) predict sequential access patterns and proactively read ahead of the current position. vm.readahead_kb and per-device read_ahead_kb control this. For sequential large-file reads, read-ahead dramatically improves throughput by keeping the page cache filled before the application needs the data.
O_DIRECT and when should you use it?Answer: O_DIRECT bypasses the page cache — I/O goes directly between user buffer and disk (via DMA). Requirements: buffer, offset, and length must be aligned to block size (512 or 4096 bytes). Use when: application manages its own cache (PostgreSQL, MySQL, Redis), prevents double-buffering, for benchmarking raw storage performance.
Answer: The I/O scheduler (elevator) orders pending I/O requests to optimize disk head movement (HDDs) or parallel submission (SSDs). Schedulers: mq-deadline (deadline guarantee, good for databases), kyber (low-latency, good for SSDs/NVMe), bfq (budget fair queuing, good for desktop/audio). Check: cat /sys/block/sda/queue/scheduler. Set: echo mq-deadline > /sys/block/sda/queue/scheduler.
Answer: NVMe (Non-Volatile Memory Express) uses PCIe with up to 64K queues with up to 64K entries each — massive parallelism. SATA/AHCI: 1 queue, 32 entries. Linux uses the blk-mq (multi-queue) block layer for NVMe. noop/none scheduler is typically best for NVMe (hardware manages queuing). nvme list shows NVMe devices; nvme smart-log shows health.
fallocate() and when is it used?xxxxxxxxxxfallocate -l 10G file.img # pre-allocate 10GB (fast, no zeros)fallocate -d file # punch holes (FALLOC_FL_PUNCH_HOLE)fallocate(FALLOC_FL_KEEP_SIZE) pre-allocates disk blocks without changing file size. Avoids fragmentation and guarantees space availability. Used by databases (PostgreSQL WAL), VMs (disk images), and torrent clients.
truncate() vs fallocate()?Answer: truncate(fd, size) sets file size — if extending, creates a sparse file (virtual space, no real blocks allocated). If shrinking, truncates data. fallocate() actually allocates physical blocks without writing data (or removes them with PUNCH_HOLE). Sparse files are great for thin provisioning but may cause ENOSPC surprises when finally written.
Answer: A sparse file has "holes" — regions where lseek() was used to skip past data without writing. The filesystem doesn't allocate blocks for holes; reads return zeros. ls -lh shows the logical size; du -sh shows the actual disk usage. cp --sparse=auto preserves sparseness. Common for VM disk images and database pre-allocation.
mmap() vs read() for file I/O performance?Answer: Both use the page cache — no real throughput difference for large sequential I/O. mmap() advantages: random access without seek overhead, zero-copy for read-only (no user buffer needed), enables shared memory between processes. read() advantages: simpler error handling, better for streaming/sequential (kernel can do large-block reads), works on more file types (pipes, sockets). For large databases: typically O_DIRECT + pread() is preferred.
aio (POSIX async I/O) vs io_uring?Answer: POSIX AIO (aio_read, aio_write): implemented in user space (glibc creates threads) — not truly kernel-async, high overhead. Linux AIO (io_submit): true kernel async but limited (only works with O_DIRECT, no fixed buffers, syscall per operation). io_uring (Linux 5.1+): true kernel async with ring buffers — supports any I/O type, batching, fixed buffers/files, and can operate with zero syscalls for pre-registered operations.
xxxxxxxxxx# Server /etc/exports:/data client1(rw,sync,no_subtree_check) 192.168.1.0/24(ro)exportfs -ra # reload exportsshowmount -e # show exportsOptions: rw/ro, sync (reply after write to disk), async (reply before disk write — faster, risk of data loss), no_root_squash (allow root access from client), subtree_check/no_subtree_check.
xxxxxxxxxxmount -t nfs4 server:/export /mnt/nfs# With options:mount -t nfs4 -o rsize=1048576,wsize=1048576,timeo=14,intr server:/export /mnt# In /etc/fstab:server:/export /mnt/nfs nfs4 _netdev,auto 0 0_netdev: wait for network. timeo: NFS timeout (tenths of seconds). rsize/wsize: read/write block size.
Answer: NFSv3: stateless (server doesn't track open files), UDP or TCP, separate mount protocol (mountd), no built-in locking (separate lockd), AUTH_SYS (UID/GID) security. NFSv4: stateful (server knows about open files), TCP only, single protocol (no mountd/portmap), integrated locking, compound operations (reduces round-trips), Kerberos support (GSSAPI), better firewalling (single port 2049).
Answer: CIFS (Common Internet File System, now SMB3) is Microsoft's network filesystem protocol, used for Windows shares. NFS is Unix/POSIX-native. On Linux: mount -t cifs //server/share /mnt -o username=user,password=pass. For large deployments, SMB3 has better Windows integration, while NFS is better for Unix/Linux environments.
xxxxxxxxxxnfsstat -c # client-side NFS statisticsmountstats # per-mount detailed statsnfsiostat 1 # per-mount I/O per secondcat /proc/net/rpc/nfs # raw RPC statstcpdump -i eth0 port 2049 # capture NFS trafficfsck and when should you run it?Answer: fsck (filesystem consistency check) verifies and repairs filesystem inconsistencies. It should be run on an unmounted filesystem (or remounted read-only). Auto-run on boot if filesystem was not cleanly unmounted or if mount count/interval exceeded (ext4). Manual:
xxxxxxxxxxfsck -n /dev/sda1 # check only, no repairsfsck -y /dev/sda1 # fix all errors automaticallye2fsck -f /dev/sda1 # force check even if cleandumpe2fs used for?xxxxxxxxxxdumpe2fs /dev/sda1 | head -100 # superblock + block group detailsdumpe2fs -h /dev/sda1 # superblock onlyShows: filesystem creation date, last mount time, UUID, journal info, block groups, inode/block counts.
debugfs (ext2/3/4 tool)?xxxxxxxxxxdebugfs /dev/sda1debugfs> stat <inode_number> # show inode detailsdebugfs> ls /lost+found # list lost+founddebugfs> dump <inode> /tmp/recovered # extract inode datadebugfs> lsdel # list deleted inodes (for recovery)Interactive tool for low-level ext2/3/4 inspection and recovery. Use with care — can directly modify filesystem.
tune2fs and what can it do?xxxxxxxxxxtune2fs -l /dev/sda1 # show superblock infotune2fs -c 30 /dev/sda1 # set max mount count before fscktune2fs -i 1m /dev/sda1 # set check interval (1 month)tune2fs -L "my-disk" /dev/sda1 # set volume labeltune2fs -U random /dev/sda1 # generate new UUIDtune2fs -m 5 /dev/sda1 # reserved block percentage (default 5%)tune2fs -O dir_index /dev/sda1 # enable HTree directoriese2fsck -p vs e2fsck -y?Answer: e2fsck -p: automatically fix problems that can be safely repaired without human intervention (passive/auto fix). e2fsck -y: answer "yes" to all questions — more aggressive, may make changes that lose data in edge cases. Use -p for automated boot-time checks; -y only when you understand the implications.
xfs_repair?xxxxxxxxxxxfs_repair /dev/sdb1 # repair XFS filesystem (must be unmounted)xfs_repair -n /dev/sdb1 # check only, no repairsxfs_info /dev/sdb1 # show XFS filesystem infoxfs_db -c "sb 0" -c "p" /dev/sdb1 # superblock dumpXFS equivalent of e2fsck. Requires unmounted or read-only mounted filesystem.
lost+found directory?Answer: lost+found exists at the root of each ext2/3/4 filesystem. When fsck finds orphaned inodes (data blocks without a directory entry — e.g., from a crash), it reconnects them here as numeric filenames (the inode number). Pre-allocated by mke2fs to have space for fsck to use.
Answer:
xxxxxxxxxx# Method 1: debugfsdebugfs /dev/sda1> lsdel # list recently deleted inodes> dump <inode> /tmp/recovered# Method 2: extundeleteextundelete /dev/sda1 --recover-all --output-dir /tmp/recovered# Method 3: photorec (file carving, ignores filesystem)photorec /dev/sda1Note: If data blocks have been overwritten (new files created), recovery may fail. Unmount immediately after deletion for best results.
xxxxxxxxxx# Ext4 (online resize supported for growth):lvextend -L +10G /dev/vg0/data && resize2fs /dev/vg0/data# XFS (online grow only):xfs_growfs /mnt/data# Shrinking (offline only):umount /mnt/datae2fsck -f /dev/vg0/dataresize2fs /dev/vg0/data 20Glvreduce -L 20G /dev/vg0/databadblocks and when do you use it?xxxxxxxxxxbadblocks -v /dev/sda1 # non-destructive read-only scanbadblocks -w /dev/sda1 # destructive write test (ERASES DATA)e2fsck -c /dev/sda1 # run badblocks and mark bad blocksTests for physical bad sectors on a disk. On modern drives, the drive firmware handles bad sector remapping internally; badblocks primarily catches firmware failures.
ext3 and ext4?Answer: ext4 adds: extents (vs. indirect block maps), 48-bit block addressing (1EB vs 16TB), multiple block allocation, delayed allocation, persistent preallocation, journal checksums, larger timestamps (2446 AD instead of 2038), online defragmentation, HTree B-tree for large directories, metadata checksums. ext4 can mount ext3 filesystems (backward compatible).
noatime and why is it often used?Answer: Every file read updates the access time (atime) in the inode — causing a write for every read. noatime mount option disables atime updates, significantly reducing I/O for read-heavy workloads. relatime (default since kernel 2.6.30) is a compromise: updates atime only if older than mtime or ctime, or more than 24h old. strictatime always updates (rarely needed).
lazytime mount option?Answer: lazytime defers inode timestamp updates to memory only (dirty inode), writing to disk only when: the inode needs to be written anyway (for other reasons), the file is explicitly synced, or after 24 hours. Reduces inode write traffic (especially helpful for rotational media). Part of ext4 and other modern filesystems.
xxxxxxxxxxe4defrag -c /path/to/file # check fragmentation scoree4defrag /path/to/file # defragment a filee4defrag / # defragment entire filesystemCan run on a live, mounted filesystem. Re-arranges blocks to make files contiguous. May be needed after heavy write workloads that created fragmentation.
data=journal ext4 mount mode?Answer: data=journal journals all file data (not just metadata) in the ext4 journal. Ensures full data consistency after crash — no data loss. Significant performance overhead (all writes go to journal then data area). Used for critical databases where any data loss is unacceptable. Other modes: data=ordered (default, data written before metadata commit), data=writeback (fastest, metadata journaled but data may be stale after crash).
errors=remount-ro ext4 mount option?Answer: When ext4 encounters a fatal filesystem error, it automatically remounts the filesystem read-only to prevent further corruption. Alternative: errors=continue (log and continue — risky), errors=panic (kernel panic — for critical systems where you prefer down over corrupt). Default for root filesystem.
Answer: By default, ext4 reserves 5% of blocks for root processes. This ensures root can always log in and fix problems even when the filesystem appears full to regular users. Change with tune2fs -m 1 /dev/sda1. For large filesystems, 5% can be a lot (5% of 1TB = 50GB wasted).
xfs_quota and how does it work?xxxxxxxxxxmount -o uquota,gquota /dev/sdb1 /mnt # mount with quotasxfs_quota -x -c 'limit -u bsoft=5g bhard=6g isoft=1000 ihard=1100 alice' /mntxfs_quota -x -c 'report -h' /mnt # show quota usageXFS has integrated quota management. Supports user, group, and project (directory tree) quotas.
e2label and xfs_admin -L?xxxxxxxxxxe2label /dev/sda1 # show ext4 labele2label /dev/sda1 "my-disk" # set labelxfs_admin -L "data-disk" /dev/sdb1 # set XFS labelVolume labels allow mounting by label (LABEL=my-disk) instead of device path — more stable across reboots when device ordering may change.
discard/TRIM and how does it benefit SSDs?Answer: When files are deleted, the filesystem can inform the SSD about freed blocks via TRIM (DISCARD in the block layer). The SSD firmware uses this to pre-erase blocks, maintaining write performance. Two methods: discard mount option (online TRIM — every unlink triggers discard) or periodic fstrim -v / via systemd timer (recommended — less I/O overhead). NVMe natively supports async discard.
btrfs subvolume and snapshot?xxxxxxxxxxbtrfs subvolume create /data/subvol1 # create subvolumebtrfs subvolume snapshot /data/subvol1 /data/snap1 # snapshotbtrfs subvolume list /data # list subvolumesbtrfs subvolume delete /data/snap1 # delete snapshotSubvolumes are independent filesystem trees within a Btrfs volume. Snapshots are instant (O(1) CoW) and can be writable or read-only. Used for container image layers, backup checkpoints.
xxxxxxxxxxbtrfs send /data/snapshot1 | btrfs receive /backup/btrfs send -p /data/snapshot1 /data/snapshot2 | btrfs receive /backup/ # incrementalbtrfs send generates a binary stream of changes; btrfs receive applies it to another Btrfs filesystem. Enables efficient incremental backups by sending only changes between snapshots.
fstab's nofail option?Answer: nofail allows the system to boot even if the filesystem fails to mount. Without it, a missing/failing mount causes a boot error and drops into emergency mode. Useful for: optional external drives, NFS mounts (_netdev + nofail), secondary data disks.
xxxxxxxxxx# Mount with quota options:mount -o usrquota,grpquota /dev/sda2 /home# Create quota files:quotacheck -cug /home# Enable:quotaon /home# Set limits:edquota -u username # interactivesetquota -u username 5G 6G 1000 1100 /home # non-interactive# Report:repquota -aAnswer: Soft limit: the user can exceed this for a grace period (default 7 days). Hard limit: absolute maximum — cannot be exceeded. Soft limit warns without immediately preventing writes; hard limit enforces strictly. Set both: bsoft=5G bhard=6G.
coalesce_request in the block layer?Answer: When consecutive block I/O requests are adjacent on disk, the block layer merges them into a single larger request. Reduces overhead (one DMA transaction instead of many). queue/max_sectors_kb limits the maximum merged request size. Important for sequential I/O performance.
blkid and when is it used?xxxxxxxxxxblkid # show all block devices with UUID/type/labelblkid /dev/sda1 # specific deviceblkid -o value -s UUID /dev/sda1 # just the UUIDReads filesystem metadata (UUID, type, label) from block devices. Used in /etc/fstab (UUID references), system scripts, and device detection.
parted and how does it differ from fdisk?Answer: parted supports both MBR and GPT partition tables, can resize partitions, and is scriptable. fdisk is simpler, primarily for MBR (though fdisk on modern Linux also supports GPT). gdisk is a GPT-specific tool. parted is preferred for large disks (> 2TB requires GPT).
mkfs.ext4 options for HDD vs SSD?xxxxxxxxxx# SSD: disable journal for less write amplification (if you accept the risk):mkfs.ext4 -O ^has_journal /dev/sda1# Or use discard at mount time and periodic fstrim# SSD: set stride/stripe for RAID alignmentmkfs.ext4 -E stride=128,stripe-width=512 /dev/sda1fscrypt/ext4 encryption)?Answer: fscrypt provides per-directory or per-file encryption at the filesystem level (ext4, f2fs, ubifs). Unlike full-disk encryption (LUKS), individual directories can have different keys. Files are encrypted at rest; the key unlocks access. Used in Android (internal storage), multi-user Linux systems.
xxxxxxxxxxtune2fs -O encrypt /dev/sda1 # enable encrypt featurefscrypt setup /mnt # initialize fscryptfscrypt encrypt /mnt/private/ # encrypt directoryxxxxxxxxxx# Sequential write:dd if=/dev/zero of=/mnt/test bs=1M count=1024 conv=fdatasync# Sequential read:dd if=/mnt/test of=/dev/null bs=1M# Random I/O:fio --name=randread --ioengine=libaio --iodepth=16 --rw=randread \ --bs=4k --size=1G --numjobs=4 --filename=/mnt/testfio and why is it used for storage benchmarking?Answer: fio (Flexible I/O Tester) is the standard tool for storage performance testing. Supports: multiple I/O engines (libaio, io_uring, sync, mmap), various access patterns (sequential/random, read/write/randmix), queue depths, block sizes, multiple jobs. Produces IOPS, throughput (BW), and latency statistics.
Answer: Queue depth = number of outstanding I/O requests submitted to the device without waiting for completion. HDDs: deeper queue allows elevator scheduling (NCQ). SSDs/NVMe: highly parallel internally, benefit greatly from deeper queues (32-128). Linux default queue depth: cat /sys/block/sda/queue/nr_requests. fio --iodepth=32 tests with depth 32.
ionice and how does it affect filesystem I/O?xxxxxxxxxxionice -c1 -n4 ./program # real-time I/O, priority 4ionice -c2 -n7 ./program # best-effort, low priorityionice -c3 -p 1234 # idle: only run when no other I/OUses the CFQ/BFQ I/O scheduler's class-based prioritization. Class 1 (real-time), Class 2 (best-effort), Class 3 (idle). Analogous to CPU nice values but for I/O.
blockdev used for?xxxxxxxxxxblockdev --getbsz /dev/sda # get block sizeblockdev --setro /dev/sda # set read-onlyblockdev --setrw /dev/sda # set read-writeblockdev --flushbufs /dev/sda # flush buffersblockdev --getsz /dev/sda # size in 512-byte sectorshdparm used for?xxxxxxxxxxhdparm -I /dev/sda # drive info (identity, features)hdparm -Tt /dev/sda # benchmark cached reads and disk readshdparm -W /dev/sda # show/set write cachehdparm -a /dev/sda # get/set read-ahead sectorsxxxxxxxxxxe2fsck -n /dev/sda1 # reports fragmentatione4defrag -c /path # fragmentation score for ext4filefrag -v /path/to/file # show extent map for a filexfs_db -c "frag -f" /dev/sdb1 # XFS fragmentation reportHigh fragmentation = many non-contiguous extents per file → more disk seeks → worse read performance.
dm-cache and bcache?Answer: Both use a fast SSD to cache a slow HDD:
bcache: sets up a bcache device; SSD is the cache device, HDD is the backing device. Transparent to upper layers. Writeback or writethrough mode.
dm-cache: device mapper target; more flexible, supports multiple caching policies (smq, mq). Used by LVM thin provisioning with caching. Both improve mixed random/sequential I/O patterns where the hot working set fits on the SSD.
lvmcache and how do you set it up?xxxxxxxxxxpvcreate /dev/ssd /dev/hddvgcreate myvg /dev/ssd /dev/hddlvcreate -L 50G -n slow myvg /dev/hddlvcreate -L 10G -n fast myvg /dev/ssdlvconvert --type cache --cachepool myvg/fast myvg/slow/proc/sys/vm/dirty_ratio and dirty_background_ratio?Answer:
dirty_background_ratio (default 10%): when dirty pages exceed this % of RAM, background writeback starts.
dirty_ratio (default 20%): when dirty pages exceed this, processes are throttled — they must do I/O themselves.
For write-heavy workloads, lower these to write more frequently (prevent sudden large flushes). For latency-sensitive: lower dirty_background_ratio.
openat() and why is it preferred over open()?Answer: openat(dirfd, path, flags) opens a file relative to a directory FD rather than CWD. Advantages: race-free path operations (no TOCTOU between stat and open), works correctly in multi-threaded code (CWD is process-global), essential for filesystem traversal. Use with O_NOFOLLOW for symlink-safe operations.
linkat() and symlinkat()?Answer: linkat(olddirfd, oldpath, newdirfd, newpath, flags) creates a hard link with directory FDs for both paths — race-free. symlinkat(target, dirfd, linkpath) creates a symlink relative to a directory FD. Part of the *at() syscall family for race-free filesystem operations.
renameat() and when should you use it over rename()?Answer: renameat(olddirfd, oldpath, newdirfd, newpath) renames/moves files using directory FDs instead of CWD. Race-free, correct in multi-threaded environments. rename() uses the process's CWD which is global and can be changed by another thread.
Answer: A mount point is a directory that serves as the attachment point for a filesystem. Path resolution crosses mount points transparently. .. from a mount root returns to the parent filesystem's mount point directory. stat and statfs can distinguish if two paths are on the same filesystem (same st_dev).
chdir() vs fchdir()?Answer: chdir(path) changes the process's working directory by path (follows symlinks, requires execute permission on each component). fchdir(dirfd) changes to a directory already opened as a file descriptor — faster and more secure (no TOCTOU, works even if the path was moved). Used in file servers for efficient directory traversal.
xxxxxxxxxxstat /path/to/file | grep Links # "Links: N"ls -l /path/to/file # link count in 2nd columnfind / -inum <inode_number> 2>/dev/null # find all hard linksrename() and renameat2() with RENAME_NOREPLACE?Answer: rename(old, new) atomically replaces new if it exists. renameat2(AT_FDCWD, old, AT_FDCWD, new, RENAME_NOREPLACE) fails with EEXIST if new already exists — useful when you want to atomically create a file only if it doesn't already exist (like O_EXCL for renames).
cp -a differ from cp?xxxxxxxxxxcp file dest # copy content onlycp -a file dest # copy with permissions, timestamps, symlinks, recursioncp -p file dest # preserve timestamps, permissions, ownershipcp --reflink=auto file dest # CoW copy on Btrfs/XFS (instant, shares blocks)--reflink and how does it work?Answer: cp --reflink=auto creates a CoW (copy-on-write) clone using the filesystem's extent sharing (Btrfs, XFS with reflinks enabled). The copy is instantaneous and uses no additional space until one version is modified. Modified pages get their own copy. Like a snapshot for a single file.
rsync's -H flag?Answer: rsync -H preserves hard links. Without -H, rsync copies each hard-linked file as a separate copy (losing the hard link relationship). -H detects files with the same inode on the source and creates corresponding hard links on the destination.
Answer: A race condition where a privileged operation checks a condition (e.g., access() to verify file is safe) and then uses the path (e.g., open()) — in between, an attacker replaces the path with a symlink to a sensitive file. Fix: use O_NOFOLLOW, openat() with a directory FD, or check after opening (fstat() instead of stat()).
/proc/sys/fs/protected_symlinks?Answer: When set to 1 (default in modern kernels): symlink following is restricted in world-writable sticky directories (like /tmp). A symlink can only be followed if: the follower is the symlink owner, or the directory owner matches the symlink owner. Prevents symlink-based TOCTOU attacks in shared directories.
/proc/sys/fs/protected_hardlinks?Answer: When enabled (default 1): hard links can only be created if the creator is the file owner, or has read+write access to the file. Prevents privilege escalation via hard links to setuid files (creating a hard link in /tmp to a setuid binary then waiting for a privileged operation on it).
nosuid mount option and why is it important?Answer: Prevents setuid/setgid bits from having effect on executables within the filesystem. Critical for: removable media (USB drives), world-writable directories, home directories. An attacker who can write to a filesystem without nosuid could create a setuid root binary to escalate privileges.
xxxxxxxxxx# AIDE (Advanced Intrusion Detection Environment):aide --init # create baseline databaseaide --check # check against baseline# Tripwire: similar tool# dm-verity: kernel-level block integrity (Android, verified boot)Detects unauthorized modifications to files by comparing against a cryptographic hash baseline.
stat output and what does each field mean?xxxxxxxxxxstat /etc/passwdFields: File (name), Size (bytes), Blocks (512-byte blocks on disk), IO Block (preferred I/O block size), File type, Device (major:minor), Inode (number), Links (hard link count), Access (permissions+type in octal and rwxrwxrwx), Uid/Gid (owner), Access/Modify/Change times.
Answer: mtime (modification time): changes when file data content is modified. ctime (change time, NOT creation time): changes when the inode is modified — includes: data modification, permission changes, owner changes, hard link additions/removals. You cannot directly get the creation time on most Linux filesystems (ext4 does store it as crtime, accessible via debugfs).
fadvise/posix_fadvise and how does it help?Answer: Hints to the kernel about expected access patterns, allowing optimization:
xxxxxxxxxxposix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); // enable large read-aheadposix_fadvise(fd, 0, 0, POSIX_FADV_RANDOM); // disable read-aheadposix_fadvise(fd, offset, len, POSIX_FADV_DONTNEED); // evict from page cacheposix_fadvise(fd, offset, len, POSIX_FADV_WILLNEED); // pre-read into cacheAnswer: A union filesystem merges multiple directory trees into one view (Union Mount). Files from higher-priority layers override lower ones. Used by: OverlayFS (containers), AUFS (Docker's old default), UnionFS. Reads search layers from top to bottom; writes go to the top (writable) layer with CoW semantics.
getattrlist() on macOS vs getxattr() on Linux?Answer: On Linux, extended attributes are accessed via getxattr(path, name, value, size) / setxattr() / listxattr(). On macOS, getattrlist() is used for volume/file attributes. For portability, use the POSIX xattr API. Namespaces differ: Linux has user., security., system., trusted. prefixes.
inotify_add_watch and what events can you monitor?xxxxxxxxxxinotify_add_watch(fd, path, IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO | IN_ATTRIB | IN_CLOSE_WRITE | IN_OPEN);Events: IN_ACCESS (read), IN_MODIFY (write), IN_ATTRIB (metadata change), IN_CLOSE_WRITE (close after write), IN_OPEN (open), IN_CREATE, IN_DELETE, IN_MOVED_FROM/TO (rename), IN_DELETE_SELF, IN_UNMOUNT.
kAFS (kernel AFS)?Answer: AFS (Andrew File System) is a distributed network filesystem. Linux includes a native kernel AFS client (kAFS). Features: location transparency (files accessed by cell/volume name, not server), caching (cached locally until callback expires), Kerberos authentication. Used at universities and large organizations for network home directories.
squashfs?Answer: squashfs is a compressed read-only filesystem. Used for: Linux live CDs (entire OS in one squashfs image), Android system image, snap packages (.snap is a squashfs), embedded systems. Very high compression ratio (zstd, xz, lzo). mksquashfs /source out.sqsh creates; mount: mount -o loop out.sqsh /mnt.
noatime vs relatime difference in practice?Answer: noatime never updates atime — saves every read from triggering an inode write. relatime updates atime only if it's older than mtime/ctime or more than 24h old — provides reasonable atime semantics while avoiding per-read writes. relatime is the default since Linux 2.6.30 (a good balance). Use noatime only if you're sure no application depends on atime (e.g., mutt, old at daemons used atime).
df -i and why can a filesystem run out of space with plenty of disk free?Answer: df -i shows inode usage. If inode count reaches 100%, no new files can be created even if blocks are free. Causes: many small files, many hard links, unreleased inode after file deletion with open FDs. Fix: delete small files, or (offline) mkfs with mkfs.ext4 -N <more_inodes>.
e2fsck exit code 0 vs 1 vs 2?Answer:
0: No errors found.
1: Filesystem errors corrected.
2: System should be rebooted.
4: Filesystem errors left uncorrected.
8: Operational error.
16: Usage/syntax error.
128: Shared library error. In init scripts, exit codes 1 and 2 are normal; 4+ indicates serious problems.
xxxxxxxxxxcat /proc/mounts # all mountsfindmnt /path # specific pathmount | grep /path # traditionalcat /proc/<pid>/mounts # per-process view (for namespaces)O_TMPFILE?xxxxxxxxxxint fd = open("/tmp", O_TMPFILE | O_RDWR, 0600);// Write to fd — file has no directory entry// Optionally link it into the filesystem atomically:linkat(fd, "", AT_FDCWD, "/tmp/myfile", AT_EMPTY_PATH);Creates a nameless temporary file — never appears in any directory until explicitly linked. Prevents partial files from being visible if the process crashes. Requires Linux 3.11+ and a supporting filesystem.
copy_file_range() syscall?xxxxxxxxxxcopy_file_range(src_fd, &src_off, dst_fd, &dst_off, len, 0);Copies data between two files entirely within the kernel — no userspace buffer needed. The kernel can use reflinks (CoW on Btrfs/XFS) or direct block copies. Used by cp --reflink=auto on supported filesystems for efficient, potentially zero-copy file copies.
Answer: VFS provides the abstract interface (inodes, dentries, file operations) used by user space. Filesystem drivers (ext4, xfs, btrfs) implement VFS interfaces and translate them into block device operations (read/write specific sectors). The block layer manages I/O scheduling, request merging, device queues, and hands requests to device drivers (SCSI, NVMe, virtio-blk). The storage device (SSD/HDD) handles the physical I/O. Page cache sits between VFS and the filesystem driver for write buffering and read caching.