Backport of bacdfbf3d1eb23ff8e8110681728a5b467443446 and e5d3f98abcdc20d64d99609bd0aa82331835b439 from master