Magnetite forms in small quantities interspersed with many iron-rich minerals, but only forms bodies of crystals on its own when mafic magma, a very liquid magma laden with heavy elements, cools sufficiently slowly for individual crystals to clump together. Magnetite can also form during metamorphism of impure iron-rich limestone.
The formation of magnetite during the geological metamorphism of limestone only occurs with limestone that formed before oxygen levels on Earth were sufficient for dissolved iron to accumulate in the oceans. This iron reached levels where it clumped and solidified out of the ocean water, forming iron ores on the sea floor. Some of this iron ore, when undergoing geologic processes involving heat and pressure, became magnetite. Photosynthetic organisms have since greatly increased the levels of oxygen on Earth, and iron no longer persists in the oceans, as it is oxidized too quickly.
Magnetite is one of the few naturally occurring magnetic materials, and as it forms, its magnetic poles align with those of the Earth. Once formed, however, the magnetite's magnetic alignment does not change, even if Earth's magnetic field changes. This property provides scientists with a record of how the Earth's magnetic fields have behaved stretching back billions of years.