In the novel, Liet Kynes tells Leto and Paul that the worms defend the spice. From this, Paul infers a likely relationship which turns out to be correct. The worms make it. But why do they do so? Is it part of their reproductive cycle? Do other desert creatures feed on it?
Why do the worms produce spice, and what role does it play in the ecology of Arrakis?
As an aside, it seems odd how little curiosity there is in universe about this extremely valuable limited resource. One would think there would be teams of planetary ecologists trying to find out everything they could!