The dungeon started at the top of the castle. In medieval French, a donjon was the keep: the great fortified tower in the innermost court, the strongest part of the building and the lord's last refuge.

English took the word from Anglo-Norman, where it was spelled donjun, dongon or dongoun. The Oxford English Dictionary, as Grammarphobia reports, traces it to Latin domnus, a shortened form of dominus, "lord" or "master." Wikipedia calls the Latin link possible rather than certain. So "the lord's tower" is the likeliest reading, not a proven one.

The prison sense arrived almost as early as the tower. Wikipedia says it is first attested in 13th-century Anglo-Norman, for a keep used as a prison. In English, the OED's earliest tower example, spelled "donioun," comes from The Seven Sages of Rome, around 1330. Its earliest prison example is a Northern Homily dated before 1400, where a soul "es broht til a donjoun."

For a while English used one word for both: the tower and the secure cell inside it. The OED defines that cell as a small chamber, underground room or pit for prisoners, "esp. in the keep of a castle." Prisoners were held in the lord's tower, and the tower's name attached itself to their cell.

In early modern English the spellings divided the work. Donjon kept the tower and dungeon took the prison, according to Grammarphobia's reading of the OED. Merriam-Webster still defines donjon as "a massive inner tower in a medieval castle." French never made the switch. A French donjon is only a keep, which makes it a false friend for English speakers.

The word moved again in 1974. The first Dungeons & Dragons rules, by Gary Gygax and Dave Arneson, used it for a whole underground complex: "A good dungeon will have no less than a dozen levels down." The French edition of the game is called Donjons et Dragons. To a French ear, the monsters are back up in the tower.