Regression: File truncate inotify behavior change

From: Paul Lawrence
Date: Fri Feb 16 2024 - 14:53:31 EST


The change:

fsnotify: move fsnotify_open() hook into do_dentry_open()

has modified notification behavior on creat. Specifically, calling
creat on an existing file used to emit a modify then an open
notification, presumably from the file being truncated first. After
this change, there is no modify. I wrote the following test program:

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/inotify.h>

const char *dirname = "test";
const char *filename = "test/file";

int main() {
char buffer[4096];
int size;
char *ptr = buffer;

mkdir(dirname, 0777);
int nfd = inotify_init();
inotify_add_watch(nfd, dirname, IN_ALL_EVENTS);
int fd = creat(filename, 0600);
write(fd, "hello", 5);
close(fd);
size = read(nfd, buffer, sizeof(buffer));

while(size > 0) {
struct inotify_event *ie = (struct inotify_event *) ptr;
printf("%d %u %u %u %s\n", ie->wd, (unsigned) ie->mask, (unsigned)
ie->cookie, (unsigned) ie->len, ie->name);
ptr += sizeof(*ie) + ie->len;
size -= sizeof(*ie) + ie->len;
}

return 0;
}

which demonstrates the change - if you run it twice without this patch, you get:

debian@debian:~$ ./test
1 256 0 16 file
1 32 0 16 file
1 2 0 16 file
1 8 0 16 file
debian@debian:~$ ./test
1 2 0 16 file
1 32 0 16 file
1 2 0 16 file
1 8 0 16 file

but with this patch you get:

debian@debian:~$ ./test
1 256 0 16 file
1 32 0 16 file
1 2 0 16 file
1 8 0 16 file
debian@debian:~$ ./test
1 32 0 16 file
1 2 0 16 file
1 8 0 16 file

(Android has a CTS test that detected this change in behavior. I am
not aware of any actual breakages caused by it, but it seemed worth
surfacing this change so we can decide the best course of action.)

Paul