3

I have this question specific for the arm architecture.

I have seen in the ARM Register set we have link register (r14) and program counter (r15). During context switch time link register gets the address of program counter value of last function executed. but context switch also stores the program counter value.

Why do we need to save the program counter register status as we have link register that already has the program counter value ?

user2760375
  • 2,238
  • 2
  • 22
  • 29
  • 2
    As Dr. Emmett Brown once said "This one shows where you're going, this one shows where you are, this one shows where you were". The `pc` is the address of the instruction being executed, the `lr` is the next address on from where the last `bl` occurred, so you are able to return. – Colin Mar 09 '17 at 09:07
  • Further to this the LR has a special meaning when in an exception. It contains the EXC_RETURN code. See the Cortex-m user guides. – Realtime Rik Mar 09 '17 at 13:56
  • Your question needs a little clarification. Are you talking about a pre-emptive reschedule (due to a timer interrupt) or co-operative multi-tasking where a function is called? The ARM has separate (banked registers) for different operating modes. Also see: [ARM Link and frame pointer](http://stackoverflow.com/questions/15752188/arm-link-register-and-frame-pointer/) which deals with many of the same concepts for user space. For an OS, you need to detail whether cortex-m, cortex-a, ARM64, or legacy for fine details. – artless noise Mar 09 '17 at 14:05

1 Answers1

3

Let's say thread one is running, and it is executing instruction 0x1000, it calls a function located at 0x2000 at this point, and the Link register stores 0x1004. The PC has moved to the location where the function is located, 0x2008 (There are some gotchas about how PC is updated, if I remember right it is 2 words ahead of the current instruction being fetched).

Now a context switch occurs and another thread needs to start running. You will need to store the PC which is 0x2008 and also the LR which is 0x1004 so that after you switch back you can jump back to your earlier function.

revelationnow
  • 356
  • 1
  • 7