The minhag I've seen in Ashkenazi synagogues is to say L’Dovid (Tehillim 27) morning and evening, from Rosh Chodesh Elul until Shemini Atzeres. The earliest source I can find for this is the Mishnah Berurah (581:2), which isn’t particularly that early of a source. Further, he doesn’t give a reason for this minhag.
What is the Mishnah Berurah’s source? What is the earliest source that discusses this minhag? What is the reason (reasons?) for it?