my cats seem to do it when they are happy, or they might do it to get comfortable? because they seem to settle after doing it for a while, or maybe sharpening their claws gently??
It is an unconscious reaction to contentment, much like their purr. The kneading action is ingrained from kittenhood, when from birth kitties alternately press their paws against mama's belly while nursing, in an effort to stimulate lactation.
I asked this question when I was a kid and we had our first kitten. My mum told me that it was something wild cats did in their nest before they lay down to sleep - to make sure that no snakes had got in the bedding.