FRANKFURT (Reuters) - Deutsche Bank, Germany's largest bank, and state-backed lender BayernLB [BAYLB.UL] have agreed to settle an $810 million lawsuit in connection with residential mortgage-backed securities, or RMBS, that Deutsche sold to BayernLB.

"We have reached a basic agreement. The final settlement has yet to be agreed," a BayernLB spokesman said in a statement.

In the suit, originally filed in a New York court in 2012, BayernLB asserted that Deutsche Bank sold the securities to external clients while secretly criticizing them within the bank and ultimately profiting from their failure.

"Deutsche Bank originated, purchased, financed and securitized exceptionally high-risk loans into these RMBS, all while internally disparaging the poor quality of these loans and the RMBS they backed as 'pigs' and 'crap,'" according to the 2012 court filing from BayernLB.

Deutsche Bank declined to comment.

In a statement dated Aug. 13, a judge for the Supreme Court of the State of New York acknowledged a notice by both banks that they had agreed in principle to settle the case out of court.

Big banks have faced numerous lawsuits filed in the United States accusing them of misleading purchasers of mortgage-backed securities and home loans about the quality of the underwriting, and of conflicts of interest that might have tainted the sales.

Among those settled are more than a dozen brought in 2011 by the Federal Housing Finance Agency to recoup losses suffered by government-controlled mortgage companies Fannie Mae and Freddie Mac.

The FHFA has so far recouped $16.1 billion, or roughly 11 cents per dollar of the underlying securities.

(Reporting by Thomas Atkins and Kathrin Jones in Frankfurt, Jonathan Stempel in New York; Editing by Arno Schuetze/Mark Heinrich)