diff --git a/fs/inode.c b/fs/inode.c index 13ceb98c3bd3..93af998ee290 100644 --- a/fs/inode.c +++ b/fs/inode.c @@ -2110,6 +2110,30 @@ void inode_nohighmem(struct inode *inode) } EXPORT_SYMBOL(inode_nohighmem); +/** + * timespec64_trunc - Truncate timespec64 to a granularity + * @t: Timespec64 + * @gran: Granularity in ns. + * + * Truncate a timespec64 to a granularity. Always rounds down. gran must + * not be 0 nor greater than a second (NSEC_PER_SEC, or 10^9 ns). + */ +struct timespec64 timespec64_trunc(struct timespec64 t, unsigned gran) +{ + /* Avoid division in the common cases 1 ns and 1 s. */ + if (gran == 1) { + /* nothing */ + } else if (gran == NSEC_PER_SEC) { + t.tv_nsec = 0; + } else if (gran > 1 && gran < NSEC_PER_SEC) { + t.tv_nsec -= t.tv_nsec % gran; + } else { + WARN(1, "illegal file time granularity: %u", gran); + } + return t; +} +EXPORT_SYMBOL(timespec64_trunc); + /** * current_time - Return FS time * @inode: inode. diff --git a/include/linux/fs.h b/include/linux/fs.h index 760d8da1b6c7..7f6997e0dabf 100644 --- a/include/linux/fs.h +++ b/include/linux/fs.h @@ -1476,6 +1476,7 @@ static inline void i_gid_write(struct inode *inode, gid_t gid) inode->i_gid = make_kgid(inode->i_sb->s_user_ns, gid); } +extern struct timespec64 timespec64_trunc(struct timespec64 t, unsigned gran); extern struct timespec current_time(struct inode *inode); /*