Wells Fargo (WFC), the largest U.S. home lender, said Monday it has agreed to pay $591 million to Fannie Mae to settle substantially all of its repurchase liabilities tied to loans sold to the government-controlled mortgage company before Jan. 1, 2009.

After adjusting for credits related to certain earlier repurchases, Wells Fargo will pay Fannie Mae about $541 million in cash.

San Francisco-based Wells Fargo said in a statement that the cost of the agreement has been fully accrued for as of Sept. 30.

Fannie Mae and Freddie Mac support the U.S. housing market by buying loans from lenders and packaging them into securities then selling those packaged loans to investors as mortgage-backed securities.

During the housing boom leading up to the financial crisis of 2008, the two government-sponsored finance companies dramatically stepped up their role in the housing financing sector.

But after billions of dollars of loans purchased by Fannie and Freddie soured due to defaults by millions of homeowners, the entities have demanded that lenders buy back loans that didn’t originally meet federal guidelines.

All those soured loans nearly bankrupted Fannie and Freddie and in 2008 the U.S. Treasury was forced to step in with a massive taxpayer-funded bailout. Eventually, the two were kept alive with more than $150 billion in government funds.

Since the housing market has picked up as the U.S. economy has slowly recovered Fannie and Freddie have returned to profitability, using dividends to almost pay off their bailout loans.

Wells Fargo's deal is the second related to bad loans sold to U.S. government housing entities in the years leading up to the housing crisis. Deutsche Bank (DB) recently agreed to pay $1.93 billion to settle a lawsuit filed by the Federal Housing Finance Agency, which oversees Freddie and Fannie.

Wells Fargo’s shares were down 11 cents, or 0.24%, at $45.39 at 10 a.m. EST.

Follow Dunstan Prial on Twitter @DunstanPrial