В ядре Linux была устранена следующая уязвимость: fs: избегать повторных сканирований в evict_inodes() We наблюдались зависшие задачи, когда пользователи пытались демонтировать файловую систему после того, как её диск был удалён во время ещё использования. Во время удаления устройства fs_bdev_mark_dead() вызывает evict_inodes(), удерживая при этом s_umount. Каждый раз, когда evict_inodes() сбрасывает s_inode_list_lock для переноса, он перезапускает ход с головы s_inodes.
Со многими ссылками на inodes во главе списка, эти перезапуски неоднократно сканируют одни и те же inodes, не возвращая их. Это может удерживать s_umount в течение длительного времени, блокируя одновременные попытки umount и запуская отчеты с подвешенными задачами. Держите текущий inode, уже отмеченный I_FREEING, вне утилизационной партии, пока s_inode_list_lock не будет повторно приобретен.
Возобновите прогулку из этого inode и утилизируйте его в более поздней партии или в конце прогулки. Нулевой пересчет и проверка состояния в i_lock позволяют этому ходуну требовать inode, устанавливая I_FREEING и удаляя его из LRU. Другие исполнители пропускают inode, оставляя этого ходока ответственным за выселение.
Только evict() удаляет его из s_inodes, поэтому сохранение его из партии утилизации гарантирует, что он остается в списке, пока блокировка сбрасывается. После повторного получения блокировки чтение ее текущего следующего указателя учитывает одновременное удаление следующих inodes. Существующие правила inode lifetime запрещают получение ссылки на inode с пометкой I_FREEING или I_WILL_FREE. __iget() требует, чтобы его абонент держал i_lock и установил, что получение ссылки является действительным.
Inode lookup и igrab() проверяют эти флаги под i_lock при получении ссылки с нуля. ihold() требует существующей ссылки, которая сохранит i_count ненулевым и не позволит этому ходуну претендовать на inode. Эти правила уже позволяют iput_final() и inode-усадщику выпускать i_lock после установки I_FREEING и до завершения выселения. Временная ссылка __iget() также сохранит inode в списке, но его выпуск должен сохранить обработку последней ссылки.
Другой пользователь может получить ссылку, обновить ленивые метки времени и отказаться от ее ссылки, пока удерживается контакт. Если контакт становится последней ссылкой, отбрасывание его с помощью atomic_dec_and_test () и выселение напрямую обходит обработку iput()'s по лени и может потерять эти обновления меток времени. fs_bdev_mark_dead() работает с набором SB_ACTIVE, поэтому iput() может сохранять inode в кэше, в то время как evict_inodes() должен выселять иноды с нулевой ссылкой. Инод также может быть освобожден, когда iput () возвращается, поэтому ходок не может использовать его для принудительного выселения.
Использование I_FREEING сохраняет существующее поведение выселения без введения дополнительного перехода с последней ссылкой. Автогруппа xfstests перешла на ext4 и XFS с известными несвязанными отказами, исключенными. Никаких новых проблем не наблюдалось, и ранее воспроизводимая зависшая задача больше не возникает с этим патчем.
Показать оригинальное описание (EN)
In the Linux kernel, the following vulnerability has been resolved: fs: avoid repeated scans in evict_inodes() We observed hung tasks when users attempted to unmount a filesystem after its disk had been removed while still in use. During device removal, fs_bdev_mark_dead() calls evict_inodes() while holding s_umount. Each time evict_inodes() drops s_inode_list_lock to reschedule, it restarts the walk from the head of s_inodes. With many referenced inodes at the head of the list, these restarts repeatedly scan the same inodes without reclaiming them. This can keep s_umount held for a long time, blocking concurrent umount attempts and triggering hung-task reports. Keep the current inode, already marked I_FREEING, out of the disposal batch until s_inode_list_lock is reacquired. Resume the walk from this inode and dispose of it in a later batch or at the end of the walk. The zero-refcount and state checks under i_lock allow this walker to claim the inode by setting I_FREEING and removing it from the LRU. Other reclaimers skip the inode, leaving this walker responsible for eviction. Only evict() removes it from s_inodes, so keeping it out of the disposal batch ensures that it remains on the list while the lock is dropped. After reacquiring the lock, reading its current next pointer accounts for concurrent removal of following inodes. The existing inode lifetime rules prohibit acquiring a reference to an inode marked I_FREEING or I_WILL_FREE. __iget() requires its caller to hold i_lock and establish that taking a reference is valid. Inode lookup and igrab() check these flags under i_lock when acquiring a reference from zero. ihold() requires an existing reference, which would keep i_count nonzero and prevent this walker from claiming the inode. These rules already allow iput_final() and the inode shrinker to release i_lock after setting I_FREEING and before eviction completes. A temporary __iget() reference would also keep the inode on the list, but its release must preserve last-reference handling. Another user can acquire a reference, update lazy timestamps and drop its reference while the pin is held. If the pin becomes the last reference, dropping it with atomic_dec_and_test() and evicting directly bypasses iput()'s lazytime handling and can lose those timestamp updates. Releasing the pin with iput() preserves that handling, but does not guarantee eviction. fs_bdev_mark_dead() runs with SB_ACTIVE set, so iput() may retain the inode in cache, whereas evict_inodes() must evict eligible zero-reference inodes. The inode may also have been freed when iput() returns, so the walker cannot then use it to force eviction. Using I_FREEING preserves the existing eviction behavior without introducing an additional last-reference transition. The xfstests auto group passed on ext4 and XFS with known unrelated failures excluded. No new issues were observed, and the previously reproducible hung task no longer occurs with this patch.