Comments in the ik solver source code explain all the math.
In the demo below, when no IK solution is possible the link arm turns red.
Instructions: drag the mouse to change viewpoint.