Apply aa983d2b to v0.6 branch

Just a cherry-pick.  As v0.6 is the latest version works on FreeBSD, BSD specific changes needs to be merged to v0.6 branch.