Using hybrid density functional theory, we address point defects susceptible to cause charge compensation upon Mg doping of GaN. We determine the free energy of formation of the nitrogen vacancy and of several Mg-related defects. The entropic contribution as a function of temperature is determined within the quasiharmonic approximation. We find that the Mg interstitial shows a noticeably lower free energy of formation than the Mg substitutional to Ga in p-type conditions. Therefore, the Mg impurity is amphoteric behaving like an acceptor when substitutional to Ga and like a double donor when accommodated in an interstitial position. The hybrid-functional results are then linked to experimental observations by solving the charge neutrality equations for semiconductor dominated by impurities. We show that a thermodynamic equilibrium model is unable to account for the experimental hole concentration as a function of Mg doping density, due to nitrogen vacancies and Mg interstitials acting as compensating donors. To explain the experimental result, which includes a dropoff of the hole concentration at high Mg densities, we thus resort to nonequilibrium models. We show that either nitrogen vacancies or Mg interstitials could be at the origin of the self-compensation mechanism. However, only the model based on interstitial Mg donors provides a natural mechanism to account for the sudden appearance of self-compensation. Indeed, the amphoteric nature of the Mg impurity leads to Fermi-level pinning and accounts for the observed dropoff of the hole concentration of GaN samples at high Mg doping. Our work suggests that current limitations in p-type doping of GaN could be overcome by extrinsically controlling the Fermi energy during growth.