Initial backport of #1558