Section 14.33

Dynamic patching and hot update

Definition

Dynamic patching, also called hot update, hotpatching or live patching, is the practice of changing the code or data of a running program without stopping and restarting it. An updater loads the new version beside the old one, switches the program to it, for example by changing a function pointer, and later frees the old version. The program keeps its state, such as variables and open connections, across the switch, so correctness depends on the switch and on that state, not only on the new code.

The idea

A network router holds 10,000 open connections, and a fix arrives for one faulty function. Restarting the router applies the fix but drops every connection and stops traffic for seconds. A hot update replaces only the faulty function while traffic continues. The difficulty is the moment of replacement. A thread, one sequence of instructions that the operating system schedules, may be halfway through the old function at that moment: its program counter §2.9 points into the old code, its stack holds the old function’s local variables, and the data it wrote follows the old version’s rules.

The core idea is to separate two groups. New calls must find the new version; calls already in progress keep running the old one. The old version can be removed only when nothing can still be using it. A road diversion is a fair picture: a new signpost at the junction sends every new car onto the new road, cars already on the old road drive on to its end, and the old road closes only after the last of them has left. The picture stops at data. Cars carry nothing that must be converted, whereas data written by the old code may be in a format that the new code reads differently.

How it works

A hot update passes through five steps. Call the old version AA and the new version BB.

  1. Prepare. Build BB, check it, and load it into memory beside AA without touching AA. The check covers origin, meaning that the update comes from an authorized party, for example by verifying a digital signature §5.14, a value that only the holder of a private key can compute; it must also cover compatibility, meaning that BB accepts the data, locks and calling conventions that AA uses.

  2. Transform the state. If BB stores data differently, convert the existing data to BB’s format at a moment when no code of AA can still read or write it, or give BB new fields so that the old fields keep their old meaning.

  3. Publish. Redirect future calls to BB with one store that other processors see either completely or not at all: change a function pointer or an entry in a dispatch table §2.39, a table of function addresses through which calls are made, or overwrite the first instruction of AA with a jump to BB, which turns that location into a trampoline §14.28, a small piece of code that only redirects execution. That store is the linearization point §8.6 of the update: calls that start before it run AA, and calls that start after it run BB.

  4. Wait. Calls already inside AA continue in AA, so AA must stay in memory. Wait for a quiescent point §14.34: a moment after which no thread is executing AA, no stack frame (the record that a call in progress keeps on its thread’s stack) holds a return address into AA, meaning an address in AA at which execution resumes when a called function returns, and no stored pointer, such as a registered callback §14.22 or a queued job, leads into AA.

  5. Retire. Free the memory of AA.

A thread that is inside AA at the switch can be treated in three ways.

Rewriting machine code where it stands adds hardware obligations. Another processor core may fetch the instruction bytes while they are half written, so the change must be made by one aligned store that the processor performs atomically, or the code must first be made unreachable. A processor with an instruction cache, a small fast memory that holds copies of recently fetched instructions, may go on executing the old bytes until the cache is cleaned and invalidated and the processor’s pipeline of fetched instructions is flushed. On a microcontroller §6.1 that runs its program from flash memory §6.6, code cannot be changed one word at a time, because flash must be erased a whole page at a time before most changes can be written. Such systems redirect execution instead, through pointers or through a hardware unit such as the Flash Patch and Breakpoint §14.29 unit described in the Breakpoint and watchpoint entry.

Worked example

Calls in flight. Two calls, c1c_1 and c2c_2, are executing AA when the function pointer changes to BB at time 0. A third call, c3c_3, starts at time 1, reads the pointer and runs BB. The number of calls still in AA is 2 at time 0; c1c_1 returns at time 3, leaving 1; c2c_2 returns at time 5, leaving 0. With no other path to AA, such as a saved pointer or a queued callback, time 5 is the quiescent point, and AA may be freed from then on. Freeing AA at time 0 would have sent c1c_1 and c2c_2 into freed memory.

A hidden return address. At time 4, c2c_2 is inside a helper function §2.19 hh that AA called. A check that looks only at the program counter of each thread finds c2c_2 in hh, not in AA, and wrongly concludes that no call is in AA. But c2c_2’s stack holds the return address, the address of the instruction in AA at which execution continues when hh returns. Had AA been freed at time 4, hh would have returned into freed memory. A sound check also searches every stack for return addresses into AA.

A changed meaning. AA stores a timeout §9.34 in a field as a number of milliseconds, and BB reads the same field as microseconds. The stored value is 2, meaning 2 milliseconds. If BB reads the value unchanged, the timeout becomes 2 microseconds, 1000 times too short. Converting multiplies by 1000: 2×1000=20002 \times 1000 = 2000 microseconds. But if a call still running AA reads the field after the conversion, it takes 2000 as milliseconds, 2 seconds, 1000 times too long. The conversion is safe only after the last code of AA that reads the field has finished, or if BB uses a new field and leaves the old one as it was.

Stated precisely

Let AA be the old version, BB the new version, and tpt_p the moment of the publishing store. A hot update is correct when all four of the following hold.

  1. Atomic publication. A call that reads the redirect after tpt_p runs BB, an earlier call runs AA, and no call sees a mixture. This needs the redirect to change in one atomic store, and BB’s code and data to be completely written and visible to every processor before that store, which a memory barrier §4.37, an instruction that orders memory accesses, ensures.

  2. Compatible state at every moment. Each piece of shared state is, at every moment, in a format that every version still able to read or write it understands.

  3. Safe retirement. AA is freed only after a quiescent point: no thread executes AA, no stack holds a return address into AA, no stored pointer leads into AA, and the redirect can no longer lead a new call to AA.

  4. Valid state for BB. The invariants the program relies on, such as a count that equals the length of a list, hold for the converted state as BB interprets it.

These four conditions are safety properties §1.11: they say that nothing bad happens. Whether the quiescent point of the third condition is ever reached is a separate liveness property §1.12. A thread that never leaves AA, such as one that runs an endless loop inside it, prevents retirement for ever, and a correct update mechanism may then wait indefinitely.

Two meanings of in place

The phrase in place has two meanings in update vocabulary. In the first, an update applied in place is applied to a running system without a reset, a reboot or reflashing, the writing of a new program image into flash memory; a hot update is in place in this sense. In the second, used for storage, an in-place write overwrites the current copy at its own location, so that while the write is in progress neither the old nor the new copy is whole, and an interrupted write leaves a torn write §8.19.

A two-slot commit writes the new version into a second, inactive slot and then switches a selector that names the active slot, as an A/B update §8.10 does. It deliberately avoids the storage meaning: it never overwrites the copy in use. It achieves the first meaning only if the running program can switch to the other slot by itself, as it can for a table or module that the program reaches through a pointer. A firmware image that the processor executes from its slot normally switches at the next reboot. A hot update that writes BB beside AA and changes a pointer is in place in the first meaning and not in the second; rewriting the instructions of AA where they stand is in place in both meanings, and must then also prevent torn writes.

Limits and common mistakes

Continuing without a restart is not the same as migrating state correctly. A hot update can keep every connection open and still corrupt the data of each one.

Authenticating an update shows who sent it. It does not show that the update is compatible with the running state, safe or timely.

Some changes are hard to apply hot: a new layout for a structure that many functions share, a function that never returns, such as a main loop, an interrupt handler §6.12 that is already running, or device settings that AA made and BB interprets differently.

Switching in memory and recording the switch in storage are separate steps. An update that must survive a reboot must also be written durably, and either step can fail while the other succeeds.

Undoing a hot update is itself a hot update, with the same obligations in the opposite direction.

The wait for a quiescent point has no bound unless every user of AA finishes within a bounded time. A mechanism that is safe can still be slow or never finish.

Questions answered

What happens if a thread is executing the old code during replacement?

The thread keeps executing the old code. Changing a function pointer or placing a jump affects only calls that start afterwards; it does not move a call already in progress, whose program counter, local variables and return addresses still refer to the old version. The update must therefore handle that thread in one of three ways. It can keep the old code and data in memory and let the thread finish there, freeing the old version only at a quiescent point, when no thread executes it, no stack frame returns into it and no stored pointer leads to it. It can delay the switch until no thread is inside the affected code. Or it can stop the thread at a known point and convert its state to the new version. While old and new code run side by side, they must agree on the format of every piece of shared data.

If the updater frees or overwrites the old code while the thread is still inside it, the thread executes freed memory or a half-written mix of old and new instructions, which typically crashes the program or corrupts its data.

Related entries: Trampoline (§14.28), Quiescent point (§14.34), Linearization point (§8.6), Peak versus retained memory (§11.37), Read-copy update (RCU) (§9.20), A/B update (§8.10), Torn write (§8.19), Breakpoint and watchpoint (§14.29).