pi: cross-port refactoring/cleanup from private branch used for ongoing upstreaming