본문 바로가기

Core BSP 분석/리눅스 커널 핵심 분석

[리눅스커널] tracing: 파일 오픈 내역 확인하기

<커널: v5.10>
 
부팅 시간을 측정할 때 어떤 파일이 오픈됐는지 확인할 필요가 있습니다.
이 때 활용되면 좋은 패치입니다.
 
Author: Austin Kim <austindh.kim@gmail.com>
Date:   Mon Sep 20 19:16:16 2021 +0900
 
    open: trace the filename with directory
 
    When measuring booting-time, it is necessary to see how the file is
    opened. With this commit, we can trace how file is opened with ftrace buffer.
 
    <...>-124     [001] ....     2.968597: do_sys_openat2: cached_setup_ke: open("/dev/tty5", 131072, 0)
    fd = 3, inode = 25
   <...>-139     [002] ....     2.970130: do_sys_openat2: modprobe: open("/usr/lib/modules/5.10.46-
   v8+/kernel/crypto/sha256_generic.ko", 655360, 0) fd = 0, inode = 284403
   <...>-142     [000] d..1     2.970491: console: [    2.970468] [exec:kbd_mode-142] exec_file:
    /usr/bin/kbd_mode, arg: [kbd_mode] 
   <...>-142     [000] ....     2.970783: do_sys_openat2: kbd_mode: open("/etc/ld.so.cache", 655360, 0)
    fd = 3, inode = 6059
   <...>-142     [000] ....     2.970880: do_sys_openat2: kbd_mode: open("/usr/lib/aarch64-linux-gnu/libc
   -2.28.so", 655360, 0) fd = 3, inode = 6857
   <...>-142     [000] ....     2.971834: do_sys_openat2: kbd_mode: open("/usr/lib/locale/locale-archive",
   655360, 0) fd = 3, inode = 12847
   <...>-142     [000] ....     2.972191: do_sys_openat2: kbd_mode: open("/dev/tty5", 131074, 0) fd = 3, 
   inode = 25
 
diff --git a/fs/open.c b/fs/open.c
index 4d7537ae5..b7c8260f9
--- a/fs/open.c
+++ b/fs/open.c
@@ -1153,6 +1153,27 @@ struct file *file_open_root(struct dentry *dentry, struct vfsmount *mnt,
 }
 EXPORT_SYMBOL(file_open_root);
 
+static void _trace_do_sys_open(struct file *filp, int flags, int mode, long fd)
+{
+       char *buf;
+       char *fname;
+
+       buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
+       if (!buf)
+               return;
+
+       fname = d_path(&filp->f_path, buf, PAGE_SIZE);
+
+       if (IS_ERR(fname))
+               goto out;
+
+       trace_printk("%s: open(\"%s\", %d, %d) fd = %ld, inode = %ld\n",
+                      current->comm, fname, flags, mode, fd, filp->f_inode->i_ino);
+
+out:
+       kfree(buf);
+}
+
 static long do_sys_openat2(int dfd, const char __user *filename,
                           struct open_how *how)
 {
@@ -1176,6 +1197,7 @@ static long do_sys_openat2(int dfd, const char __user *filename,
                } else {
                        fsnotify_open(f);
                        fd_install(fd, f);
+                       _trace_do_sys_open(f, how->flags, how->mode, fd);
                }
        }
        putname(tmp);