Backport of 4013e26670c5 and 60210a3d86dc for 4.9 to 5.10