From emaste at freebsd.org, originally part of FreeBSD commit r339216 / fc3c19a9 with autoconf bits added by me.