OED has this pre-dating Shakespeare:
m. to tear (†rend) one's hair, i.e. as a symptom of passionate grief.
1548 Hall's Vnion: Henry IV f. xiiijv, This knight..sobbed, wept, and rent his heare.
1609 Shakespeare Troilus & Cressida iv. iii. 33 Teare my bright haire, & scratch my praised cheekes.
It is something which can actually be witnessed in more demonstrative cultures. Mourners can indeed pull their own hair.
As an indication of exasperation, however ("I was pulling my hair out trying to get the copier to work!") there seems to be rather less information — although Shyam's trichotillomaniaShyam's trichotillomania may well be related.