Why does writing/erasing flash configuration words clear the entire program memory?
This happens when the last eight words of the code space (also called the Flash Configuration Words) is reserved and should be written with configuration data, not executable code. The location of Flash Configuration Words is 0FFF0h:0FFFFh. Between the configuration bytes is the code protection bit. For purposes of code protection, the program memory for every device is treated as a single block. By altering this bit, you protect the entire code memory and not just individual segments, so the entire code will be read as 0x0000.
Read and store the Flash Configuration Words, erase the memory and restore the Flash Configuration Words as all of the configuration registers are automatically loaded from the eight Flash Configuration Words.
This is possible only for devices where the configuration registers are not continuously monitored during operation. Continuously monitoring means that their values are compared to complimentary shadow registers. If a mismatch is detected between the two sets of registers, a reset automatically occurs. If this is the case, restoring the Flash Configuration won't work.