Directory Implementation
A practical guide to directory entries, filesystem-specific indexes, Linux path lookup, and the VFS dentry cache.
A practical guide to directory entries, filesystem-specific indexes, Linux path lookup, and the VFS dentry cache.
Directory Implementation
When you type ls /home/user/documents/report.pdf, something has to figure out where that file actually lives on disk. That something is the directory implementation. The directory is the mapping between human-readable names and the underlying inodes that point to file data. How that mapping is structured determines how fast you can find files, how many files a directory can hold, and how the file system behaves under heavy load.
Most people think directories are simple folders. Under the hood, they’re sophisticated data structures that make the difference between a file system that screams and one that crawls.
Introduction
A directory maps names to filesystem objects, usually through inode numbers on Unix-like filesystems. The on-disk representation and lookup index depend on the filesystem and its configuration. A linear scan, a hash index, and a tree are useful data-structure models, but they are not stages that every filesystem follows.
This article uses those models to explain filesystem lookup, then separates Linux VFS path caching from the on-disk directory format. A large directory can behave differently across filesystems, kernel versions, storage devices, and workloads, so benchmark the filesystem you run.
When to Use / When Not to Use
Understanding directory implementation helps with system design and troubleshooting.
When directory implementation matters:
- Systems with millions of files in single directories
- High-throughput workloads that create/delete files frequently
- Backup systems that must scan directory structures
- Troubleshooting slow file system operations
When you can ignore it:
- Normal desktop/server use with moderate file counts
- Cloud storage abstracted behind network file systems
- Applications using higher-level APIs (databases, etc.)
Architecture or Flow Diagram
graph TD
A[Path: /home/user/docs/file.txt] --> B[Root Directory]
B --> C[Look up 'home']
C --> D[User Directory]
D --> E[Look up 'docs']
E --> F[Docs Directory]
F --> G[Look up 'file.txt']
G --> H[Return Inode Number]
style A stroke:#ff00ff,stroke-width:2px
style H stroke:#ff00ff,stroke-width:2px
Path resolution walks through each component. The efficiency of each lookup step determines overall performance.
Core Concepts
Directory Entry Structure
At the basic level, a directory contains entries. Each entry maps a name to an inode:
// Classic Unix directory entry (simplified)
struct old_dirent {
unsigned long d_ino; // Inode number
unsigned short d_reclen; // Record length
unsigned char d_type; // File type
char d_name[256]; // File name (variable length)
};
// Modern directory entry with type
struct linux_dirent64 {
unsigned long d_ino; // Inode number
unsigned long d_off; // Offset to next entry
unsigned short d_reclen; // Record length
unsigned char d_type; // File type
char d_name[]; // File name (null-terminated)
};
The d_reclen field enables entries of variable length. Older systems used fixed-size entries (often 16 or 32 bytes), which limited file names and wasted space.
Linear Search (Simple List)
The most basic directory implementation: entries stored as a simple list, searched sequentially.
graph TD
A[Directory Entry Array] --> B[.]
A --> C[..]
A --> D[file1.txt]
A --> E[file2.txt]
A --> F[file3.txt]
A --> G[fileN.txt]
H[Search for file3.txt] --> I[Compare with file1.txt: NO]
I --> J[Compare with file2.txt: NO]
J --> K[Compare with file3.txt: YES - Return inode]
style H stroke:#00fff9
Characteristics:
- O(n) lookup time where n is number of entries
- No memory overhead for indexing
- Simple implementation
- Performance degrades linearly with directory size
def linear_search(directory, target_name):
"""Simulate linear directory search."""
for entry in directory.entries:
if entry.name == target_name:
return entry.inode
return None # Not found
# Complexity: O(n) where n = number of entries
# For 1 million files in a directory: up to 1 million comparisons
Hash Table Directories
In a hash-table model, a hash of the filename selects a bucket. Under a suitable hash distribution, lookup is O(1) on average; collisions and resizing can make an individual lookup slower. This describes the data structure, not a guaranteed filesystem path-lookup time:
graph TD
A[Filename: document.txt] --> B[Hash Function]
B --> C[Bucket Index: 7]
C --> D[Bucket 7]
D --> E[Entry: document.txt -> inode 1234]
F[Filename: report.pdf] --> G[Hash Function]
G --> H[Bucket Index: 3]
H --> I[Bucket 3]
I --> J[Entry: report.pdf -> inode 5678]
style A stroke:#ff00ff
style F stroke:#ff00ff
Advantages:
- O(1) average bucket lookup under a suitable hash distribution
- Handles collisions through chaining or open addressing
- Good for large directories
Disadvantages:
- Hash computation overhead
- Collisions require additional handling
- Memory overhead for hash table structure
- Cannot efficiently list entries in sorted order
// Hash table directory implementation (conceptual)
typedef struct dir_entry {
char *name;
unsigned long inode;
struct dir_entry *next; // Collision chain
} DirEntry;
typedef struct {
DirEntry *buckets[TABLE_SIZE];
unsigned int (*hash_fn)(const char *name, int len);
} HashDirectory;
// Insert operation
int hash_insert(HashDirectory *dir, const char *name, unsigned long inode) {
unsigned int index = dir->hash_fn(name, strlen(name));
DirEntry *new_entry = malloc(sizeof(DirEntry));
new_entry->name = strdup(name);
new_entry->inode = inode;
new_entry->next = dir->buckets[index];
dir->buckets[index] = new_entry;
return 0;
}
B-Tree and B+ Tree Directories
An ordered B-tree is one possible directory index. Filesystems choose their own on-disk formats and lookup rules; this diagram is a data-structure model, not a description shared by ext4, NTFS, and XFS:
graph TD
A[Root Node] --> B[Intermediate Node]
A --> C[Intermediate Node]
B --> D[Leaf: A-M]
B --> E[Leaf: N-Z]
C --> F[Leaf: A-G]
C --> G[Leaf: H-N]
style A stroke:#ff00ff,stroke-width:3px
style D stroke:#00fff9
style E stroke:#00fff9
style F stroke:#00fff9
style G stroke:#00fff9
B-Tree characteristics:
- O(log n) lookup in the abstract tree model
- Can maintain sorted order and support range scans
- Rebalances as entries are inserted or deleted
- Actual filesystem costs depend on its format, caching, and storage
ext4 HTree (Indexed Directory): ext4 can index a directory with an HTree: a hash-based index that directs a lookup to directory blocks. It is not an ordered B-tree. The directory entries remain in leaf blocks, while index nodes store hashes and block references. Small directories can remain unindexed; the kernel and filesystem tools manage indexed-directory state. The ext4 directory documentation describes the HTree format.
An HTree index stores filename hashes and references to directory blocks. It narrows the blocks that need to be searched, but hash collisions still require checking names in the selected leaf block. This filesystem-specific design should not be generalized to other filesystems.
graph TD
A[Hash Index Root] --> B[Index Node 0]
A --> C[Index Node 1]
B --> D[Leaf: files 0-999]
B --> E[Leaf: files 1000-1999]
C --> F[Leaf: files 2000-2999]
C --> G[Leaf: files 3000-3999]
style A stroke:#ff00ff,stroke-width:3px
FUSE-based directory implementations reveal the full complexity of these operations in userspace. Handling readdir() with offset, implementing mkdir() with proper error codes (EEXIST, EACCES, ENOSPC), and ensuring atomic rename operations across concurrent access are all non-trivial. Implementing a simple directory index with FUSE clarifies why kernel-level directory operations need careful locking.
Path Resolution
Path resolution walks the directory tree, looking up each component:
// Simplified path resolution algorithm
inode_t resolve_path(const char *path) {
if (path[0] == '/') {
// Absolute path - start at root
current = root_inode;
path = path + 1;
} else {
// Relative path - start at current directory
current = cwd_inode;
}
while (*path) {
// Find next path component
component = next_component(&path);
// Skip empty components (e.g., "a//b")
if (strlen(component) == 0) continue;
// Look up component in current directory
inode = lookup_entry(current, component);
if (!inode) return -ENOENT; // Component doesn't exist
// Handle ".." and "."
if (strcmp(component, "..") == 0) {
current = get_parent(current);
} else if (strcmp(component, ".") == 0) {
// Stay at current
} else {
current = inode;
}
}
return current;
}
Directory Caching
Linux VFS keeps a dentry cache (dcache) in memory for recently resolved pathname components, including negative results for names that were not found. A dentry links a name to a parent and, when present, an inode. This cache is separate from the filesystem’s on-disk directory index. Directory data may also be cached in the page cache; a dcache hit can avoid repeating filesystem lookup work, but a miss does not always mean physical disk I/O because the relevant directory blocks may already be cached. The VFS coordinates updates and invalidation when names change. See file-system abstraction and page cache and buffer cache for the surrounding layers.
# Check dentry cache statistics
cat /proc/sys/fs/dentry-state
# View cached entries
ls -la /proc/slabinfo | grep dentry
# Clear dentry cache (requires root)
echo 3 > /proc/sys/vm/drop_caches
Production Failure Scenarios
Scenario 1: Million-File Directory Meltdown
Illustrative scenario: A CI job stores millions of build artifacts in one directory. Directory enumeration and metadata operations slow down, but the cause depends on the filesystem, kernel, storage, cache state, and access pattern. A linear-search implementation can inspect many entries for a lookup; an indexed directory reduces that work, though it does not make every operation constant-time. Measure lookup, create, and enumeration separately before changing the layout.
Detection:
# Count files in a directory
ls -la /path/to/directory | wc -l
# Or faster
find /path/to/directory -maxdepth 1 | wc -l
# Check directory entry type
debugfs -R "dir /path/to/directory" /dev/sda1
Mitigation:
-
Upgrade to ext4 which enables HTree indexing automatically
-
Use
e2fsckto convert directory to indexed format:sudo tune2fs -O dir_index /dev/sda1 sudo e2fsck -fD /dev/sda1 # Convert directories -
Restructure storage to spread files across multiple directories
-
Implement automatic directory sharding (e.g., using first letters)
Scenario 2: Directory Entry Corruption
What happened: A server crashed mid-write to a directory. On reboot, the directory contained entries pointing to non-existent inodes. Some file names were garbled. The kernel marked the file system dirty.
Why it happened: Without journaling (ext3), directory modifications weren’t atomic. A partial write left the directory in an inconsistent state.
Detection:
# Run file system check in read-only mode
sudo fsck.ext4 -n /dev/sda1
# Use debugfs to examine directory structure
sudo debugfs -w /dev/sda1
debugfs: dirstat /path/to/directory
Mitigation:
- Use journaling file systems (ext4, XFS)
- Convert ext3 to ext4:
tune2fs -O extents,uninit_bg /dev/sda1 - Run periodic consistency checks
- Monitor kernel logs for file system errors
Scenario 3: Case-Insensitive Lookup Failure
What happened: A developer created a file named Config.php and pushed to a case-insensitive Windows file share mounted on Linux. Another developer on Linux couldn’t find config.php. The share appeared to lose the file.
Why it happened: Different file systems have different case sensitivity rules:
| File System | Case Sensitive? |
|---|---|
| ext2/3/4 | Yes |
| XFS | Yes |
| NTFS | No |
| FAT32 | No |
| CIFS/SMB default | Often no |
Detection:
# Check mount options for case sensitivity
mount | grep cifs
# Test case sensitivity
touch TESTFILE
ls testfile 2>/dev/null && echo "Case insensitive" || echo "Case sensitive"
Mitigation:
-
Use consistent naming conventions (all lowercase)
-
Specify
case sensitivitymount option for CIFS:mount -o case insensitive //server/share /mnt # Or mount -o case sensitive //server/share /mnt -
Document case sensitivity rules for cross-platform projects
Unicode Normalization in Case-Insensitive File Systems
Case-insensitive file systems have a Unicode problem: the same logical character can be represented multiple ways in UTF-8 (e.g., é as a single codepoint U+00E9 versus e + combining acute accent U+0301). If a file is created with one representation and looked up with another, naive byte comparison fails even though they look identical.
How the lookup actually fails: When you create Crème Brûlée.txt using NFC normalization (U+00E9), and then a macOS application writes the same filename using NFD normalization (U+0301 combining accent), the directory stores two different byte sequences for what appears to be the same name. On a case-insensitive lookup, the filesystem uppercases both for comparison, but the Unicode code points fold differently: U+00E9 (é) uppercases to U+00C9 (É), while U+0301 is a combining mark that may be dropped or handled inconsistently depending on the locale settings. The result is a lookup miss despite the file existing.
NTFS behavior: NTFS uses RtlUpcaseUnicodeString() which performs locale-aware case folding. However, normalization forms (NFC composed vs NFD decomposed) can still produce different uppercase results across locales. Windows generally uses NFC internally, but files copied from macOS (which uses NFD) may arrive in decomposed form. The NTFS driver handles this transparently on reads, but if you access the raw NTFS volume from Linux via NTFS-3G, you may see the decomposed form stored on disk.
FAT32/VFAT behavior: FAT32 with VFAT long filenames normalizes to the composed form (NFC) when storing and uses case-insensitive comparisons. However, the normalization is not exposed to userspace as a tunable. If you copy a file from a VFAT volume to ext4, the filename’s normalization form is preserved as-is, potentially creating invisible duplicates if the same name exists in different normalization forms.
The silent “file disappeared” problem: For cross-platform projects sharing files over NTFS/CIFS, convmv can pre-normalize filenames to NFC before upload, avoiding the scenario where the same visible filename has two different stored representations. This matters for version control systems and build pipelines where filename collisions cause silent failures or data loss. Run convmv -r --nfc /path/to/files to normalize entire directory trees recursively.
Trade-off Table
| Method | Lookup Time | Insert Time | Memory | Use Case |
|---|---|---|---|---|
| Linear List | O(n) | O(1) at end | Minimal | Small directories (<1000 files) |
| Hash table model | O(1) average under assumptions | O(1) average under assumptions | Varies | Conceptual model for hashed lookup |
| Ordered tree model | O(log n) | O(log n) | Varies | Conceptual model when sorted traversal matters |
| ext4 HTree | Hash-index lookup into directory blocks | Filesystem-specific | Filesystem-specific | ext4 indexed directories; not the universal Linux default |
These complexity figures describe abstract data structures. End-to-end pathname lookup also includes every path component, VFS caching, filesystem work, permissions, mount boundaries, and storage latency. An average O(1) hash lookup is not a promise of O(1) full-path resolution.
Implementation Snippet
Directory Entry Parser
#!/usr/bin/env python3
"""Parse Linux ext4 directory entries."""
import struct
def parse_ext4_directory(data, block_size=4096):
"""Parse directory entries from an ext4 directory block."""
entries = []
offset = 0
while offset < block_size:
# Directory entry header (8 bytes)
header = struct.unpack('<IHHHHH', data[offset:offset+struct.calcsize('<IHHHHH')])
inode = header[0]
rec_len = header[1]
name_len = header[3]
if inode == 0:
# Entry not in use
offset += rec_len
continue
# Extract filename
name_start = offset + struct.calcsize('<IHHHHH')
name = data[name_start:name_start + name_len].decode('utf-8', errors='replace')
# File type (stored in record length high bits in ext4)
file_type = (rec_len >> 12) if rec_len > 255 else 1
entries.append({
'inode': inode,
'name': name,
'rec_len': rec_len & 0xFFF, # Lower 12 bits
'type': ['unknown', 'regular', 'directory', 'char', 'block',
'fifo', 'sock', 'symlink'][file_type]
})
offset += rec_len
return entries
def list_directory(device, inode_num):
"""List entries in a directory given its inode."""
import subprocess
result = subprocess.run([
'debugfs', '-R', f'rdump / {inode_num}',
device
], capture_output=True, text=True)
return result.stdout
Simulating Directory Search
#!/usr/bin/env python3
"""Compare different directory search strategies."""
import time
import random
import string
class DirectoryEntry:
def __init__(self, name, inode):
self.name = name
self.inode = inode
class LinearDirectory:
"""Simple list-based directory."""
def __init__(self):
self.entries = []
def insert(self, name, inode):
self.entries.append(DirectoryEntry(name, inode))
def lookup(self, name):
for entry in self.entries:
if entry.name == name:
return entry.inode
return None
def list_all(self):
return [e.name for e in self.entries]
class HashDirectory:
"""Hash table based directory."""
def __init__(self, size=256):
self.buckets = [[] for _ in range(size)]
self.size = size
def _hash(self, name):
h = 0
for c in name:
h = (h * 31 + ord(c)) % self.size
return h
def insert(self, name, inode):
bucket = self._hash(name)
for entry in self.buckets[bucket]:
if entry.name == name:
entry.inode = inode
return
self.buckets[bucket].append(DirectoryEntry(name, inode))
def lookup(self, name):
bucket = self._hash(name)
for entry in self.buckets[bucket]:
if entry.name == name:
return entry.inode
return None
def benchmark(directory, names, iterations=1000):
"""Benchmark directory lookup performance."""
# Insert all names
for name in names:
directory.insert(name, random.randint(1, 1000000))
# Benchmark lookups
start = time.time()
for _ in range(iterations):
for name in random.sample(names, min(100, len(names))):
directory.lookup(name)
elapsed = time.time() - start
return elapsed
if __name__ == "__main__":
# Generate test names
names = [''.join(random.choices(string.ascii_lowercase, k=10))
for _ in range(10000)]
linear = LinearDirectory()
hash_dir = HashDirectory()
linear_time = benchmark(linear, names)
hash_time = benchmark(hash_dir, names)
print(f"Linear search: {linear_time:.4f}s")
print(f"Hash table: {hash_time:.4f}s")
print(f"Speedup: {linear_time/hash_time:.2f}x")
Observability Checklist
Monitoring directory performance:
- ls -la /path: Check entry count and modification
- getfattr -d file: Check extended attributes
- debugfs -R “dirstat /path” /dev/sdX: Directory statistics on ext4
- xfs_info /mount: Show XFS directory block configuration
# Monitor directory operation times
strace -c ls /path/to/directory
# Check for problematic directories
for dir in /var /home /tmp; do
count=$(find "$dir" -maxdepth 1 -type f | wc -l)
if [ $count -gt 10000 ]; then
echo "WARNING: $dir has $count files"
fi
done
# Check ext4 directory indexing
sudo tune2fs -l /dev/sda1 | grep -E "Directory"
# Should show: "Directory ACLs", "Directory Indexed"
Common Pitfalls / Anti-Patterns
1. Millions of Files in One Directory
# BAD: Storing millions of files in single directory
# This kills performance on most file systems
find /logs -name "*.log" | head -1000000 > /tmp/all_logs
# GOOD: Use subdirectories sharded by date/hash
find /logs -type d | head
# /logs/2024/01/01
# /logs/2024/01/02
# ...
# GOOD: Use hierarchical sharding
for i in $(seq 0 99); do
mkdir -p /data/$i
done
mv file_0001.dat /data/$(($RANDOM % 100))/
2. Long File Names
The 255-byte filename limit exists because the original Unix directory entry design stored filenames in a fixed 14-byte field (ext2 later extended this to 255 bytes via name_len). When you hit this limit, ENOENT (No such file or directory) is returned even though the file might be createable on another filesystem.
Why this limit matters in practice: Some build systems and packaging tools generate filenames by concatenating project paths, timestamps, and hashes. A path like /home/user/very-long-project-name/build-output/2024-01-15-14-30-00-SNAPSHOT-reactor-core-a3f8b2c1d4e5/module/target/classes/com/example/very/deeply/nested/package/ClassName.java already exceeds 255 bytes at the component level. The kernel returns ENOENT on lookup, but the actual error is “name too long” — applications often misinterpret this as “file doesn’t exist.”
The PATH_MAX trap: PATH_MAX (4096 bytes) is the maximum total path length, but this is not guaranteed on all filesystems. NFS mounts may impose lower limits. A file that fits on ext4 may fail to create on an NFS share mounted with a smaller rsize/wsize. Network filesystem clients that don’t handle path length limits gracefully can deadlock or corrupt data when path components are truncated silently.
ENAME toolong behavior: When a filename exceeds 255 bytes, the kernel returns ENAMETOOLONG on Linux. However, some programs still try to create the file with a truncated name, leading to mysterious failures where “myfile.txt” exists but “myfile.txt.bak” cannot be created because both resolve to the same 255-byte truncated form.
# Path length limits (older systems):
# - Maximum component: 255 bytes
# - Maximum total path: 4096 bytes
# BAD: Extremely long file names — creates ENAMETOOLONG on lookup
touch "this_is_a_very_very_long_file_name_that_might_cause_problems.txt"
# GOOD: Use reasonable naming conventions
touch "config_v2_final_REVISED.txt"
# Check actual PATH_MAX on your filesystem
pathconf /your/mount/point _PC_PATH_MAX
3. Special Characters in File Names
Special characters break scripts because the shell performs word splitting and glob expansion before commands see the arguments. When you type rm file with spaces.txt, the shell splits it into three arguments: rm, file, with, spaces.txt. The filesystem sees file and with as separate filenames, neither of which matches the actual file.
The glob expansion problem: *, ?, and [ are wildcard characters that expand to matching filenames in the current directory. If a file is named file*.txt, running rm file*.txt expands to rm file1.txt file2.txt file3.txt before rm even runs. If no files match the pattern, the literal string file*.txt is passed to rm, which then tries to delete a file literally named file*.txt.
Null byte handling: Unix filenames cannot contain null bytes (\0) because this is the string terminator used by C library functions. The kernel simply refuses to create such filenames, returning EINVAL. This is a fundamental design constraint, not a filesystem limitation.
Newline in filenames: Newlines are legal in filenames but cause cascading failures in line-based tools. ls | grep fails to match because the newline is part of the name. wc -l counts one file as two lines. Scripts that read filenames with while read misparse the input. Tools like find -print0 and xargs -0 use null delimiters specifically to handle filenames containing newlines and spaces.
Shell quoting and escaping: To create or access files with special characters, you need quoting: touch "file with spaces.txt" or touch 'file;with;semicolons.txt'. To pass such filenames to a command, use rm "./file with spaces.txt" or pipe through find -print0 | xargs -0.
# BAD: Special characters that break scripts
touch "file with spaces.txt"
touch "file;with;semicolons.txt"
touch "file*with*asterisks.txt"
# GOOD: Alphanumeric and underscores
touch "config_settings.txt"
touch "user_data_backup.txt"
# Safe handling with find and xargs
find . -name "*.txt" -print0 | xargs -0 rm
4. Misunderstanding Directory Permissions
Directory permissions work differently than file permissions:
- Read (r): List directory contents (use
ls) - Write (w): Create, rename, or delete files within directory
- Execute (x): Access directory contents (traverse, use
cd)
# r--: Can see file names but not metadata or content
ls /directory # Yes
ls -l /directory # No
cat /file # No
# -w-: Can create/delete files but can't read them
touch /directory/newfile # Yes
rm /directory/file # Yes
ls /directory # No
# --x: Can access known files but not list directory
cd /directory # Yes
ls /directory # No
cat /file # Yes (if you know exact path)
5. Ignoring the Sticky Bit on Shared Directories
Without the sticky bit, any user with write permission to a directory can delete any file in it, regardless of who owns the file. In a shared directory like /tmp or a collaborative workspace, this is a security problem: user A creates a file, user B deletes it, user A cannot do anything about it.
The vulnerability scenario: Suppose /shared is a project directory with drwxrwxr-x permissions (writable by group). User Alice creates results.csv. User Bob, also in the group, can run rm /shared/results.csv and Alice’s file is gone. Bob didn’t need write permission on Alice’s file — only write permission on the directory.
The sticky bit fixes this: When the sticky bit is set (chmod +t /shared), the kernel checks that you own the file before allowing deletion, even if you have write permission on the directory. Non-owners receive EACCES (Permission denied) when attempting to delete others’ files. The directory permission to create and delete your own files remains unchanged.
System directories with sticky bits: The classic example is /tmp (typically drwxrwxrwt) and /var/tmp (drwxrwxrwt). These are world-writable directories where many programs create temporary files. Without sticky bits, any user could delete any other user’s temp files — a denial-of-service vector. Most Unix systems set the sticky bit on these directories by default.
Detecting directories missing the sticky bit: A directory that is world-writable (drwxrwxrwx) but lacks the sticky bit is a security finding in any hardening audit. In containerized environments, be aware that volume mounts may override the sticky bit if the underlying filesystem doesn’t support it (some NFS mounts, overlay filesystems with certain configurations).
# Prevents users from deleting others' files in shared directories
chmod +t /shared/directory
# View sticky bit — the 't' at the end of permissions
ls -la /shared
# drwxrwxrwt 2 root root 4096 May 19 10:00 /shared
# ^ sticky bit
# 't' = sticky bit set (everyone sees it)
# 'T' = sticky bit set but no execute permission on directory (less common)
6. Neglecting Directory Access Control Lists (ACLs)
Standard Unix permissions (owner/group/other) cannot express “alice gets read-write, bob gets read-only, the dev team gets execute, and everyone else gets nothing” without creating multiple groups. ACLs extend the permission model to handle these cases without group gymnastics.
When basic permissions fall short: Suppose a directory contains a financial report owned by finance:accounts with permissions 640. User alice is in the legal group, not accounts. She cannot read the file. But the compliance policy says legal should be able to read it without being added to the accounts group. With ACLs: setfacl -m u:alice:r /finance/report.pdf gives alice read access without modifying the file’s group membership.
Default ACLs on directories: When you set a default ACL on a directory (setfacl -d -m g:developers:rx /project), every new file and subdirectory created within inherits that ACL. This is how you enforce access policies automatically — new files don’t need manual ACL configuration. Without default ACLs, files inherit the directory’s standard permissions, which may be too permissive or too restrictive.
The three ACL permission types: u:username:permissions grants specific user access. g:groupname:permissions grants specific group access. o:permissions sets the “other” fallback (used when no user or group ACL matches). The effective permission is determined by scanning user entries first, then group entries, then other — first match wins.
ACL interaction with chmod: Running chmod on a file with ACLs recalculates the base permissions but preserves named user and group entries. chmod 640 file sets the base to rw-r-----, but alice’s explicit u:alice:r entry from the ACL is evaluated independently. This can cause confusion: a file with chmod 000 but u:alice:rw is still readable and writable by alice.
Viewing and interpreting ACLs: getfacl shows the full ACL including inheritance flags. The output lists the owner, group, and named entries. A + at the end of ls -l permissions indicates extended ACL entries are present.
# Set default ACL for new files in directory — children inherit automatically
setfacl -d -m u:alice:rw /shared/directory
# Set ACL for specific user
setfacl -m u:bob:r /shared/directory
# Set group ACL
setfacl -m g:developers:rx /shared/directory
# View full ACLs
getfacl /shared/directory
# # file: /shared/directory
# # owner: root
# # group: root
# user::rwx
# user:alice:rw-
# user:bob:r--
# group::r-x
# group:developers:r-x
# mask::rwx
# other::---
# Remove specific ACL entry
setfacl -x u:alice /shared/directory
Quick Recap Checklist
- Directories map file names to inode numbers
- Linear search is O(n), good for small directories (<1000 entries)
- Hash tables provide O(1) average lookup but no sorted iteration
- B-trees give O(log n) and maintain sorted order
- ext4 uses HTree for large directories; convert with
e2fsck -D - Path resolution walks through each component, looking up each name
- Directory caching (dentry cache) dramatically speeds repeated lookups
- Different file systems have different case sensitivity rules
- Watch for inode exhaustion (not just space) when many small files exist
Interview Questions
Path resolution is a multi-step process:
- Parse: Split the path into components:
/,home,user,docs,file.txt - Start: Begin at the root inode (for absolute paths starting with
/) or current directory (for relative paths) - Lookup each component:
- Look up
homein the root directory → get inode for/home - Look up
userin/home→ get inode for/home/user - Continue until
file.txtis found
- Look up
- Validate permissions: At each step, verify execute permission on the directory
- Return inode: The inode number for
file.txt
The kernel uses the dentry cache to speed repeated lookups. Each path component lookup first checks the cache before doing I/O.
ext3 uses linear directory search: To find any file, ext3 scans entries one by one from the beginning. With a million files, the average lookup requires scanning 500,000 entries. This is O(n) complexity.
ext4 uses HTree indexing: When a directory grows beyond ~100 entries, ext4 automatically converts it to use a two-level hash tree. Lookups become O(log n) — finding a file in a million-entry directory takes ~20 comparisons instead of 500,000.
Additional factors:
- ext4 uses larger directory block sizes (4KB vs 1KB)
- ext4 has delayed allocation (better block placement)
- ext4 journal ensures directory modifications are atomic
You can manually convert ext3 directories to indexed format with e2fsck -D.
The dentry cache (Directory Entry cache) caches recently accessed directory entries — the mappings between file names and inode numbers. It's a tree-structured cache that lives in kernel memory.
Importance:
- Avoids repeated disk I/O for frequently accessed paths
- Enables fast path resolution (check cache → hit vs miss)
- Stores validity and aging information
- Helps maintain consistency across mount points
When you access /home/user/docs/file.txt:
- Check cache for
/→ get root inode - Check cache for
/home→ get inode - Check cache for
/home/user→ get inode - And so on...
Without the dentry cache, every path component lookup would require disk I/O.
Directory permissions control what you can do with the directory itself:
- Read (r): List the contents — you can see what files exist (via
ls) - Write (w): Create, rename, or delete files within the directory (even files you don't own, if directory is writable)
- Execute (x): Enter the directory and access files within it — you need this to
cdinto the directory or access any file by path
File permissions control what you can do with the file itself:
- Read (r): View file contents
- Write (w): Modify file contents
- Execute (x): Run the file as a program
Key insight: you need execute permission on a directory to access any file within it, regardless of the file's own permissions. To read /home/user/secret.txt, you need x on /, /home, and /home/user, plus r on secret.txt.
On Unix/Linux systems, deleting an open file works due to how the kernel handles file references:
- Directory entry removed: The file name is removed from its parent directory immediately
- Inode reference held: The file's inode remains allocated as long as any process has it open
- Data blocks intact: The actual file data stays on disk until the last reference (file descriptor or hard link) is released
- Process continues: The process with the open file descriptor can still read/write normally
- Cleanup on close: When the last process closes the file, the kernel frees the inode and data blocks
This behavior is used by package managers and software updates: they create a new version of a file, atomically replace the old one, and the old version persists until processes using it exit.
You can verify this with: lsof +L1 — shows files that are deleted but still open.
B-trees store keys in sorted order at each level. For directory lookups, this means:
- Range queries are efficient: Listing all files starting with "a" can stop early
- Prefix matching: Finding all files in a range is a tree traversal, not a full scan
- Insert/delete balanced: Tree stays balanced, guaranteeing O(log n) even after many modifications
ext4's HTree is a hash-indexed B-tree: the hash of the filename determines which branch to follow. This maintains O(log n) lookup while distributing entries evenly across branches (avoiding the "hot spot" problem of sorted B-trees with sequential inserts).
The dentry cache (dcache) stores directory entry structures—mappings from filename component to inode. Each dentry also holds references to its parent dentry and children, forming the directory tree in memory.
The inode cache stores the actual inode structures loaded from disk. When VFS needs to read a file's metadata or data blocks, it uses the inode cache to avoid disk I/O.
The relationship: dentries point to inodes. When you resolve /home/user/file.txt, the dentry for "user" points to the inode for /home/user. Both caches are separately managed but work together—dentries provide fast path resolution, inodes provide fast metadata access.
On ext3 (linear search), listing a directory with millions of files requires reading every entry sequentially. The O(n) complexity means average lookup is n/2 comparisons—catastrophic for large directories.
On ext4 with HTree, `ls` should be O(log n) for each entry lookup during readdir(), but there are still bottlenecks:
- readdir() must return entries in sorted order—HTree lookups still traverse the tree
- Each directory entry requires a dentry allocation in kernel memory
- Stale dentry invalidation if files are being created/deleted concurrently
- Directory block reads are sequential but still I/O-bound
The real cost is often not the lookup but the memory allocation and userspace processing for millions of entries.
When accessing /home/user/documents/report.txt:
- You need execute (x) permission on `/` to reach any subdirectory
- You need execute (x) on `/home` to enter it
- You need execute (x) on `/home/user` to enter it
- You need execute (x) on `/home/user/documents` to enter it
- Finally, you need the appropriate permission on `report.txt` itself (r for read, w for write, etc.)
The directory permissions don't control access to files inside—they control access to the directory itself. Even if you have full permission on a file, you can't access it if you lack execute permission on any parent directory.
A negative dentry is a cached lookup result indicating "this name does not exist." When you look up /nonexistent once, the kernel caches the negative result, preventing repeated lookup attempts.
Benefits:
- Avoids repeated failed lookups for missing files
- Particularly important for shared libraries (/lib/libfoo.so not found)—avoids filesystem hits on every program load
- TTL-based invalidation prevents stale negatives
Negative dentries can cause issues when a file is created after a negative cache: the cache must be invalidated. This happens through directory notifications (inotify) or timeout-based expiry.
Hard links: Multiple directory entries (directory entries are names in a directory) point to the same inode. The inode maintains a link count — how many directory entries reference it. Deleting a hard link decrements the count; when it reaches zero, the inode is freed. Hard links cannot span file systems (same inode numbers are local to each filesystem), and cannot reference directories (would create cycles).
Symbolic links: A special file type containing a path string. The path can point anywhere (even to nonexistent targets). Resolving a symbolic link requires following the path — if the target is removed, the symlink becomes "dangling." Symlinks can span file systems and reference directories. Directory entries for symlinks store the link's target path, not an inode.
At implementation: hard links share inode references directly; symlinks store path strings that must be recursively resolved.
VFS (Virtual File System) provides a unified interface that all file systems implement. For directory operations:
struct inode_operations: Contains function pointers forlookup,create,mkdir,renamestruct dentry_operations: Containsd_hash,d_compare,d_deletestruct file_operations: Containsreaddirfunction for iterating directory entries
When you call readdir(), VFS routes to the concrete filesystem's iterate() or readdir() implementation. ext4 uses HTree for indexed lookup; NFS may send lookups to remote server; tmpfs stores entries in RAM. VFS handles caching, locking, and pathname translation — filesystem code only deals with its own structures.
Page cache stores disk blocks (file data and metadata) in memory. Dentry cache stores parsed pathname components. They interact:
- When resolving
/home/user/file.txt, dentry cache holds "/" dentry, "home" dentry, "user" dentry - Each dentry points to an inode — inodes are cached in the inode cache
- When a file is opened, its inode's pages (block mapping + data blocks) are in page cache
- Modifying a file: dentry → inode → page cache → mark page dirty → writeback
The relationship: dentries are parsed from directory file data (which lives in page cache). When directory contents change, d_invalidate() marks relevant dentries invalid — they will be re-parsed on next lookup, pulling fresh data from page cache.
Journaling records directory operations in a journal (separate log area) before applying them to the actual directory:
- Journal transaction: Record intent (transaction begin, operation details)
- Commit: Write operation to journal on disk (durable)
- Checkpoint: Apply operation to actual directory structure
- Journal cleanup: Remove committed transactions from journal
On crash recovery: filesystem replays journal entries, completing any committed transactions. Directory structure is never left in partial-write state. ext4 uses journaling for metadata (configurable: ordered mode journals only metadata, writeback allows data journal). XFS journals both data and metadata in different modes.
Local rename (same filesystem, different directory): It's a meta-operation — the inode doesn't change, only the parent directory entry. The kernel:
- Lock both source and destination parent directories (inode mutex)
- Verify destination doesn't already exist (if it does, fail with EEXIST)
- Remove source filename entry, decrement link count of source inode
- Create destination filename entry pointing to same inode, increment link count
- Unlock directories
This is atomic in the sense that no intermediate state is visible: either the old name or the new name exists, never both simultaneously. The rename is cheap because no data moves — only directory entries are updated.
inotify (inode notification) is a Linux kernel subsystem for filesystem event monitoring. When you inotify_init(), you get a file descriptor; inotify_add_watch() registers interest in specific files/directories.
Events are stored in an inotify_event structure and can be read via read(). For directories, events include: IN_CREATE, IN_DELETE, IN_MOVED_FROM, IN_MOVED_TO, IN_MODIFY. The kernel hooks into VFS: when VFS modifies a directory entry, it calls inotify_d_instantiate() which queues events.
Performance: inotify watches consume kernel memory. Large number of watches or rapid events can overwhelm buffers — events may be coalesced or lost (read size determines how many events you retrieve per read).
File descriptor limits (ulimit -n, /proc/sys/fs/file-max) control how many open file descriptors a process can have. Each open file, directory traversal, and memory-mapped file consumes a file descriptor.
During directory traversal (e.g., readdir() loop), each directory entry may trigger:
stat()calls for metadata — these use fd indirectly via dentry cache- Opening files — each open consumes a file descriptor
- Processing large directories without closing descriptors — causes leaks
When FD limit is reached: EMFILE (Too many open files) — new file opens fail, but existing operations may continue if they have open descriptors. Always close directory handles with closedir() after use.
fsck recovery process:
- Phase 1: Check inodes — verify inode structure, link counts, block allocation bitmap consistency
- Phase 2: Check directory structure — verify directory entries point to valid inodes, parent/child relationships
- Phase 3: Reconnect orphaned inodes — inodes with zero directory links are reattached to lost+found
- Phase 4: Check reference counts — verify link counts match actual directory references
- Phase 5: Check cylinder groups — verify superblock and group descriptors
Limitations: fsck cannot recover data content (only structure), cannot repair hardware errors, cannot restore deleted files from backups. Orphaned files in lost+found have numeric names — content must be manually identified. Running fsck on mounted filesystem is dangerous — use recovery mode.
Case insensitivity implementation: When creating or looking up a filename, the filesystem normalizes the name (converts to uppercase in NTFS, or stores comparison flags). Lookup uses case-folded comparison instead of byte comparison.
NTFS specifics: Stores names in Unicode (UTF-16), uses RtlUpcaseUnicodeString() for comparisons. The volume mount option case sensitive can enable case-preserving-but-sensitive behavior for WSL/developers.
FAT32 specifics: 8.3 filename format (max 8 chars + 3 extension), all uppercase internally. Long filename (VFAT) extension stores names as UTF-16 but normalizes for lookup.
Cross-platform issues: A file created as "README.TXT" on Windows may appear as "readme.txt" on Linux — the filesystem stores the original case but lookup is case-insensitive. Applications expecting case-sensitive behavior may fail.
Directory quotas limit the number of entries or total size within a directory tree. Implementation options:
- Project quotas (XFS): Hierarchical quota tracking, each directory tree has a project ID with enforced limits
- Directory-based limits: Some filesystems (ReiserFS, ext4 with patches) support per-directory entry limits
- External quota systems: Quota daemon (quotacheck, quotaon) scans filesystem and enforces limits via inode count
Interaction with entry allocation:
- User attempts to create file in directory with quota
- Kernel checks current entry count vs soft/hard limits
- If hard limit reached, return
EDQUOT(disc quota exceeded) - Quota is checked before actual allocation — prevents partial operations
Quota enforcement for directories is more complex than for files because directories can contain many files — the quota applies to the tree, not individual entries.
Further Reading
Topic-Specific Deep Dives:
- Distributed Directory Systems: Ceph’s CRUSH algorithm and GlusterFS’s elastic hash algorithm distribute directory metadata across cluster nodes, pushing directory indexing to per-node hashmaps when the directory space exceeds single-machine limits. The ext4 HTree and B+ Tree patterns give way to hash-based partitioning at scale — understanding the single-machine versions makes the distributed versions easier to reason about. ( Ceph docs: https://docs.ceph.com/docs/master/architecture/ ; GlusterFS: https://docs.gluster.org/en/latest/ )
External References:
- Linux kernel source — dentry cache:
fs/dcache.c - Linux ext4 directory format and HTree documentation
- Linux kernel source — ext4 directory:
fs/ext4/dir.c - Understanding the Linux Kernel, Chapter 12 — VFS and dentry cache (oreilly.com)
- The Linux Programming Interface, Chapter 13 — directory operations (nostarch.com)
Related Topics:
- Journaling file systems: How ext4, XFS, and JFS use write-ahead logging to keep directory structures consistent across crashes
- POSIX ACLs: The difference between traditional permission bits and ACL entries that can grant access to specific named users
Conclusion
Directory entries map names to objects, but the storage format is filesystem-specific. ext4 HTree uses a hash index; a generic ordered B-tree diagram describes a different model. Neither an index nor a favorable average-case complexity guarantees a particular application latency.
Linux VFS dentries cache pathname components in memory. They are distinct from both the filesystem’s directory index and the page cache that may hold directory data. When a lookup is slow, measure these layers before assuming the directory structure is the cause.
For deeper study, explore how distributed file systems like Ceph and GlusterFS implement directory metadata at scale, how case-insensitive file systems handle Unicode normalization, and how the trade-offs between directory implementation strategies affect benchmark results. The principles learned here apply broadly to any system that needs to map keys to values at scale.
Category
Related Posts
ASLR & Stack Protection
Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.
Assembly Language Basics: Writing Code the CPU Understands
Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.
Boolean Logic & Gates
Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.