It's all controlled by the Hatch-Waxman Act; the Wikipedia article is better than the average one on a controversial subject, though out of date. But even when a patent expires, the generic doesn't get to sell until they get FDA approval that they're manufacturing the generic to a +/-20% approximation of the original drug. I've had pharma execs complain bitterly to me that the generics aren't the same thing.
Wrt to generics cutting sweetheart deals with patent holders ("pay for delay"), the FTC has been complaining about it for years, but pharma kept beating it back in court -- until last year, and now the Supreme Court is stepping in to resolve the question once and for all, or at least until lobbyists on one side or the other get to Congress. It's getting argued in three weeks, so you'll start to see a lot of news stories about the issue soon.
Here's the summary of the upcoming case involving Andrew Sullivan's favorite career pick-me-up AndroGel:
Issue: Whether reverse-payment agreements are per se lawful unless the underlying patent litigation was a sham or the patent was obtained by fraud (as the court below held), or instead are presumptively anticompetitive and unlawful (as the Third Circuit has held). (Alito, J., recused)
The Foley law firm explains:
ANDA litigation often is settled by a "reverse payment" agreement, wherein the patent owner pays the would-be generic company (the ANDA filer) to stay off the market for a period of time. (It is called a "reverse" payment because usually it is the infringer who pays the patent owner.)
In other words, the firm with the original patent pays the challenger to take a dive in the lawsuit.
While patents are given special treatment under antitrust laws, the FTC does not like reverse payment settlement agreements. According to the FTC's assertions in its petition for certiorari in the Watson AndroGel® case:
Reverse-payment agreements tend to support monopoly pricing of brand-name drugs by delaying the onset of generic competition ....
Reverse-payment agreements ... [cost] consumers billions of dollars each year.
The FTC also implies that the majority of patents would be invalidated if litigation proceeded:
[A] substantial fraction of fully litigated patent cases have, historically, resulted in a finding of patent invalidity.
Overall, in cases litigated to decision, would-be generic competitors have prevailed three quarters of the time in paragraph IV patent litigation against brand-name manufacturers.
This sounds boring, but giant piles of money are involved.