I have few questions here:
- Did Gandalf know the origin of Glamdring? If so, how did he know it?
- Is it explained in the books how Glamdring made its way to a troll's treasure hoard or who had it before Gandalf?
Gandalf and the Dwarves (and Bilbo) were told about the origins of Glamdring, Orcrist and Sting by Elrond in Rivendell:
Elrond knew all about runes of every kind. That day he looked at the swords they had brought from the trolls' lair, and he said: "These are not troll-make. They are old swords, very old swords of the High Elves of the West, my kin. They were made in Gondolin for the Goblin-wars. They must have come from a dragon's hoard or goblin plunder, for dragons and goblins destroyed that city many ages ago. This, Thorin, the runes name Orcrist, the Goblin-cleaver in the ancient tongue of Gondolin; it was a famous blade. This, Gandalf, was Glamdring, Foe-hammer that the king of Gondolin once wore. Keep them well!"
Glamdring was therefore originally owned by Turgon, king of Gondolin, and the "Goblin-wars" were the battles of the Elves of Beleriand against Morgoth, most likely in the case the Battle of Unnumbered Tears, since it was the only time the Host of Gondolin came out to fight.
The only hint of its origin is given further in the text:
"Whence did the trolls get them, I wonder?" said Thorin looking at his sword with new interest.
"I could not say," said Elrond, "but one may guess that your trolls had plundered other plunderers, or come on the remnants of old robberies in some hold in the mountains of the North."