Carbon solubility in a liquid iron alloy containing nitrogen and sulfur has been studied experimentally in a carbon-saturated Fe-C-N-S-B system at pressures of 5.5 and 7.8 GPa, temperatures of 1450 to 1800 °C, and oxygen fugacities from the IW buffer to log fO2 ΔIW-6 (ΔIW is the logarithmic difference between experimental fO2 and that imposed by the coexistence of iron and wüstite). Carbon saturation of Fe-rich melts at 5.5 and 7.8 GPa maintains crystallization of flaky graphite and diamond. Diamond containing 2100-2600 ppm N and 130-150 ppm B crystallizes in equilibrium with BN within the diamond stability field at 7.8 GPa and 1600 to 1800 °C, while graphite forms at other conditions. The solubility of carbon in the C-saturated metal melt free from nitrogen and sulfur is 6.2 wt% C at 7.8 GPa and 1600 °C and decreases markedly with increasing nitrogen. A 1450-1600 °C graphite-saturated iron melt with 6.2-8.8 wt% N can dissolve: 3.6-3.9 and 1.4-2.5 wt% C at 5.5 and 7.8 GPa, respectively. However, the melt equilibrated with boron nitride and containing 1-1.7 wt% sulfur and 500-780 ppm boron dissolves twice less nitrogen while the solubility of carbon remains relatively high (3.8-5.2 wt%). According to our estimates, nitrogen partitions between diamond and the iron melt rich in volatiles at DN Dm/Met = 0.013-0.024. The pressure increase in the Fe-C-N system affects iron affinity of N and C: it increases in nitrogen but decreases in carbon. The reduction of C solubility in a Fe-rich melt containing nitrogen and sulfur may have had important consequences in the case of imperfect equilibration between the core and the mantle during their separation in the early Earth history. The reduction of C solubility allowed C supersaturation of the liquid iron alloy and crystallization of graphite and diamond. The carbon phases could float in the segregated core liquid and contribute to the carbon budget of the overlying silicate magma ocean. Therefore, the process led to the formation of graphite and diamond, which were the oldest carbon phases in silicate mantle.