forward-port from 2.X commits 5827-6000 including