How does a CPU change frequency?
The clock that the CPU uses does not come directly from the crystal oscillator in the motherboard ! The (fixed frequency) clock from the crystal oscillator is first fed to a system called a Phase Locked Loop or PLL. This PLL can be a separate chip on the motherboard but also inside any of the other chips or both.

The simplest PLLs can only multiply the fixed frequency clock from the crystal oscillator so if the crystal oscillator runs at 40 MHz then such a PLL can generate 80 MHz, 120 MHz, 160 Mhz, etc. Basically n times the crystal clock frequency.

More advanced PLLs can also make almost any frequency in between by using a fracional divider and sigma-delta modulation techniques.