I had the same problem on my E34. I'm not 100% if the E39 has the same mechanism but i'll detail the problem and solution for the e34 and you can figure the rest out yourself
So what happens is the power up/down on the headrest turns a flexible worm cable. this cable is accessible through the back of the seat. After time the cable can 'tighten' and doing so, gets shorter. Because the cable is encased in a solid plastic sheathe and as it gets shorter, it slowly pulls away from the slot that it fits into, so that when the motors spins it, you just hear a 'click click click' noise.
The solution is to pull off the back of the seat, cut away a chunk of the plastic sheathe without damaging the cable inside, and shorten the sheathe.