Why does anyone do anything they are not directly drawing a paycheque for doing? Some people volunteer to teach little legue.
Companies come together and contribute to FOSS projects where the company benefits. Microsoft contributed code to the kernel for VirtualPC compatibility (think it was the server virtualization app actually). Several big companies contribute to the kernel because it benefits there hardware business; HP, IBM, Dell. The kernel being a little scewed towards server use (eg. scheduler) reflects the benefits the server retailers gain by contributing.
Businesses who sell FOSS developed code may be using a community based R&D version from which they include the best ideas into the production targeted retail version. Red Hat does this with Fedora -> Red Hat Enterprise Linux. The first is the community version; the melting pot of new ideas. The second is the stable version meant for production server rooms. You get the same at the application level; a free version and a more enabled or closer supported retail version. Splunk has a freely available version (4 nodes or 500 MB of logs per day) but once you go over that limit your into paying enterprise pricing. Virtualbox; free for personal use with a more enabled retail version for professional use.
In terms of the individual, motivations differ. For some, writing code may simply be recreation; enjoyment outside work hours. I spend all day playing admin at work only to come home and spend my free time at home in front of my own machines. Maybe one is modifying an existing program to fit a new need; eg. modifying a program that counts beans so it shows separate counts by colour in addition to the total.
In economic terms, it is not a retail economy; a developers value is not measured by how much money they can produce. It is an information economy; a developers value is measured by what skill they demonstrate in their coding. It is a meritocracy; one is measured based on what they do; write shoddy code and your economic value drops with "oh, yeah, that guy's code is a mess."
A good source is Eric S Raymond's essays including Cathedral and the Bazaar and a few other discussions of FOSS social structure and potential business models. The Magic Cauldron is probably where you want to start though.
The Magic Cauldron
This paper analyzes the economics of open-source software. It includes some explosion of common myths about software production economics, a game-theoretical account of why open-source cooperation is stable, and a taxonomy of open-source business models.
Keep Up with TechRepublic