|
| 1 | +// |
| 2 | +// Java Does USB |
| 3 | +// Copyright (c) 2023 Manuel Bleichenbacher |
| 4 | +// Licensed under MIT License |
| 5 | +// https://opensource.org/licenses/MIT |
| 6 | +// |
| 7 | + |
| 8 | +package net.codecrete.usb.windows; |
| 9 | + |
| 10 | +import net.codecrete.usb.windows.gen.kernel32.Kernel32; |
| 11 | +import net.codecrete.usb.windows.gen.kernel32.OVERLAPPED; |
| 12 | +import net.codecrete.usb.windows.winsdk.Kernel32B; |
| 13 | + |
| 14 | +import java.lang.foreign.Arena; |
| 15 | +import java.lang.foreign.MemorySegment; |
| 16 | +import java.util.ArrayList; |
| 17 | +import java.util.HashMap; |
| 18 | +import java.util.List; |
| 19 | +import java.util.Map; |
| 20 | + |
| 21 | +import static java.lang.foreign.MemorySegment.NULL; |
| 22 | +import static java.lang.foreign.ValueLayout.*; |
| 23 | +import static net.codecrete.usb.windows.WindowsUSBException.throwLastError; |
| 24 | + |
| 25 | +/** |
| 26 | + * Background task for handling asynchronous transfers. |
| 27 | + * <p> |
| 28 | + * Each USB device must register its handle with this task. |
| 29 | + * </p> |
| 30 | + * <p> |
| 31 | + * The task keeps track of the submitted transfers by indexing them |
| 32 | + * by OVERLAPPED struct address. |
| 33 | + * </p> |
| 34 | + * <p> |
| 35 | + * OVERLAPPED structs are allocated but never freed. To limit the memory usage, |
| 36 | + * OVERLAPPED structs are reused. So the maximum number of outstanding transfers |
| 37 | + * determines the number of allocated OVERLAPPED structs. |
| 38 | + * </p> |
| 39 | + */ |
| 40 | +public class WindowsAsyncTask { |
| 41 | + |
| 42 | + private static WindowsAsyncTask singletonInstance; |
| 43 | + |
| 44 | + /** |
| 45 | + * Singleton instance of background task. |
| 46 | + * |
| 47 | + * @return background task |
| 48 | + */ |
| 49 | + static synchronized WindowsAsyncTask instance() { |
| 50 | + if (singletonInstance == null) |
| 51 | + singletonInstance = new WindowsAsyncTask(); |
| 52 | + return singletonInstance; |
| 53 | + } |
| 54 | + |
| 55 | + // Currently outstanding transfer requests, |
| 56 | + // indexed by OVERLAPPED address. |
| 57 | + private Map<Long, WindowsTransfer> requestsByOverlapped; |
| 58 | + // available OVERLAPPED data structures |
| 59 | + private List<MemorySegment> availableOverlappedStructs; |
| 60 | + // Arena used to allocate OVERLAPPED data structures |
| 61 | + private Arena arena; |
| 62 | + |
| 63 | + /** |
| 64 | + * Windows completion port for asynchronous/overlapped IO |
| 65 | + */ |
| 66 | + private MemorySegment asyncIoCompletionPort = NULL; |
| 67 | + |
| 68 | + /** |
| 69 | + * Background task for handling asynchronous IO completions. |
| 70 | + */ |
| 71 | + private void asyncCompletionTask() { |
| 72 | + |
| 73 | + try (var arena = Arena.openConfined()) { |
| 74 | + |
| 75 | + var overlappedHolder = arena.allocate(ADDRESS, NULL); |
| 76 | + var numBytesHolder = arena.allocate(JAVA_INT, 0); |
| 77 | + var completionKeyHolder = arena.allocate(JAVA_LONG, 0); |
| 78 | + var lastErrorState = arena.allocate(Win.LAST_ERROR_STATE.layout()); |
| 79 | + |
| 80 | + while (true) { |
| 81 | + overlappedHolder.set(ADDRESS, 0, MemorySegment.NULL); |
| 82 | + completionKeyHolder.set(JAVA_LONG, 0, 0); |
| 83 | + |
| 84 | + int res = Kernel32B.GetQueuedCompletionStatus(asyncIoCompletionPort, numBytesHolder, |
| 85 | + completionKeyHolder, overlappedHolder, Kernel32.INFINITE(), lastErrorState); |
| 86 | + var overlappedAddr = overlappedHolder.get(JAVA_LONG, 0); |
| 87 | + |
| 88 | + if (res == 0 && overlappedAddr == 0) |
| 89 | + throwLastError(lastErrorState, "Internal error (SetupDiGetDeviceInterfaceDetailW)"); |
| 90 | + |
| 91 | + if (overlappedAddr == 0) |
| 92 | + return; // registry closing? |
| 93 | + |
| 94 | + completeTransfer(overlappedAddr); |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * Add a Windows handle (of a USB device) to the completion port. |
| 101 | + * <p> |
| 102 | + * The handle is removed by closing it. |
| 103 | + * </p> |
| 104 | + * |
| 105 | + * @param handle Windows handle |
| 106 | + */ |
| 107 | + synchronized void addDevice(MemorySegment handle) { |
| 108 | + |
| 109 | + try (var arena = Arena.openConfined()) { |
| 110 | + var lastErrorState = arena.allocate(Win.LAST_ERROR_STATE.layout()); |
| 111 | + |
| 112 | + // Creates a new port if it doesn't exist; adds handle to existing port if it exists |
| 113 | + MemorySegment portHandle = Kernel32B.CreateIoCompletionPort(handle, asyncIoCompletionPort, |
| 114 | + handle.address(), 0, lastErrorState); |
| 115 | + if (portHandle == MemorySegment.NULL) |
| 116 | + throwLastError(lastErrorState, "internal error (CreateIoCompletionPort)"); |
| 117 | + |
| 118 | + if (asyncIoCompletionPort == MemorySegment.NULL) { |
| 119 | + asyncIoCompletionPort = portHandle; |
| 120 | + startAsyncIOTask(); |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + private void startAsyncIOTask() { |
| 126 | + availableOverlappedStructs = new ArrayList<>(); |
| 127 | + arena = Arena.openShared(); |
| 128 | + requestsByOverlapped = new HashMap<>(); |
| 129 | + |
| 130 | + // start background thread for handling IO completion |
| 131 | + Thread t = new Thread(this::asyncCompletionTask, "USB async IO"); |
| 132 | + t.setDaemon(true); |
| 133 | + t.start(); |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Prepare a transfer for submission by adding the OVERLAPPED struct. |
| 138 | + * |
| 139 | + * @param transfer transfer to prepare |
| 140 | + */ |
| 141 | + synchronized void prepareForSubmission(WindowsTransfer transfer) { |
| 142 | + MemorySegment overlapped; |
| 143 | + int size = availableOverlappedStructs.size(); |
| 144 | + if (size == 0) { |
| 145 | + overlapped = arena.allocate(OVERLAPPED.$LAYOUT()); |
| 146 | + } else { |
| 147 | + overlapped = availableOverlappedStructs.remove(size - 1); |
| 148 | + } |
| 149 | + |
| 150 | + transfer.overlapped = overlapped; |
| 151 | + transfer.resultSize = -1; |
| 152 | + requestsByOverlapped.put(overlapped.address(), transfer); |
| 153 | + } |
| 154 | + |
| 155 | + /** |
| 156 | + * Completes the transfer by calling the completion handler. |
| 157 | + * |
| 158 | + * @param overlappedAddr address of OVERLAPPED struct |
| 159 | + */ |
| 160 | + private synchronized void completeTransfer(long overlappedAddr) { |
| 161 | + var transfer = requestsByOverlapped.remove(overlappedAddr); |
| 162 | + if (transfer == null) |
| 163 | + return; |
| 164 | + |
| 165 | + transfer.resultCode = (int) OVERLAPPED.Internal$get(transfer.overlapped); |
| 166 | + transfer.resultSize = (int) OVERLAPPED.InternalHigh$get(transfer.overlapped); |
| 167 | + |
| 168 | + availableOverlappedStructs.add(transfer.overlapped); |
| 169 | + transfer.overlapped = null; |
| 170 | + transfer.completion.completed(transfer); |
| 171 | + } |
| 172 | +} |
0 commit comments