It may be dirt to us, but it is a useful element to them.
Dirt is a sunscreen, protecting their skin from sunburn, especially where hair is sparse or short.
Dirt dries them off if they are wet or sweaty.
Dirt is a pest repellent. It makes it harder for insects to bite them.
Dirt scratches their itches while they are rolling. You can see this as they roll onto their backs and wiggle around.
BTW, it isn't just these two species but many. If you watch cattle, they paw the ground to create a dust storm around themselves. Even cats, as fastidious as they are known to be, will roll in the dirt.
We have to stop looking at things from a human angle and begin looking at it from their point of view if we want to understand why they do things.