How the chemistry of Mars both extended and ended its habitability