windows_threadpool_sys/io.rs
1// Copyright (c) 2026 Mike Grier
2//! Thread-pool I/O (`TP_IO`): a completion backend over the shared overlapped
3//! submission seam.
4//!
5//! [`ThreadpoolIo`] is the third completion backend for the overlapped model
6//! defined by `windows-overlapped-io-sys`. It reuses that crate's endpoint
7//! ownership and pinned [`Operation`] storage unchanged, and adds the two
8//! concerns that only the thread pool has:
9//!
10//! - **Balanced accounting.** `StartThreadpoolIo` must precede every overlapped
11//! operation, and every start must be balanced exactly once -- by the I/O
12//! callback when a completion will be delivered, or by `CancelThreadpoolIo`
13//! when the submission failed immediately or completed synchronously on a
14//! handle in `FILE_SKIP_COMPLETION_PORT_ON_SUCCESS` mode.
15//! - **Callback-driven reclamation.** The pool, not the caller, dequeues
16//! completions. Each callback reclaims its operation's storage: typed through
17//! [`IoCompletion::claim`] when the payload type is known, or generically
18//! through the seam's `reclaim_overlapped` when the callback lets the
19//! completion drop.
20//!
21//! The pool's internal completion port is system-managed and is never exposed:
22//! this backend neither posts to it nor dequeues from it.
23
24use std::cell::Cell;
25use std::fmt;
26use std::io;
27use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, OwnedHandle};
28use std::ptr;
29use std::sync::Arc;
30
31use windows_overlapped_io_sys::{
32 Issued, Operation, OperationId, OperationRegistry, OperationState, Submitted,
33 UnassociatedEndpoint, reclaim_overlapped,
34};
35use windows_sys::Win32::Foundation::{FALSE, HANDLE, NO_ERROR};
36use windows_sys::Win32::System::IO::{CancelIoEx, OVERLAPPED};
37use windows_sys::Win32::System::Threading::{
38 CancelThreadpoolIo, CloseThreadpoolIo, CreateThreadpoolIo, PTP_CALLBACK_INSTANCE, PTP_IO,
39 StartThreadpoolIo, WaitForThreadpoolIoCallbacks,
40};
41
42use crate::callback_env::CallbackEnviron;
43
44/// Heap-allocated callback state kept alive for the lifetime of the `TP_IO`
45/// object, and freed only after [`ThreadpoolIo::drop`] has drained every
46/// operation and waited for every executing callback.
47struct IoContext {
48 live: Arc<OperationRegistry>,
49 /// This pool's entry in the self-heal registry.
50 ///
51 /// Held for its `Drop`, not read. The claim keeps the entry alive while
52 /// this object exists, which is what makes the entry's pre-created repair
53 /// work object available -- and bound to the pool, deferring its free --
54 /// if a wait on the same pool is later cancelled. Only a wait reads a
55 /// registration, because only a wait reaches the removal primitive that
56 /// owes a repair.
57 #[allow(dead_code)]
58 registration: crate::heal::Registration,
59 callback: Box<dyn Fn(&IoCompletion) + Send + Sync + 'static>,
60}
61
62/// Trampoline from the raw `PTP_WIN32_IO_CALLBACK` ABI into the boxed closure.
63///
64/// SAFETY: `context` must point to a live [`IoContext`] for the entire duration
65/// of every callback invocation, and `overlapped` must be the identity of an
66/// operation submitted through [`ThreadpoolIo::submit`] whose storage has not
67/// been reclaimed. [`ThreadpoolIo`]'s `Drop` ordering guarantees both.
68unsafe extern "system" fn io_trampoline(
69 _instance: PTP_CALLBACK_INSTANCE,
70 context: *mut core::ffi::c_void,
71 overlapped: *mut core::ffi::c_void,
72 io_result: u32,
73 bytes_transferred: usize,
74 _io: PTP_IO,
75) {
76 // SAFETY: context is a valid *mut IoContext for the full callback duration (see Drop).
77 let ctx = unsafe { &*(context as *const IoContext) };
78 crate::trace_record!("io", "trampoline-entered", overlapped as usize, io_result);
79 // Stamped before the callback, not after: a dispatch that is still running
80 // is evidence the pool is live, and a long callback must not look like
81 // silence to the self-heal.
82
83 let overlapped = overlapped.cast::<OVERLAPPED>();
84
85 // Deregister before running any user code, and take the identity from the
86 // same lookup. This balances the `StartThreadpoolIo` for this operation.
87 //
88 // It must happen here rather than after the callback: the kernel is finished
89 // with the operation by the time its callback is entered, and the callback
90 // may take ownership of the storage with `IoCompletion::claim` and drop it
91 // immediately, so the address can become available for reuse at any point
92 // from here on. The invariant is that an address is **never registered while
93 // it is available for reuse** -- otherwise a concurrent submission handed
94 // that address would collide with the entry still sitting in the registry.
95 let id = ctx.live.remove(overlapped);
96
97 // Not contained: the callback contract requires that it not unwind, and a
98 // callback that breaks it aborts here rather than being silently forgiven.
99 let completion = IoCompletion {
100 overlapped,
101 id,
102 io_result,
103 bytes_transferred,
104 claimed: Cell::new(false),
105 };
106 (ctx.callback)(&completion);
107 crate::trace_record!("io", "trampoline-left", overlapped as usize, io_result);
108}
109
110/// An owned thread-pool I/O object bound to one overlapped endpoint.
111///
112/// Creating a `ThreadpoolIo` consumes an [`UnassociatedEndpoint`], which is the
113/// same one-time, consuming association the other backends use: `CreateThreadpoolIo`
114/// binds the handle to the pool's internal completion port, and no second
115/// association is possible afterward.
116///
117/// Every [`ThreadpoolIo::submit`] is paired with exactly one balancing action, so
118/// [`ThreadpoolIo::outstanding`] is always the number of operations whose storage
119/// the kernel or pool still owns. `Drop` never frees that storage early: it
120/// cancels what is outstanding, waits for the resulting callbacks, waits for any
121/// callback still executing, and only then releases the object, the handle, and
122/// the callback context.
123///
124/// # Examples
125///
126/// Read a file with one overlapped operation. Submission is `unsafe` because
127/// only the caller can guarantee the native call it issues matches the operation
128/// it was handed; everything after that is safe.
129///
130/// ```
131/// use std::io;
132/// use std::os::windows::io::AsRawHandle;
133/// use std::ptr;
134/// use std::sync::mpsc;
135/// use windows_overlapped_io_sys::{Issued, Operation, Submitted, UnassociatedEndpoint};
136/// use windows_sys::Win32::Foundation::ERROR_IO_PENDING;
137/// use windows_sys::Win32::Storage::FileSystem::ReadFile;
138/// use windows_threadpool_sys::io::{IoCompletion, ThreadpoolIo};
139///
140/// let path = std::env::temp_dir().join(format!("wtps-doc-{}.tmp", std::process::id()));
141/// std::fs::write(&path, b"overlapped hello")?;
142///
143/// let endpoint = UnassociatedEndpoint::open(&path, true, false, 0)?;
144/// let (tx, rx) = mpsc::channel();
145/// let sender = std::sync::Mutex::new(tx);
146///
147/// let tp = ThreadpoolIo::new(endpoint, move |completion: &IoCompletion| {
148/// // SAFETY: this object only ever carries `Operation<()>`, submitted
149/// // below, and each completion is claimed exactly once.
150/// let _operation = unsafe { completion.claim::<()>() };
151/// let _ = sender.lock().expect("send").send(completion.bytes_transferred());
152/// }, None)?;
153///
154/// let mut buffer = [0_u8; 64];
155/// let buf_ptr = buffer.as_mut_ptr();
156/// let buf_len = buffer.len() as u32;
157///
158/// let mut operation = Operation::new(());
159/// operation.set_offset(0);
160///
161/// // SAFETY: issues exactly one overlapped ReadFile into `buffer`, which stays
162/// // alive until the completion is received below. The handle is not in
163/// // skip-on-success mode, so both synchronous success and ERROR_IO_PENDING
164/// // deliver a completion callback.
165/// let submitted = unsafe {
166/// tp.submit(operation, |handle, overlapped| {
167/// let ok = ReadFile(handle.as_raw_handle(), buf_ptr, buf_len, ptr::null_mut(), overlapped);
168/// if ok != 0 {
169/// return Ok(Issued::Pending);
170/// }
171/// let error = io::Error::last_os_error();
172/// if error.raw_os_error() == Some(ERROR_IO_PENDING as i32) {
173/// return Ok(Issued::Pending);
174/// }
175/// Err(error)
176/// })
177/// };
178/// assert!(matches!(submitted, Submitted::Pending(_)));
179///
180/// let read = rx.recv().expect("a completion");
181/// tp.run_down();
182/// assert_eq!(&buffer[..read], b"overlapped hello");
183///
184/// drop(tp);
185/// let _ = std::fs::remove_file(&path);
186/// # Ok::<(), std::io::Error>(())
187/// ```
188pub struct ThreadpoolIo {
189 tp_io: PTP_IO,
190 handle: OwnedHandle,
191 // Kept alive as a raw pointer until Drop has drained and waited.
192 context: *mut IoContext,
193 live: Arc<OperationRegistry>,
194}
195
196// SAFETY: PTP_IO is a cross-thread pool object and OwnedHandle is Send + Sync.
197// `context` points to an IoContext whose callback is Fn + Send + Sync and whose
198// registry is an Arc<OperationRegistry>; it is only read (never reassigned)
199// until Drop frees it after all callbacks have finished.
200unsafe impl Send for ThreadpoolIo {}
201unsafe impl Sync for ThreadpoolIo {}
202
203impl ThreadpoolIo {
204 /// Bind an overlapped endpoint to the thread pool, invoking `callback` for
205 /// every operation completion the pool delivers.
206 ///
207 /// Pass `Some(env)` to select a private pool or callback priority; `None`
208 /// uses the process-default pool with default priority.
209 ///
210 /// Do **not** point `env` at a cleanup group. A `TP_IO` object must not be
211 /// closed while an overlapped operation is outstanding, because the kernel
212 /// still owns that operation's storage, and a group's bulk release has no
213 /// way to establish that -- which is why
214 /// [`CleanupGroup`](crate::cleanup_group::CleanupGroup) has no `create_io`.
215 /// A group would also close this object while its own `Drop` still expects
216 /// to, closing it twice. Let `Drop` run it down instead: it cancels, drains,
217 /// and only then closes.
218 ///
219 /// The callback runs on a shared, process-managed pool thread. It must
220 /// restore any thread state it changes, must not terminate its thread, and
221 /// must not block waiting on this object's rundown. It must not panic: a
222 /// panic unwinds to the `extern "system"` trampoline and aborts the process.
223 ///
224 /// # Errors
225 ///
226 /// Returns the error from `CreateThreadpoolIo`, most commonly when the
227 /// handle was not opened for overlapped I/O.
228 pub fn new<F>(
229 endpoint: UnassociatedEndpoint,
230 callback: F,
231 env: Option<&mut CallbackEnviron>,
232 ) -> io::Result<Self>
233 where
234 F: Fn(&IoCompletion) + Send + Sync + 'static,
235 {
236 let handle = endpoint.into_handle();
237 let live = Arc::new(OperationRegistry::new());
238 // Read before `env` is consumed below, and registered before the object
239 // exists: the entry must be able to repair this pool from the moment
240 // anything of ours can dispatch on it.
241 let registration = crate::heal::register(crate::heal::key_of(env.as_deref()));
242 let context = Box::into_raw(Box::new(IoContext {
243 live: Arc::clone(&live),
244 registration,
245 callback: Box::new(callback),
246 }));
247
248 let env_ptr = env.map_or(ptr::null_mut(), |e| e.as_mut_ptr());
249
250 let tp_io = crate::trace_call!("CreateThreadpoolIo", handle.as_raw_handle() as usize, 0, {
251 // SAFETY: the handle is a live overlapped endpoint that no other backend
252 // has associated, context is a valid heap pointer that outlives every
253 // callback, and env_ptr is valid (or null) for the duration of this call.
254 unsafe {
255 CreateThreadpoolIo(
256 handle.as_raw_handle(),
257 Some(io_trampoline),
258 context.cast(),
259 env_ptr.cast_const(),
260 )
261 }
262 });
263
264 if tp_io == 0 {
265 let error = io::Error::last_os_error();
266 // SAFETY: the pool never saw context; reclaim it immediately.
267 unsafe { drop(Box::from_raw(context)) };
268 return Err(error);
269 }
270
271 crate::trace_record!("io", "created", tp_io, handle.as_raw_handle() as usize);
272 Ok(Self {
273 tp_io,
274 handle,
275 context,
276 live,
277 })
278 }
279
280 /// Borrow the underlying handle for issuing native operations.
281 #[must_use]
282 pub fn handle(&self) -> BorrowedHandle<'_> {
283 self.handle.as_handle()
284 }
285
286 /// The number of submitted operations whose completion callback has not yet
287 /// started.
288 ///
289 /// A `TP_IO` callback deregisters its operation on entry -- before it can
290 /// claim or drop the storage -- so this counts operations still awaiting
291 /// their callback, not live allocations: it can read zero while a final
292 /// callback is still running and its operation's storage is still alive. Use
293 /// [`run_down`](Self::run_down) to wait for callbacks to finish. It is
294 /// equivalently the number of `StartThreadpoolIo` calls not yet balanced by a
295 /// callback start or a `CancelThreadpoolIo`.
296 #[must_use]
297 pub fn outstanding(&self) -> usize {
298 self.live.len()
299 }
300
301 /// Submit an owned operation on this endpoint.
302 ///
303 /// `StartThreadpoolIo` is issued before `issue` runs, as the SDK requires,
304 /// and is balanced exactly once: by the I/O callback on the
305 /// [`Issued::Pending`] path, or by `CancelThreadpoolIo` here on the
306 /// synchronous-completion and immediate-failure paths.
307 ///
308 /// `issue` performs the single native overlapped call using the endpoint's
309 /// handle and the operation's stable `OVERLAPPED` pointer, and classifies the
310 /// outcome as an [`Issued`]: [`Issued::Pending`] when the pool will deliver a
311 /// completion callback, or [`Issued::Completed`] when the call finished
312 /// synchronously and no callback will arrive -- the outcome a handle in
313 /// `FILE_SKIP_COMPLETION_PORT_ON_SUCCESS` mode reports on synchronous
314 /// success. It returns `Err` for an immediate failure that yields no
315 /// callback.
316 ///
317 /// On the pending path the operation's storage is transferred out and is
318 /// recovered later inside the callback with [`IoCompletion::claim`]. On the
319 /// synchronous and failure paths the operation is returned intact through
320 /// [`Submitted`] so its storage can be reused or inspected.
321 ///
322 /// # Panics
323 ///
324 /// Panics if this object already has a live operation registered at the new
325 /// operation's storage address. That cannot happen through ordinary use --
326 /// `operation` owns freshly boxed storage -- and indicates a defect in this
327 /// crate's own bookkeeping rather than in the calling code. See
328 /// `OperationRegistry::insert` in `windows-overlapped-io-sys` for the
329 /// invariant involved.
330 ///
331 /// # Safety
332 ///
333 /// `issue` must start exactly one overlapped operation using the provided
334 /// `OVERLAPPED` pointer and no other storage, and must classify the outcome
335 /// correctly: [`Issued::Pending`] only when a completion callback will be
336 /// delivered for this object, [`Issued::Completed`] only when the operation
337 /// is already complete and no callback will arrive, and `Err` only when the
338 /// submission failed and no callback will arrive. Misclassifying either
339 /// unbalances the pool's accounting or frees storage the kernel still owns.
340 ///
341 /// `issue` must not unwind. `StartThreadpoolIo` is issued before it runs and
342 /// is balanced only on the paths below; a panic out of `issue` skips that
343 /// balancing while leaving the start pending, and -- because a panic before
344 /// starting the I/O is indistinguishable from one after -- rundown could then
345 /// wait forever for a callback that will never arrive. A closure that might
346 /// panic must catch it and return `Err` instead.
347 ///
348 /// `P: 'static` because submitting leaks the operation's storage, to be
349 /// freed later through a thunk carrying no lifetime -- see
350 /// [`Operation::into_overlapped`].
351 pub unsafe fn submit<P, F>(&self, operation: Operation<P>, issue: F) -> Submitted<P>
352 where
353 P: Send + 'static,
354 F: FnOnce(BorrowedHandle<'_>, *mut OVERLAPPED) -> io::Result<Issued>,
355 {
356 // Transfer the operation's storage out; the kernel owns it until it is
357 // reclaimed. `into_overlapped` arms the type-erased reclaim thunk.
358 let overlapped = operation.into_overlapped();
359 // Stamp this submission with a fresh generation, so the identity names
360 // this operation and not whatever later operation may reuse the address.
361 let id = OperationId::mint(overlapped);
362
363 // Register before starting so a callback can never race ahead of the
364 // accounting; the registry's length is the unbalanced-start count.
365 self.live.insert(id);
366 // SAFETY: tp_io is valid for the lifetime of self. This start is balanced
367 // exactly once on every path below.
368 crate::trace_call!("StartThreadpoolIo", self.tp_io, overlapped as usize, {
369 // SAFETY: tp_io is valid for the lifetime of self. This start is balanced
370 // exactly once on every path below.
371 unsafe { StartThreadpoolIo(self.tp_io) };
372 });
373 crate::trace_record!("io", "started", self.tp_io, overlapped as usize);
374
375 match issue(self.handle(), overlapped) {
376 Ok(Issued::Pending) => Submitted::Pending(id),
377 Ok(Issued::Completed { bytes_transferred }) => {
378 // SAFETY: no callback will arrive, so the start must be balanced
379 // here or the pool would wait for a completion that never comes.
380 crate::trace_call!("CancelThreadpoolIo", self.tp_io, overlapped as usize, {
381 // SAFETY: no callback will arrive, so the start must be balanced
382 // here or the pool would wait for a completion that never comes.
383 unsafe { CancelThreadpoolIo(self.tp_io) };
384 });
385 // Paired with `started`: this operation will never reach the
386 // trampoline, so without this record its `started` would look
387 // like a dispatch that never happened.
388 crate::trace_record!("io", "start-cancelled", self.tp_io, overlapped as usize);
389 self.live.remove(overlapped);
390 // SAFETY: the operation completed synchronously and no callback
391 // will arrive, so the kernel is done with the storage; reclaim
392 // the box we just leaked, exactly once.
393 let mut operation = unsafe { Operation::<P>::from_overlapped(overlapped) };
394 operation.set_state(OperationState::Completed);
395 Submitted::Completed {
396 operation,
397 bytes_transferred,
398 }
399 }
400 Err(error) => {
401 // SAFETY: the submission failed and no callback will arrive, so
402 // the start must be balanced here.
403 crate::trace_call!("CancelThreadpoolIo", self.tp_io, overlapped as usize, {
404 // SAFETY: the submission failed and no callback will arrive, so
405 // the start must be balanced here.
406 unsafe { CancelThreadpoolIo(self.tp_io) };
407 });
408 crate::trace_record!("io", "start-cancelled", self.tp_io, overlapped as usize);
409 self.live.remove(overlapped);
410 // SAFETY: no callback will arrive, so reclaim the operation we
411 // just leaked, exactly once.
412 let mut operation = unsafe { Operation::<P>::from_overlapped(overlapped) };
413 operation.set_state(OperationState::Idle);
414 Submitted::Failed { operation, error }
415 }
416 }
417 }
418
419 /// Request cancellation of a single outstanding operation.
420 ///
421 /// Cancellation is only a request: the operation still completes, typically
422 /// with `ERROR_OPERATION_ABORTED`, and that completion callback remains the
423 /// point at which its storage is reclaimed.
424 ///
425 /// The identity is checked against this object's live operations first. An
426 /// identity whose operation has already completed is rejected with
427 /// [`io::ErrorKind::NotFound`] and no native call is made, even if another
428 /// operation has since been given the same storage address. Cancelling
429 /// therefore races safely against completion: the worst outcome of a late
430 /// cancel is this error, never the cancellation of an unrelated operation.
431 ///
432 /// # Errors
433 ///
434 /// Returns [`io::ErrorKind::NotFound`] if `id` no longer names a live
435 /// operation, or the error from `CancelIoEx` if the native request fails.
436 pub fn cancel(&self, id: OperationId) -> io::Result<()> {
437 // The liveness check and the native call happen under one registry
438 // guard; splitting them would let the address be recycled in between.
439 self.live.cancel_if_live(id, || {
440 // SAFETY: cancelling by a valid handle and an OVERLAPPED identity
441 // the registry has confirmed still names a live operation, and which
442 // cannot be reclaimed and reissued while the guard is held.
443 let ok = crate::trace_call!(
444 "CancelIoEx",
445 self.raw_handle() as usize,
446 id.as_ptr() as usize,
447 {
448 // SAFETY: the handle is owned by self and the OVERLAPPED is live.
449 unsafe { CancelIoEx(self.raw_handle(), id.as_ptr()) }
450 }
451 );
452 if ok == 0 {
453 return Err(io::Error::last_os_error());
454 }
455 Ok(())
456 })
457 }
458
459 /// Request cancellation of every outstanding operation on this endpoint.
460 ///
461 /// # Errors
462 ///
463 /// Returns the error from `CancelIoEx`, which reports `ERROR_NOT_FOUND` when
464 /// nothing was outstanding.
465 pub fn cancel_all(&self) -> io::Result<()> {
466 // SAFETY: a null OVERLAPPED cancels all operations on the handle.
467 let ok = crate::trace_call!("CancelIoEx(all)", self.raw_handle() as usize, 0, {
468 // SAFETY: the handle is owned by self; a null OVERLAPPED cancels all.
469 unsafe { CancelIoEx(self.raw_handle(), ptr::null()) }
470 });
471 if ok == 0 {
472 return Err(io::Error::last_os_error());
473 }
474 Ok(())
475 }
476
477 /// Block until every outstanding operation has completed and every
478 /// completion callback has finished running.
479 ///
480 /// Every outstanding operation must already be cancelled or otherwise
481 /// destined to complete -- which [`ThreadpoolIo::cancel_all`] guarantees --
482 /// or this waits indefinitely.
483 ///
484 /// Two things are waited for, because an operation is deregistered when its
485 /// callback is *entered* rather than when that callback returns: first that
486 /// no operation is outstanding, then that no callback is still executing.
487 /// Together they mean a caller can read whatever its callbacks recorded as
488 /// soon as this returns.
489 ///
490 /// Must not be called from inside this object's own callback, which would
491 /// wait on the callback's own completion.
492 pub fn run_down(&self) {
493 crate::trace_record!("io", "rundown-begin", self.tp_io, self.outstanding());
494 self.live.wait_until_empty();
495 // Deregistration happens at callback entry, so an empty registry does
496 // not by itself mean the callbacks have finished.
497 self.wait();
498 crate::trace_record!("io", "rundown-ended", self.tp_io);
499 }
500
501 /// Block until no I/O callback for this object is executing.
502 ///
503 /// This waits for callbacks that have already started; it does not cancel
504 /// pending ones. There is deliberately no cancelling variant: cancelling a
505 /// pending I/O callback would neither cancel the underlying operation nor
506 /// make its `OVERLAPPED` storage safe to free, so the only sound way to stop
507 /// outstanding I/O is [`ThreadpoolIo::cancel_all`] followed by
508 /// [`ThreadpoolIo::run_down`].
509 pub fn wait(&self) {
510 // SAFETY: tp_io is valid for the lifetime of self; FALSE never cancels
511 // pending callbacks, so no operation's storage is orphaned.
512 crate::trace_call!("WaitForThreadpoolIoCallbacks", self.tp_io, 0, {
513 // SAFETY: tp_io is valid for the lifetime of self; FALSE never cancels
514 // pending callbacks, so no operation storage is orphaned.
515 unsafe { WaitForThreadpoolIoCallbacks(self.tp_io, FALSE) };
516 });
517 }
518
519 fn raw_handle(&self) -> HANDLE {
520 self.handle.as_raw_handle()
521 }
522}
523
524impl fmt::Debug for ThreadpoolIo {
525 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526 f.debug_struct("ThreadpoolIo")
527 .field("outstanding", &self.outstanding())
528 .finish_non_exhaustive()
529 }
530}
531
532impl Drop for ThreadpoolIo {
533 fn drop(&mut self) {
534 let count = self.outstanding();
535 crate::trace_record!("io", "drop-begin", self.tp_io, count);
536 if count > 0 {
537 // A blocking Drop signals that rundown was skipped. Report it from
538 // this single site, then make the block terminate: because this
539 // object owns the handle, cancelling guarantees every outstanding
540 // operation delivers its callback.
541 //
542 // The report is a trace event rather than the `eprintln!` this
543 // shipped with, per [A developer-facing report is a trace
544 // event](../../../DESIGN-NOTES.md#reports-are-trace-events). The
545 // outstanding count rides in the second numeric slot, so the only
546 // thing the conversion cost is the English. This type needs no
547 // `CloseObligation`: `outstanding()` answers the same question from
548 // live state, which is why the other four types carry a flag and
549 // this one does not.
550 crate::trace_record!(
551 "io",
552 crate::obligation::DROP_OBLIGATION_OWED,
553 self.tp_io,
554 count
555 );
556 let _ = self.cancel_all();
557 self.live.wait_until_empty();
558 }
559
560 // The count reaches zero when the last callback is *entered*, not when
561 // it returns, so a callback frame may still be running here. Both calls
562 // below must happen before the context is freed and before the handle
563 // closes.
564 //
565 // SAFETY: tp_io is valid and no operation is outstanding, so waiting
566 // without cancelling cannot orphan any storage, and closing the object
567 // is legal once its callbacks have finished.
568 crate::trace_call!("WaitForThreadpoolIoCallbacks", self.tp_io, 0, {
569 // SAFETY: tp_io is valid and nothing is outstanding, so waiting without
570 // cancelling cannot orphan any storage.
571 unsafe { WaitForThreadpoolIoCallbacks(self.tp_io, FALSE) };
572 });
573 crate::trace_call!("CloseThreadpoolIo", self.tp_io, 0, {
574 // SAFETY: closing the object is legal once its callbacks have finished.
575 unsafe { CloseThreadpoolIo(self.tp_io) };
576 });
577 crate::trace_record!("io", "drop-drained", self.tp_io);
578
579 // SAFETY: the TP_IO object is closed and every callback has finished, so
580 // nothing can reach the context again; free it exactly once. `handle`
581 // closes after this, when its field is dropped.
582 unsafe { drop(Box::from_raw(self.context)) };
583 // The last record this object emits, and it carries the handle because
584 // nothing after it can: the handle's close is the field drop that runs
585 // the instant this body returns, with no code of ours in between.
586 crate::trace_record!("io", "drop-closed", self.tp_io, self.raw_handle() as usize);
587 // Last, after the rundown, the close and the context free: a panic
588 // unwinds, so anything after it would be skipped; the endpoint handle
589 // still closes, because field drops run even when `Drop::drop` unwinds.
590 //
591 // `count` was read at the top, before the cancel and the wait emptied
592 // the registry -- reading it here would find zero on exactly the objects
593 // that owed a rundown.
594 crate::obligation::fail_fast_if_owed(count > 0, "ThreadpoolIo", "run_down");
595 }
596}
597
598/// One operation completion delivered to a [`ThreadpoolIo`] callback.
599///
600/// The completion borrows the operation's storage for the duration of the
601/// callback. Recover the owned operation with [`IoCompletion::claim`] when the
602/// payload type is known; otherwise the storage is reclaimed generically when
603/// the callback returns, which is what lets one object carry operations of mixed
604/// payload types.
605pub struct IoCompletion {
606 overlapped: *mut OVERLAPPED,
607 /// The identity of the completing operation, read whole from the registry
608 /// while it was still registered. `None` only if the entry was already gone,
609 /// which a correctly-operating backend does not produce.
610 id: Option<OperationId>,
611 io_result: u32,
612 bytes_transferred: usize,
613 claimed: Cell<bool>,
614}
615
616impl fmt::Debug for IoCompletion {
617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618 f.debug_struct("IoCompletion")
619 .field("overlapped", &self.overlapped)
620 .field("id", &self.id)
621 .field("io_result", &self.io_result)
622 .field("bytes_transferred", &self.bytes_transferred)
623 .finish_non_exhaustive()
624 }
625}
626
627impl IoCompletion {
628 /// The number of bytes transferred by the operation.
629 #[must_use]
630 pub fn bytes_transferred(&self) -> usize {
631 self.bytes_transferred
632 }
633
634 /// The raw Win32 result the pool reported, `NO_ERROR` on success.
635 #[must_use]
636 pub fn io_result(&self) -> u32 {
637 self.io_result
638 }
639
640 /// The failure of the completed operation, if it did not succeed.
641 ///
642 /// A cancelled operation completes here as `ERROR_OPERATION_ABORTED`.
643 #[must_use]
644 pub fn error(&self) -> Option<io::Error> {
645 if self.io_result == NO_ERROR {
646 return None;
647 }
648 Some(io::Error::from_raw_os_error(self.io_result as i32))
649 }
650
651 /// The identity of the completed operation, as returned by
652 /// [`ThreadpoolIo::submit`].
653 ///
654 /// It compares equal to the [`OperationId`] that submission returned, so a
655 /// caller holding submission-time identities can match a completion against
656 /// them directly.
657 #[must_use]
658 pub fn id(&self) -> Option<OperationId> {
659 self.id
660 }
661
662 /// The `OVERLAPPED` pointer identifying the completed operation.
663 #[must_use]
664 pub fn overlapped_ptr(&self) -> *mut OVERLAPPED {
665 self.overlapped
666 }
667
668 /// Recover the owned operation whose completion this is.
669 ///
670 /// The operation is returned in [`OperationState::Completed`] whether or not
671 /// it succeeded, matching the raw IOCP backend; read [`IoCompletion::error`]
672 /// for the outcome.
673 ///
674 /// # Safety
675 ///
676 /// This completion must be for an `Operation<P>` of this exact type
677 /// submitted through [`ThreadpoolIo::submit`], and it must be claimed at
678 /// most once.
679 pub unsafe fn claim<P>(&self) -> Operation<P> {
680 // Mark claimed so this completion's own drop will not also reclaim it.
681 self.claimed.set(true);
682 // SAFETY: by this function's contract, the identity is a matching leaked
683 // Operation<P>, reclaimed exactly once here.
684 let mut operation = unsafe { Operation::<P>::from_overlapped(self.overlapped) };
685 operation.set_state(OperationState::Completed);
686 operation
687 }
688}
689
690impl Drop for IoCompletion {
691 fn drop(&mut self) {
692 // A claimed completion handed ownership to the callback.
693 if self.claimed.get() || self.overlapped.is_null() {
694 return;
695 }
696 // SAFETY: the callback arrived, so the kernel and pool are done with the
697 // storage; the operation's armed reclaim thunk frees the box exactly once.
698 unsafe { reclaim_overlapped(self.overlapped) };
699 }
700}
701
702#[cfg(test)]
703mod tests;