Section 9.28

Asynchronous completion

Definition

Asynchronous completion separates submitting an operation from learning how it ended. The caller can continue while work is in progress. A callback §14.22 (a function the caller supplies), a status it polls, or a future (an object that holds the result when available) reports completion. A fast operation can finish before the submitting call returns. Until the completion, the operation may still use memory the caller handed over, so the interface must state when that memory returns to the caller.

The idea

A program sends a 64-byte message over a radio. Transmission takes milliseconds, and the program has other work to do. So the driver, the code that controls the radio, records a pointer to the program’s buffer in its transmit queue and returns at once. Later, the radio hardware reads the 64 bytes straight from that buffer and sends them. If the program refills the buffer as soon as the call returns, the radio may send the new contents. If the program frees the buffer and the memory is handed to another part of the program, the radio may send that part’s data, which could be a secret key.

The picture is a copy shop. The receipt you get at the counter says the order was accepted, not that the copies exist. Until the shop says the job is done, your original stays with the shop and must not be altered. Two ideas carry over. Submission and completion are different events at different times, and each piece of memory belongs to exactly one party at a time. The picture stops at one point. A copy shop’s “done” has one meaning, while a software completion can mean several different things: the input was copied, the bytes left the device, the peer received them, or they were stored permanently. The interface must say which.

How it works

Every asynchronous interface fixes three things.

  1. What submission does with the input. There are three possible contracts.

    • Copy: the interface copies the input before submission returns. The caller may reuse its buffer at once. The price is extra memory and the time of the copy.

    • Borrow: the interface keeps a pointer to the caller’s buffer, a borrowed pointer §4.3. The caller must keep the buffer alive and unchanged until the completion that releases it.

    • Transfer: the caller hands over ownership, the duty to free the buffer. The caller must not touch the buffer again, and the interface or its completion handler frees it.

  2. What the completion means. “Accepted into a queue”, “the last read of the input has happened”, “the bytes left this device”, “the peer acknowledged the bytes” and “the data is stored permanently” are different events at different times. The interface names the one that releases the buffer.

  3. How and where the completion is delivered. A callback may run in an interrupt handler §6.12 or in another thread, and it may even run before the submission call has returned. Polling, a completion queue (a queue into which the system places a record for each finished operation) or a future lets the caller collect the result when it chooses.

Three rules keep the pattern correct.

  1. Exactly one final completion per accepted submission, whether the operation succeeded, failed or was canceled. A missing completion leaves the buffer allocated forever; a duplicate one frees it twice. A submission that is refused at once returns an error, produces no completion, and leaves ownership with the caller.

  2. The completion comes after the last use. The side doing the work signals completion only after its final access to the buffer, counting accesses by hardware and by the completion handler itself.

  3. The completion publishes the results. The worker writes its results first and signals second. The caller reads the results only after it has observed the signal, and the signal must carry memory ordering that makes the worker’s writes visible to the caller, as acquire-release ordering §9.11 does: the worker signals with a release operation, and the caller reads the signal with an acquire operation.

Worked example

A borrowing interface. Times are in milliseconds (ms).

  1. At 0 ms the caller submits a pointer to a 64-byte buffer.

  2. At 1 ms the submission returns “accepted”. The radio has not read any byte.

  3. At 5 ms the radio’s DMA §4.36 (direct memory access) engine, hardware that copies between memory and a device without the processor, starts reading the buffer.

  4. At 7 ms the engine makes its last read of the buffer.

  5. At 8 ms the completion callback runs.

Freeing the buffer at 1 ms, when the submission returns, leaves 7−1=67 - 1 = 6 ms during which the engine still reads memory that may now belong to someone else. If the memory allocator gives that memory at 3 ms to code that stores a 32-byte key in it, the radio starts transmitting the key at 5 ms. Freeing at 8 ms, after the callback, is safe, because this interface places the completion after the last read.

A copying interface. The same send copies all 64 bytes into the interface’s own buffer before returning at 1 ms, so the caller may reuse its buffer at 1 ms. The interface must keep its copy until the engine’s last read at 7 ms. With up to 8 messages waiting, it needs 8×64=5128 \times 64 = 512 bytes of its own buffer space. Copying moved the duty to keep the bytes alive. It did not make the transmission finish any earlier.

A completion before the return. A caller writes submit(buf); pending = true; and its callback writes pending = false;. The send fails at once, and the driver runs the callback inside submit. The callback sets pending to false, then submit returns and the caller sets pending to true, and pending stays true forever. The caller must set pending to true before it calls submit.

Stated precisely

For one request, let rr be the time the submission call returns, ℓ\ell the time of the last access to the buffer by anything other than the caller (a worker, a hardware engine or a handler), and cc the completion that the interface designates as the release. Write x→yx \to y when event xx comes before event yy in the happens-before relation §9.10, which means that xx is ordered before yy and yy sees the effects of xx. A borrowing interface guarantees ℓ→c\ell \to c. The caller may then free or reuse the buffer at an event ff only if c→fc \to f, which holds when the caller observed the completion before ff. A copying interface guarantees ℓ→r\ell \to r, so any ff after the return is safe. A transferring interface forbids ff by the caller altogether. In these one-shot interfaces, each accepted request has one terminal outcome: success, failure or cancellation §9.29.

In the borrowing example, r=1r = 1, ℓ=7\ell = 7 and c=8c = 8, all in ms. The return comes 7−1=67 - 1 = 6 ms before the last use, so treating rr as the release loses exactly the interval in which the engine still reads the buffer.

Limits and common mistakes

A successful return from the submission is not completion. It usually means only that the request was queued.

Completion levels differ. A local “sent” completion does not mean that the peer received the data, and an acknowledgment from the peer does not mean that the data is stored permanently. Use the level that the decision needs.

A timeout §9.34 is not a completion. When the caller stops waiting, the operation may still be using the buffer. Releasing the buffer then needs a cancellation that ends with its own final completion, as the Cancellation entry explains.

A buffer that is a local variable of a function stops existing when the function returns. Submitting it to a borrowing interface and returning before the completion produces a use-after-free §4.6, an access to memory after it has been released.

A completion handler that frees the request record must not touch the record afterwards, and nothing else may touch it after the handler runs. The interface must name the single party that frees it.

On a processor with a data cache, a buffer that a DMA engine reads or writes may also need explicit cache maintenance at submission and at completion, so that the processor and the device see the same bytes.

The pattern does not say when the completion arrives. A lost interrupt §6.11 or a stalled device means it never comes, so the caller needs a timeout and a cancellation path as well.

Questions answered

When may the caller free the request buffer?

The caller may free the request buffer only after it has observed the event that the interface names as the end of every use of that buffer. For an interface that borrows the buffer, this event is the final completion of the request: success, failure or confirmed cancellation. The return of the submission call is not that event. It usually means only that the request was queued, and the worker, a DMA (direct memory access) engine or the completion handler may still read or write the buffer afterwards.

Two other contracts give different answers. If the interface copies the input before returning, the caller may reuse or free its buffer as soon as the call returns. If the interface takes ownership of the buffer, the caller never frees it; the interface or its completion handler does. A timeout on the caller’s side never releases the buffer: the caller must cancel the request and wait for the cancellation’s own final completion.

Related entries: Borrowed pointer (§4.3), Direct memory access (DMA) (§4.36), Cancellation (§9.29), Ownership (§4.2), Use-after-free (§4.6), Acquire-release ordering (§9.11), Happens-before relation (§9.10).