7 .. contents:: Table of Contents
11 Remote Procedure Call Implementation
12 ====================================
14 Traditionally, the C library abstracts over several functions that interface
15 with the platform's operating system through system calls. The GPU however does
16 not provide an operating system that can handle target dependent operations.
17 Instead, we implemented remote procedure calls to interface with the host's
18 operating system while executing on a GPU.
20 We implemented remote procedure calls using unified virtual memory to create a
21 shared communicate channel between the two processes. This memory is often
22 pinned memory that can be accessed asynchronously and atomically by multiple
23 processes simultaneously. This supports means that we can simply provide mutual
24 exclusion on a shared better to swap work back and forth between the host system
25 and the GPU. We can then use this to create a simple client-server protocol
26 using this shared memory.
28 This work treats the GPU as a client and the host as a server. The client
29 initiates a communication while the server listens for them. In order to
30 communicate between the host and the device, we simply maintain a buffer of
31 memory and two mailboxes. One mailbox is write-only while the other is
32 read-only. This exposes three primitive operations: using the buffer, giving
33 away ownership, and waiting for ownership. This is implemented as a half-duplex
34 transmission channel between the two sides. We decided to assign ownership of
35 the buffer to the client when the inbox and outbox bits are equal and to the
36 server when they are not.
38 In order to make this transmission channel thread-safe, we abstract ownership of
39 the given mailbox pair and buffer around a port, effectively acting as a lock
40 and an index into the allocated buffer slice. The server and device have
41 independent locks around the given port. In this scheme, the buffer can be used
42 to communicate intent and data generically with the server. We them simply
43 provide multiple copies of this protocol and expose them as multiple ports.
45 If this were simply a standard CPU system, this would be sufficient. However,
46 GPUs have my unique architectural challenges. First, GPU threads execute in
47 lock-step with each other in groups typically called warps or wavefronts. We
48 need to target the smallest unit of independent parallelism, so the RPC
49 interface needs to handle an entire group of threads at once. This is done by
50 increasing the size of the buffer and adding a thread mask argument so the
51 server knows which threads are active when it handles the communication. Second,
52 GPUs generally have no forward progress guarantees. In order to guarantee we do
53 not encounter deadlocks while executing it is required that the number of ports
54 matches the maximum amount of hardware parallelism on the device. It is also
55 very important that the thread mask remains consistent while interfacing with
58 .. image:: ./rpc-diagram.svg
62 The above diagram outlines the architecture of the RPC interface. For clarity
63 the following list will explain the operations done by the client and server
64 respectively when initiating a communication.
66 First, a communication from the perspective of the client:
68 * The client searches for an available port and claims the lock.
69 * The client checks that the port is still available to the current device and
71 * The client writes its data to the fixed-size packet and toggles its outbox.
72 * The client waits until its inbox matches its outbox.
73 * The client reads the data from the fixed-size packet.
74 * The client closes the port and continues executing.
76 Now, the same communication from the perspective of the server:
78 * The server searches for an available port with pending work and claims the
80 * The server checks that the port is still available to the current device.
81 * The server reads the opcode to perform the expected operation, in this
82 case a receive and then send.
83 * The server reads the data from the fixed-size packet.
84 * The server writes its data to the fixed-size packet and toggles its outbox.
85 * The server closes the port and continues searching for ports that need to be
88 This architecture currently requires that the host periodically checks the RPC
89 server's buffer for ports with pending work. Note that a port can be closed
90 without waiting for its submitted work to be completed. This allows us to model
91 asynchronous operations that do not need to wait until the server has completed
92 them. If an operation requires more data than the fixed size buffer, we simply
93 send multiple packets back and forth in a streaming fashion.
98 The Client API is not currently exported by the LLVM C library. This is
99 primarily due to being written in C++ and relying on internal data structures.
100 It uses a simple send and receive interface with a fixed-size packet. The
101 following example uses the RPC interface to call a function pointer on the
104 This code first opens a port with the given opcode to facilitate the
105 communication. It then copies over the argument struct to the server using the
106 ``send_n`` interface to stream arbitrary bytes. The next send operation provides
107 the server with the function pointer that will be executed. The final receive
108 operation is a no-op and simply forces the client to wait until the server is
109 done. It can be omitted if asynchronous execution is desired.
113 void rpc_host_call(void *fn, void *data, size_t size) {
114 rpc::Client::Port port = rpc::client.open<RPC_HOST_CALL>();
115 port.send_n(data, size);
116 port.send([=](rpc::Buffer *buffer) {
117 buffer->data[0] = reinterpret_cast<uintptr_t>(fn);
119 port.recv([](rpc::Buffer *) {});
126 This example shows the server-side handling of the previous client example. When
127 the server is checked, if there are any ports with pending work it will check
128 the opcode and perform the appropriate action. In this case, the action is to
129 call a function pointer provided by the client.
131 In this example, the server simply runs forever in a separate thread for
132 brevity's sake. Because the client is a GPU potentially handling several threads
133 at once, the server needs to loop over all the active threads on the GPU. We
134 abstract this into the ``lane_size`` variable, which is simply the device's warp
135 or wavefront size. The identifier is simply the threads index into the current
136 warp or wavefront. We allocate memory to copy the struct data into, and then
137 call the given function pointer with that copied data. The final send simply
138 signals completion and uses the implicit thread mask to delete the temporary
144 auto port = server.try_open(index);
148 switch(port->get_opcode()) {
149 case RPC_HOST_CALL: {
150 uint64_t sizes[LANE_SIZE];
151 void *args[LANE_SIZE];
152 port->recv_n(args, sizes, [&](uint64_t size) { return new char[size]; });
153 port->recv([&](rpc::Buffer *buffer, uint32_t id) {
154 reinterpret_cast<void (*)(void *)>(buffer->data[0])(args[id]);
156 port->send([&](rpc::Buffer *, uint32_t id) {
157 delete[] reinterpret_cast<uint8_t *>(args[id]);
162 port->recv([](rpc::Buffer *) {});
170 The following code shows an example of using the exported RPC interface along
171 with the C library to manually configure a working server using the CUDA
172 language. Other runtimes can use the presence of the ``__llvm_rpc_client``
173 in the GPU executable as an indicator for whether or not the server can be
174 checked. These details should ideally be handled by the GPU language runtime,
175 but the following example shows how it can be used by a standard user.
177 .. _libc_gpu_cuda_server:
183 #include <cuda_runtime.h>
185 #include <shared/rpc.h>
186 #include <shared/rpc_opcodes.h>
188 [[noreturn]] void handle_error(cudaError_t err) {
189 fprintf(stderr, "CUDA error: %s\n", cudaGetErrorString(err));
193 // Routes the library symbol into the CUDA runtime interface.
194 [[gnu::weak]] __device__ rpc::Client client asm("__llvm_rpc_client");
196 // The device-side overload of the standard C function to call.
197 extern "C" __device__ int puts(const char *);
199 // Calls the C library function from the GPU C library.
200 __global__ void hello() { puts("Hello world!"); }
203 void *rpc_client = nullptr;
204 if (cudaError_t err = cudaGetSymbolAddress(&rpc_client, client))
207 // Initialize the RPC client and server interface.
208 uint32_t warp_size = 32;
209 void *rpc_buffer = nullptr;
210 if (cudaError_t err = cudaMallocHost(
212 rpc::Server::allocation_size(warp_size, rpc::MAX_PORT_COUNT)))
214 rpc::Server server(rpc::MAX_PORT_COUNT, rpc_buffer);
215 rpc::Client client(rpc::MAX_PORT_COUNT, rpc_buffer);
217 // Initialize the client on the device so it can communicate with the server.
218 if (cudaError_t err = cudaMemcpy(rpc_client, &client, sizeof(rpc::Client),
219 cudaMemcpyHostToDevice))
223 if (cudaError_t err = cudaStreamCreate(&stream))
226 // Execute the kernel.
227 hello<<<1, 1, 0, stream>>>();
229 // While the kernel is executing, check the RPC server for work to do.
230 // Requires non-blocking CUDA kernels but avoids a separate thread.
232 auto port = server.try_open(warp_size, /*index=*/0);
233 // From libllvmlibc_rpc_server.a in the installation.
235 handle_libc_opcodes(*port, warp_size);
236 } while (cudaStreamQuery(stream) == cudaErrorNotReady);
239 The above code must be compiled in CUDA's relocatable device code mode and with
240 the advanced offloading driver to link in the library. Currently this can be
241 done with the following invocation. Using LTO avoids the overhead normally
242 associated with relocatable device code linking. The C library for GPUs is
243 linked in by forwarding the static library to the device-side link job.
247 $> clang++ -x cuda rpc.cpp --offload-arch=native -fgpu-rdc -lcudart \
248 -I<install-path>include -L<install-path>/lib -lllvmlibc_rpc_server \
249 -Xoffload-linker -lc -O3 -foffload-lto -o hello
256 The opcode is a 32-bit integer that must be unique to the requested operation.
257 All opcodes used by ``libc`` internally have the character ``c`` in the most
258 significant byte. Any other opcode is available for use outside of the ``libc``