Thermodynamics of magnetic refrigeration