Backport 92c1822c73b1acd08c0d80fa0efd32604e2ee7c0 and 802cf250348a51e96eafe0eaf07dd25005cbd891