File Systems & Links — Top 150 Interview Q&A


Filesystem Concepts

Q1: What is a filesystem?

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.

Q2: What is an inode?

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.

Q3: What metadata does an inode NOT store?

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.

Q4: How are inodes allocated on disk?

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.

Q5: What is a superblock?

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.

Q6: What is a block group in ext4?

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.

Q7: What is the block size and why does it matter?

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.

Q8: What is the VFS (Virtual Filesystem Switch)?

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.

Q9: What is the dentry cache (dcache)?

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.

Q10: What is the inode cache?

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.

Q11: What happens when you delete a file?

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.

Q12: What is a directory in a filesystem?

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.

Q13: What is filesystem journaling and why is it important?

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).

Q14: What are extent-based file allocation and how does ext4 use extents?

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.

Q15: What is filesystem fragmentation and how do you defragment ext4?

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).

Q16: What is 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.

Q17: What is write-back caching in filesystems?

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.

Q18: What is the difference between 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.

Q19: What are block device and character device filesystems?

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).

Q20: What is the difference between 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.


Common Filesystems

Q21: What is ext4 and what are its key features?

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).

Q22: What is XFS and when would you use it over ext4?

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.

Q23: What is Btrfs and its key features?

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.

Q25: What is tmpfs and how does it differ from a RAM disk?

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.

Q26: What is 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.

Q27: What is 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).

Q28: What is 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.

Q29: What is 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.

Q30: What is 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.

Q31: What is NFS and how does it work?

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).

Q32: What is FUSE (Filesystem in Userspace)?

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.

PropertyHard LinkSymlink
InodeSame inode as targetOwn inode
Cross-filesystemNo (same device only)Yes
Link directoriesNo (usually)Yes
If target deletedData survivesDangling link
Shows in ls -lNo indicator-> arrow
stat sizeFile sizeLength of path string
PerformanceNo extra lookupOne extra path lookup

Answer: 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:

readlink(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 ...

Q41: What is 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.

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.

Q45: What is 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.


Mounting & fstab

Q46: What is mount() syscall?

source: device or none for virtual filesystems. target: existing directory. mountflags: MS_RDONLY, MS_NOSUID, MS_NODEV, MS_NOEXEC, MS_REMOUNT, MS_BIND.

Q47: What is a bind mount?

A 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.

Q48: What is a recursive bind mount?

--rbind includes all sub-mount-points within the source. Necessary when the source has sub-mounts you also need visible at the destination.

Q49: What are mount propagation types?

Answer: Controls how mount/umount events propagate between peer groups:

Q50: What is /etc/fstab format?

dump: 0 = don't backup, 1 = backup with dump. pass: 0 = no fsck, 1 = root (first), 2 = others (after root).

Q51: What mount options are commonly used for security?

Answer:

Q52: What is 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:

Q53: What is findmnt and how is it used?

Q54: What is autofs 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.

Q55: What is 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.


Permissions & ACLs

Q56: How do file permissions work on directories?

Answer:

Q57: What does 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.

Q58: What is umask and how does it work?

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.

Q59: What are POSIX ACLs and how do they extend standard permissions?

Answer: POSIX ACLs allow per-user and per-group permissions beyond the owner/group/other model:

Stored in extended attributes. ls -la shows + after permissions when ACLs are present.

Q60: What is the effective permission mask in ACLs?

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.

Q61: What is SELinux and how does it differ from DAC?

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.

Q62: What are extended attributes (xattrs)?

Extended 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.

Q63: What are file capabilities and how do they work?

File 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.

Q64: What is the sticky bit on files (vs. directories)?

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.

Q65: What is chattr and lsattr?

chattr sets Linux-specific file attributes stored in the filesystem. Useful for protecting critical config files. Requires root. +i protects log files from accidental deletion.


Disk I/O & Buffering

Q66: What is the kernel's page cache and how does it affect file I/O?

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).

Q67: What is read-ahead and how does it improve performance?

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.

Q68: What is 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.

Q69: What is the block I/O scheduler and why does it matter?

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.

Q70: What is NVMe and how does it differ from SATA in software?

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.

Q71: What is fallocate() and when is it used?

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.

Q72: What is 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.

Q73: What is a sparse file?

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.

Q74: What is 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.

Q75: What is 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.


NFS/Network Filesystems

Q76: How do you configure an NFS export?

Options: 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.

Q77: How do you mount an NFS share?

_netdev: wait for network. timeo: NFS timeout (tenths of seconds). rsize/wsize: read/write block size.

Q78: What is the difference between NFSv3 and NFSv4?

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).

Q79: What is CIFS/SMB and how does it relate to NFS?

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.

Q80: How do you debug NFS performance issues?


Filesystem Debugging & Maintenance

Q81: What is fsck 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:

Q82: What is dumpe2fs used for?

Shows: filesystem creation date, last mount time, UUID, journal info, block groups, inode/block counts.

Q83: What is debugfs (ext2/3/4 tool)?

Interactive tool for low-level ext2/3/4 inspection and recovery. Use with care — can directly modify filesystem.

Q84: What is tune2fs and what can it do?

Q85: What is e2fsck -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.

Q86: What is xfs_repair?

XFS equivalent of e2fsck. Requires unmounted or read-only mounted filesystem.

Q87: What is 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.

Q88: How do you recover a deleted file in ext4?

Answer:

Note: If data blocks have been overwritten (new files created), recovery may fail. Unmount immediately after deletion for best results.

Q89: How do you resize a filesystem?

Q90: What is badblocks and when do you use it?

Tests for physical bad sectors on a disk. On modern drives, the drive firmware handles bad sector remapping internally; badblocks primarily catches firmware failures.


Advanced Filesystem Topics

Q91: What is the difference between 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).

Q92: What is 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).

Q93: What is 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.

Q94: What is online defragmentation in ext4?

Can run on a live, mounted filesystem. Re-arranges blocks to make files contiguous. May be needed after heavy write workloads that created fragmentation.

Q95: What is the 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).

Q96: What is the 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.

Q97: What is the Reserved Block Percentage in ext4?

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).

Q98: What is xfs_quota and how does it work?

XFS has integrated quota management. Supports user, group, and project (directory tree) quotas.

Q99: What is e2label and xfs_admin -L?

Volume labels allow mounting by label (LABEL=my-disk) instead of device path — more stable across reboots when device ordering may change.

Q100: What is 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.

Q101: What is btrfs subvolume and snapshot?

Subvolumes 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.

Q102: What is Btrfs send/receive?

btrfs 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.

Q103: What is 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.

Q104: What are filesystem quotas and how do you enable them on ext4?

Q105: What is the difference between soft and hard quota limits?

Answer: 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.

Q106: What is 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.

Q107: What is blkid and when is it used?

Reads filesystem metadata (UUID, type, label) from block devices. Used in /etc/fstab (UUID references), system scripts, and device detection.

Q108: What is 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).

Q109: What is the difference between mkfs.ext4 options for HDD vs SSD?

Q110: What is filesystem encryption (fscrypt/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.


Filesystem Performance & Tuning

Q111: How do you measure filesystem throughput?

Q112: What is fio 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.

Q113: What is queue depth and how does it affect I/O performance?

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.

Q114: What is ionice and how does it affect filesystem I/O?

Uses 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.

Q115: What is blockdev used for?

Q116: What is hdparm used for?

Q117: What is filesystem fragmentation and how do you measure it?

High fragmentation = many non-contiguous extents per file → more disk seeks → worse read performance.

Q118: What is dm-cache and bcache?

Answer: Both use a fast SSD to cache a slow HDD:

Q119: What is lvmcache and how do you set it up?

Q120: What is the significance of /proc/sys/vm/dirty_ratio and dirty_background_ratio?

Answer:


Q121: What is 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.

Q122: What is 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.

Q123: What is 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.

Q124: What is a mount point and how does it affect path resolution?

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).

Q125: What is 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.

Q127: What is the difference between rename() 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).

Q128: How does cp -a differ from cp?

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.

Q130: What is 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.


Filesystem Security

Q131: What is a TOCTOU (Time-of-Check-to-Time-of-Use) vulnerability in filesystems?

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()).

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.

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).

Q134: What is 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.

Q135: What is filesystem integrity monitoring?

Detects unauthorized modifications to files by comparing against a cryptographic hash baseline.


Miscellaneous Filesystem Topics

Q136: What is stat output and what does each field mean?

Fields: 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.

Q137: What is the difference between mtime and ctime?

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).

Q138: What is fadvise/posix_fadvise and how does it help?

Answer: Hints to the kernel about expected access patterns, allowing optimization:

Q139: What is a union filesystem?

Answer: 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.

Q140: What is 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.

Q141: What is inotify_add_watch and what events can you monitor?

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.

Q142: What is 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.

Q143: What is 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.

Q144: What is the 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).

Q145: What is 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>.

Q146: What is e2fsck exit code 0 vs 1 vs 2?

Answer:

Q147: How do you check filesystem mount options of a currently mounted filesystem?

Q148: What is O_TMPFILE?

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.

Q149: What is copy_file_range() syscall?

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.

Q150: What is the relationship between VFS, filesystem drivers, and the block layer?

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.