interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-rpc / transport.cpp

814 lines · 25731 bytes Raw Blame History
1#include "transport.h"
2#include "log.h"
3
4#ifdef _WIN32
5# define WIN32_LEAN_AND_MEAN
6# ifndef NOMINMAX
7# define NOMINMAX
8# endif
9# include <windows.h>
10# include <winsock2.h>
11#else
12# include <arpa/inet.h>
13# include <sys/socket.h>
14# include <sys/types.h>
15# include <netinet/in.h>
16# include <netinet/tcp.h>
17# include <netdb.h>
18# include <unistd.h>
19#endif
20#include <cstdlib>
21#include <cstring>
22#include <mutex>
23#include <optional>
24
25#ifdef GGML_RPC_RDMA
26# include <infiniband/verbs.h>
27# include <array>
28# include <cerrno>
29# include <chrono>
30# include <time.h>
31# ifndef _WIN32
32# include <poll.h>
33# endif
34# ifdef GGML_RPC_RDMA_APPLE
35# include "transport-apple.h"
36# endif
37#endif // GGML_RPC_RDMA
38
39#ifdef _WIN32
40typedef SOCKET sockfd_t;
41using ssize_t = __int64;
42#else
43typedef int sockfd_t;
44#endif
45
46#ifdef GGML_RPC_RDMA
47static constexpr size_t RDMA_GID_SIZE = 16; // RoCE GID / IB GID is always 16 bytes
48using rdma_gid_t = std::array<uint8_t, RDMA_GID_SIZE>;
49#endif // GGML_RPC_RDMA
50
51#if defined(GGML_RPC_RDMA) && !defined(GGML_RPC_RDMA_APPLE)
52static constexpr size_t RDMA_CHUNK = 256 * 1024; // 256 KiB per send/recv (fits default 8 MiB memlock)
53static constexpr int RDMA_RX_DEPTH = 24; // pre-posted recv ring: 24 × 256 KiB = 6 MiB
54// keep polling the CQ for this long after the last activity, then sleep until the next completion
55static constexpr auto RDMA_SPIN_TIME = std::chrono::milliseconds(100);
56
57struct rdma_conn {
58 struct ibv_context * ctx = nullptr;
59 struct ibv_pd * pd = nullptr;
60 struct ibv_cq * scq = nullptr; // send completions
61 struct ibv_cq * rcq = nullptr; // recv completions
62 struct ibv_qp * qp = nullptr;
63 struct ibv_comp_channel * ch = nullptr; // CQ events, so an idle connection can sleep instead of spinning
64
65 std::chrono::steady_clock::time_point last_active; // last completion or posted send
66
67 void * tx_buf = nullptr;
68 struct ibv_mr * tx_mr = nullptr;
69
70 void * rx_buf = nullptr; // RDMA_RX_DEPTH × RDMA_CHUNK contiguous
71 struct ibv_mr * rx_mr = nullptr;
72 int rx_head = 0;
73
74 uint32_t max_inline = 0;
75
76 uint8_t * rx_slot(int i) const {
77 return static_cast<uint8_t *>(rx_buf) + static_cast<size_t>(i) * RDMA_CHUNK;
78 }
79
80 bool post_rx(int i) {
81 struct ibv_sge sge = {};
82 sge.addr = (uintptr_t)rx_slot(i);
83 sge.length = RDMA_CHUNK;
84 sge.lkey = rx_mr->lkey;
85 struct ibv_recv_wr wr = {}, * bad = nullptr;
86 wr.wr_id = (uint64_t)i;
87 wr.sg_list = &sge;
88 wr.num_sge = 1;
89 return ibv_post_recv(qp, &wr, &bad) == 0;
90 }
91
92 ~rdma_conn() {
93 if (tx_mr) ibv_dereg_mr(tx_mr);
94 if (rx_mr) ibv_dereg_mr(rx_mr);
95 free(tx_buf);
96 free(rx_buf);
97 if (qp) ibv_destroy_qp(qp);
98 if (scq) ibv_destroy_cq(scq);
99 if (rcq) ibv_destroy_cq(rcq);
100 if (ch) ibv_destroy_comp_channel(ch);
101 if (pd) ibv_dealloc_pd(pd);
102 if (ctx) ibv_close_device(ctx);
103 }
104};
105
106// Local RDMA parameters captured during the probe phase and later consumed
107// by rdma_activate() after the remote side's caps arrive via HELLO.
108struct rdma_local_info {
109 uint32_t qpn = 0;
110 uint32_t psn = 0;
111 uint8_t gid[RDMA_GID_SIZE] = {};
112 uint8_t ib_port = 0;
113 int gid_idx = 0;
114 enum ibv_mtu path_mtu = IBV_MTU_1024;
115};
116
117struct rdma_caps {
118 uint32_t qpn;
119 uint32_t psn;
120 uint8_t gid[RDMA_GID_SIZE];
121};
122
123static_assert(sizeof(rdma_caps) == RPC_CONN_CAPS_SIZE, "rdma_caps must match conn_caps size");
124
125#endif // GGML_RPC_RDMA && !GGML_RPC_RDMA_APPLE
126
127struct socket_t::impl {
128 impl(sockfd_t fd) : use_rdma(false), fd(fd) {}
129 ~impl();
130 bool send_data(const void * data, size_t size);
131 bool recv_data(void * data, size_t size);
132 bool flush();
133 void get_caps(uint8_t * local_caps);
134 void update_caps(const uint8_t * remote_caps);
135
136#ifdef GGML_RPC_RDMA
137 std::optional<rdma_gid_t> rdma_build_target_gid();
138
139# ifdef GGML_RPC_RDMA_APPLE
140 std::unique_ptr<apple_rdma> rdma;
141# else
142 bool rdma_probe();
143 bool rdma_send(const void * data, size_t size);
144 bool rdma_recv(void * data, size_t size);
145 bool tcp_peer_closed();
146 bool rdma_activate(uint32_t remote_qpn, uint32_t remote_psn, const uint8_t * remote_gid);
147 bool rdma_poll(struct ibv_cq * cq, struct ibv_wc * wc);
148 bool rdma_wait_event();
149
150 std::unique_ptr<rdma_conn> rdma;
151 rdma_local_info rdma_local = {};
152# endif
153#endif // GGML_RPC_RDMA
154 bool use_rdma;
155 sockfd_t fd;
156};
157
158socket_t::impl::~impl() {
159#ifdef GGML_RPC_RDMA
160 rdma.reset();
161#endif // GGML_RPC_RDMA
162 LOG_DBG("[%s] closing socket %d\n", __func__, this->fd);
163#ifdef _WIN32
164 if (fd != INVALID_SOCKET) closesocket(this->fd);
165#else
166 if (fd >= 0) close(this->fd);
167#endif
168}
169
170#ifdef GGML_RPC_RDMA
171
172// Build a RoCE GID-shaped 16-byte target from a TCP socket's local address.
173// Used to match the socket's local IP against the kernel's GID table so that
174// a single memcmp handles IPv4, IPv4-mapped IPv6, and native IPv6 uniformly:
175// AF_INET -> ::ffff:a.b.c.d (bytes 10-11 = 0xff, last 4 = IPv4)
176// AF_INET6 (IPv4-mapped) -> ::ffff:a.b.c.d (already in GID shape)
177// AF_INET6 (native v6) -> the 16-byte IPv6 address as-is
178// Returns std::nullopt on unsupported family or getsockname failure.
179std::optional<rdma_gid_t> socket_t::impl::rdma_build_target_gid() {
180 sockaddr_storage addr = {};
181 socklen_t addr_len = sizeof(addr);
182 if (getsockname(fd, reinterpret_cast<sockaddr *>(&addr), &addr_len) != 0) {
183 return std::nullopt;
184 }
185 rdma_gid_t target = {};
186 if (addr.ss_family == AF_INET) {
187 const auto * a = reinterpret_cast<const sockaddr_in *>(&addr);
188 target[10] = 0xff;
189 target[11] = 0xff;
190 memcpy(&target[12], &a->sin_addr, 4);
191 return target;
192 }
193 if (addr.ss_family == AF_INET6) {
194 const auto * a = reinterpret_cast<const sockaddr_in6 *>(&addr);
195 memcpy(target.data(), &a->sin6_addr, RDMA_GID_SIZE);
196 return target;
197 }
198 return std::nullopt;
199}
200
201#ifndef GGML_RPC_RDMA_APPLE
202
203bool socket_t::impl::tcp_peer_closed() {
204 if (fd < 0) return false;
205#ifndef _WIN32
206 struct pollfd pfd = { fd, POLLIN | POLLRDHUP, 0 };
207 int r = poll(&pfd, 1, 0);
208 return r > 0 && (pfd.revents & (POLLHUP | POLLERR | POLLRDHUP));
209#else
210 return false;
211#endif
212}
213
214bool socket_t::impl::rdma_probe() {
215 const char * dev_env = std::getenv("GGML_RDMA_DEV");
216 const char * gid_env = std::getenv("GGML_RDMA_GID");
217
218 auto target_gid = rdma_build_target_gid();
219 if (!target_gid) {
220 return false;
221 }
222
223 const uint8_t ib_port = 1;
224 int num_devs = 0;
225 ibv_device ** devs = ibv_get_device_list(&num_devs);
226 if (!devs || num_devs == 0) return false;
227
228 ibv_context * ibctx = nullptr;
229 const char * matched_dev = nullptr;
230 int gid_idx = gid_env ? atoi(gid_env) : -1;
231 int gid_version = IBV_GID_TYPE_IB; // 0 = unknown/IB
232
233 for (int d = 0; d < num_devs; d++) {
234 const char * dn = ibv_get_device_name(devs[d]);
235 if (dev_env && strcmp(dev_env, dn) != 0) continue;
236
237 ibv_context * ctx = ibv_open_device(devs[d]);
238 if (!ctx) continue;
239
240 ibv_port_attr pa;
241 if (ibv_query_port(ctx, ib_port, &pa) != 0) { ibv_close_device(ctx); continue; }
242
243 int found_gid = gid_idx;
244 int found_version = IBV_GID_TYPE_IB;
245 if (found_gid < 0) {
246 // Find a GID on this port whose bytes equal the local TCP address
247 // (IPv4 or IPv6). Prefer RoCE v2 (UDP/IP, L3-routable) over v1
248 // (raw Ethernet, same-L2 only) so silent hangs on L3-routed paths
249 // are avoided. ibv_query_gid_ex returns gid+type in one call.
250 int v2_idx = -1;
251 int v1_idx = -1;
252 for (int i = 0; i < pa.gid_tbl_len; i++) {
253 ibv_gid_entry entry = {};
254 if (ibv_query_gid_ex(ctx, ib_port, i, &entry, 0) != 0) continue;
255 if (memcmp(entry.gid.raw, target_gid->data(), RDMA_GID_SIZE) != 0) continue;
256 if (entry.gid_type == IBV_GID_TYPE_ROCE_V2 && v2_idx < 0) {
257 v2_idx = i;
258 } else if (entry.gid_type == IBV_GID_TYPE_ROCE_V1 && v1_idx < 0) {
259 v1_idx = i;
260 }
261 }
262 if (v2_idx >= 0) {
263 found_gid = v2_idx;
264 found_version = IBV_GID_TYPE_ROCE_V2;
265 } else if (v1_idx >= 0) {
266 found_gid = v1_idx;
267 found_version = IBV_GID_TYPE_ROCE_V1;
268 }
269 } else {
270 // Explicit GID index from GGML_RDMA_GID — fetch its type for logging.
271 ibv_gid_entry entry = {};
272 if (ibv_query_gid_ex(ctx, ib_port, found_gid, &entry, 0) == 0) {
273 found_version = entry.gid_type;
274 }
275 }
276 if (found_gid >= 0) {
277 ibctx = ctx;
278 gid_idx = found_gid;
279 gid_version = found_version;
280 matched_dev = dn;
281 rdma_local.path_mtu = pa.active_mtu;
282 break;
283 }
284 ibv_close_device(ctx);
285 }
286 ibv_free_device_list(devs);
287 if (!ibctx) return false;
288
289 rdma_local.ib_port = ib_port;
290 rdma_local.gid_idx = gid_idx;
291
292 rdma = std::make_unique<rdma_conn>();
293 rdma->ctx = ibctx;
294
295 rdma->pd = ibv_alloc_pd(ibctx);
296 if (!rdma->pd) return false;
297
298 // without a completion channel rdma_poll() spins all the time, as before
299 rdma->ch = ibv_create_comp_channel(ibctx);
300 rdma->scq = ibv_create_cq(ibctx, 16, nullptr, rdma->ch, 0);
301 rdma->rcq = ibv_create_cq(ibctx, RDMA_RX_DEPTH + 4, nullptr, rdma->ch, 0);
302 if (!rdma->scq || !rdma->rcq) return false;
303
304 ibv_qp_init_attr qia = {};
305 qia.send_cq = rdma->scq;
306 qia.recv_cq = rdma->rcq;
307 qia.qp_type = IBV_QPT_RC;
308 qia.cap.max_send_wr = 4;
309 qia.cap.max_recv_wr = RDMA_RX_DEPTH + 4;
310 qia.cap.max_send_sge = 1;
311 qia.cap.max_recv_sge = 1;
312 qia.cap.max_inline_data = 256;
313
314 rdma->qp = ibv_create_qp(rdma->pd, &qia);
315 if (!rdma->qp) return false;
316 rdma->max_inline = qia.cap.max_inline_data;
317
318 rdma->tx_buf = aligned_alloc(4096, RDMA_CHUNK);
319 rdma->rx_buf = aligned_alloc(4096, static_cast<size_t>(RDMA_RX_DEPTH) * RDMA_CHUNK);
320 if (!rdma->tx_buf || !rdma->rx_buf) return false;
321
322 rdma->tx_mr = ibv_reg_mr(rdma->pd, rdma->tx_buf, RDMA_CHUNK, IBV_ACCESS_LOCAL_WRITE);
323 rdma->rx_mr = ibv_reg_mr(rdma->pd, rdma->rx_buf, static_cast<size_t>(RDMA_RX_DEPTH) * RDMA_CHUNK,
324 IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
325 if (!rdma->tx_mr || !rdma->rx_mr) return false;
326
327 ibv_gid local_gid;
328 if (ibv_query_gid(ibctx, ib_port, gid_idx, &local_gid) != 0) return false;
329
330 rdma_local.qpn = rdma->qp->qp_num;
331 rdma_local.psn = rdma->qp->qp_num & 0xffffff;
332 memcpy(&rdma_local.gid, &local_gid, RDMA_GID_SIZE);
333
334 const char * ver_str = "";
335 if (gid_version == IBV_GID_TYPE_ROCE_V2) {
336 ver_str = " RoCEv2";
337 } else if (gid_version == IBV_GID_TYPE_ROCE_V1) {
338 ver_str = " RoCEv1";
339 }
340 LOG_INFO("RDMA probed: dev=%s gid=%d%s qpn=%u inline=%u\n",
341 matched_dev, gid_idx, ver_str, rdma_local.qpn, rdma->max_inline);
342 return true;
343}
344
345// Phase 2: Given remote QPN/PSN/GID, transition QP: RESET->INIT->pre-post->RTR->RTS.
346// On success, the connection is live and ready for rdma_send/rdma_recv.
347bool socket_t::impl::rdma_activate(uint32_t remote_qpn, uint32_t remote_psn, const uint8_t * remote_gid) {
348 // RESET -> INIT
349 {
350 struct ibv_qp_attr a = {};
351 a.qp_state = IBV_QPS_INIT;
352 a.port_num = rdma_local.ib_port;
353 a.pkey_index = 0;
354 a.qp_access_flags = IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_REMOTE_READ | IBV_ACCESS_LOCAL_WRITE;
355 if (ibv_modify_qp(rdma->qp, &a,
356 IBV_QP_STATE | IBV_QP_PKEY_INDEX | IBV_QP_PORT | IBV_QP_ACCESS_FLAGS) != 0) {
357 return false;
358 }
359 }
360
361 for (int i = 0; i < RDMA_RX_DEPTH; i++) {
362 if (!rdma->post_rx(i)) return false;
363 }
364
365 // INIT -> RTR
366 {
367 struct ibv_qp_attr a = {};
368 a.qp_state = IBV_QPS_RTR;
369 a.path_mtu = rdma_local.path_mtu;
370 a.dest_qp_num = remote_qpn;
371 a.rq_psn = remote_psn;
372 a.max_dest_rd_atomic = 1;
373 a.min_rnr_timer = 1;
374 a.ah_attr.is_global = 1;
375 memcpy(&a.ah_attr.grh.dgid, remote_gid, RDMA_GID_SIZE);
376 a.ah_attr.grh.hop_limit = 1;
377 a.ah_attr.grh.sgid_index = rdma_local.gid_idx;
378 a.ah_attr.dlid = 0;
379 a.ah_attr.port_num = rdma_local.ib_port;
380 if (ibv_modify_qp(rdma->qp, &a,
381 IBV_QP_STATE | IBV_QP_AV | IBV_QP_PATH_MTU | IBV_QP_DEST_QPN |
382 IBV_QP_RQ_PSN | IBV_QP_MAX_DEST_RD_ATOMIC | IBV_QP_MIN_RNR_TIMER) != 0) {
383 return false;
384 }
385 }
386
387 // RTR -> RTS
388 {
389 struct ibv_qp_attr a = {};
390 a.qp_state = IBV_QPS_RTS;
391 a.timeout = 14;
392 a.retry_cnt = 7;
393 a.rnr_retry = 7;
394 a.sq_psn = rdma_local.psn;
395 a.max_rd_atomic = 1;
396 if (ibv_modify_qp(rdma->qp, &a,
397 IBV_QP_STATE | IBV_QP_TIMEOUT | IBV_QP_RETRY_CNT | IBV_QP_RNR_RETRY |
398 IBV_QP_SQ_PSN | IBV_QP_MAX_QP_RD_ATOMIC) != 0) {
399 return false;
400 }
401 }
402
403 rdma->last_active = std::chrono::steady_clock::now();
404
405 LOG_INFO("RDMA activated: qpn=%u->%u mtu=%d rx_depth=%d\n",
406 rdma_local.qpn, remote_qpn, 128 << rdma_local.path_mtu, RDMA_RX_DEPTH);
407 return true;
408}
409
410// Sleep until the completion channel has an event or the TCP peer closes.
411bool socket_t::impl::rdma_wait_event() {
412 rdma_conn * c = rdma.get();
413 // POLLHUP and POLLERR are always reported, the TCP socket carries no data after the RDMA upgrade
414 struct pollfd pfds[2] = {
415 { c->ch->fd, POLLIN, 0 },
416 { fd, POLLRDHUP, 0 },
417 };
418 if (poll(pfds, 2, -1) < 0) {
419 return errno == EINTR;
420 }
421 if (pfds[1].revents & (POLLHUP | POLLERR | POLLRDHUP)) {
422 return false;
423 }
424 if (pfds[0].revents & POLLIN) {
425 struct ibv_cq * ev_cq = nullptr;
426 void * ev_ctx = nullptr;
427 if (ibv_get_cq_event(c->ch, &ev_cq, &ev_ctx) != 0) {
428 return false;
429 }
430 ibv_ack_cq_events(ev_cq, 1);
431 }
432 return true;
433}
434
435bool socket_t::impl::rdma_poll(struct ibv_cq * cq, struct ibv_wc * wc) {
436 rdma_conn * c = rdma.get();
437 bool armed = false;
438 for (uint64_t s = 1; ; s++) {
439 int n = ibv_poll_cq(cq, 1, wc);
440 if (n > 0) {
441 c->last_active = std::chrono::steady_clock::now();
442 if (wc->status != IBV_WC_SUCCESS) {
443 LOG_ERROR("RDMA CQ wc error: status=%d (%s) vendor_err=0x%x\n",
444 wc->status, ibv_wc_status_str(wc->status), wc->vendor_err);
445 }
446 return wc->status == IBV_WC_SUCCESS;
447 }
448 if (n < 0) return false;
449 if (armed) {
450 // armed and still empty: sleep until the next completion
451 if (!rdma_wait_event()) {
452 return false;
453 }
454 armed = false;
455 continue;
456 }
457 // spin while the connection is busy, arm the CQ once it has been idle for RDMA_SPIN_TIME
458 // a completion that arrives before arming raises no event, so poll once more after arming
459 if (c->ch && (s & 0x3FF) == 0 && std::chrono::steady_clock::now() - c->last_active > RDMA_SPIN_TIME) {
460 if (ibv_req_notify_cq(cq, 0) != 0) {
461 return false;
462 }
463 armed = true;
464 continue;
465 }
466 if ((s & 0xFFFFF) == 0) {
467 if (tcp_peer_closed()) {
468 return false;
469 }
470 }
471 }
472}
473
474bool socket_t::impl::rdma_send(const void * data, size_t size) {
475 rdma_conn * c = rdma.get();
476 const uint8_t * src = (const uint8_t *)data;
477 size_t rem = size;
478 while (rem > 0) {
479 size_t chunk = std::min(rem, RDMA_CHUNK);
480
481 struct ibv_sge sge = {};
482 struct ibv_send_wr wr = {}, * bad = nullptr;
483 wr.opcode = IBV_WR_SEND;
484 wr.sg_list = &sge;
485 wr.num_sge = 1;
486
487 if (chunk <= c->max_inline) {
488 sge.addr = (uintptr_t)src;
489 sge.length = chunk;
490 wr.send_flags = IBV_SEND_SIGNALED | IBV_SEND_INLINE;
491 } else {
492 memcpy(c->tx_buf, src, chunk);
493 sge.addr = (uintptr_t)c->tx_buf;
494 sge.length = chunk;
495 sge.lkey = c->tx_mr->lkey;
496 wr.send_flags = IBV_SEND_SIGNALED;
497 }
498
499 if (ibv_post_send(c->qp, &wr, &bad) != 0) return false;
500 c->last_active = std::chrono::steady_clock::now();
501 struct ibv_wc wc;
502 if (!rdma_poll(c->scq, &wc)) return false;
503
504 src += chunk;
505 rem -= chunk;
506 }
507 return true;
508}
509
510bool socket_t::impl::rdma_recv(void * data, size_t size) {
511 rdma_conn * c = rdma.get();
512 uint8_t * dst = (uint8_t *)data;
513 size_t rem = size;
514 while (rem > 0) {
515 struct ibv_wc wc;
516 if (!rdma_poll(c->rcq, &wc)) return false;
517
518 int slot = (int)wc.wr_id;
519 size_t got = wc.byte_len;
520 if (got > rem) {
521 LOG_ERROR("RDMA recv overrun: got=%zu rem=%zu\n", got, rem);
522 c->post_rx(slot);
523 return false;
524 }
525 memcpy(dst, c->rx_slot(slot), got);
526
527 if (!c->post_rx(slot)) return false;
528
529 dst += got;
530 rem -= got;
531 }
532 return true;
533}
534
535#endif // !GGML_RPC_RDMA_APPLE (Linux RC transport)
536
537#endif // GGML_RPC_RDMA
538
539bool socket_t::impl::send_data(const void * data, size_t size) {
540 LOG_DBG3("[%s] transport: %s, size: %s\n", __func__, use_rdma ? "RDMA" : "TCP", rpc_log_format_size(size).c_str());
541#ifdef GGML_RPC_RDMA_APPLE
542 if (use_rdma) {
543 return rdma->send(data, size);
544 }
545#elif defined(GGML_RPC_RDMA)
546 if (use_rdma) {
547 return rdma_send(data, size);
548 }
549#endif
550 size_t bytes_sent = 0;
551 while (bytes_sent < size) {
552 size_t size_to_send = std::min(size - bytes_sent, MAX_CHUNK_SIZE);
553 ssize_t n = send(fd, (const char *)data + bytes_sent, size_to_send, 0);
554 if (n < 0) {
555 LOG_ERROR("send failed (bytes_sent=%zu, size_to_send=%zu)\n",
556 bytes_sent, size_to_send);
557 return false;
558 }
559 bytes_sent += (size_t)n;
560 }
561 return true;
562}
563
564bool socket_t::impl::recv_data(void * data, size_t size) {
565 LOG_DBG3("[%s] transport: %s, size: %s\n", __func__, use_rdma ? "RDMA" : "TCP", rpc_log_format_size(size).c_str());
566#ifdef GGML_RPC_RDMA_APPLE
567 if (use_rdma) {
568 return rdma->recv(data, size);
569 }
570#elif defined(GGML_RPC_RDMA)
571 if (use_rdma) {
572 return rdma_recv(data, size);
573 }
574#endif
575 size_t bytes_recv = 0;
576 while (bytes_recv < size) {
577 size_t size_to_recv = std::min(size - bytes_recv, MAX_CHUNK_SIZE);
578 ssize_t n = recv(fd, (char *)data + bytes_recv, size_to_recv, 0);
579 if (n < 0) {
580 LOG_ERROR("recv failed (bytes_recv=%zu, size_to_recv=%zu)\n",
581 bytes_recv, size_to_recv);
582 return false;
583 }
584 if (n == 0) {
585 LOG_WARN("recv returned 0 (peer closed?)\n");
586 return false;
587 }
588 bytes_recv += (size_t)n;
589 }
590 return true;
591}
592
593void socket_t::impl::get_caps(uint8_t * local_caps) {
594 memset(local_caps, 0, RPC_CONN_CAPS_SIZE);
595#ifdef GGML_RPC_RDMA
596 if (std::getenv("GGML_RPC_NO_RDMA")) {
597 return;
598 }
599# ifdef GGML_RPC_RDMA_APPLE
600 auto target_gid = rdma_build_target_gid();
601 if (target_gid) {
602 rdma = apple_rdma::probe(fd, target_gid->data(), local_caps);
603 }
604 if (!rdma) {
605 LOG_DBG2("[%s] RDMA probe failed, continuing with TCP\n", __func__);
606 }
607# else
608 rdma_local = {};
609 if (rdma_probe()) {
610 rdma_caps rc = {};
611 rc.qpn = rdma_local.qpn;
612 rc.psn = rdma_local.psn;
613 memcpy(rc.gid, rdma_local.gid, RDMA_GID_SIZE);
614 memcpy(local_caps, &rc, sizeof(rc));
615 } else {
616 rdma.reset();
617 LOG_DBG2("[%s] RDMA probe failed, continuing with TCP\n", __func__);
618 }
619# endif
620#endif // GGML_RPC_RDMA
621}
622
623void socket_t::impl::update_caps(const uint8_t * remote_caps) {
624#ifdef GGML_RPC_RDMA
625 // a peer that has no RDMA advertises all-zero caps and takes no further part
626 // in the negotiation, so drop to TCP without reporting a failure
627 bool remote_rdma = false;
628 for (size_t i = 0; i < RPC_CONN_CAPS_SIZE; i++) {
629 remote_rdma |= remote_caps[i] != 0;
630 }
631 if (!rdma || !remote_rdma) {
632 if (rdma && !remote_rdma) {
633 LOG_WARN("[%s] peer does not support RDMA, continuing with TCP\n", __func__);
634 }
635 rdma.reset();
636 return;
637 }
638# ifdef GGML_RPC_RDMA_APPLE
639 bool activated = rdma->activate(remote_caps);
640# else
641 rdma_caps rc = {};
642 memcpy(&rc, remote_caps, sizeof(rc));
643 bool activated = rdma_activate(rc.qpn, rc.psn, rc.gid);
644# endif
645 if (activated) {
646 use_rdma = true;
647 } else {
648 LOG_WARN("RDMA activate failed, staying on TCP\n");
649 rdma.reset();
650 }
651#else
652 (void)remote_caps;
653#endif // GGML_RPC_RDMA
654}
655
656bool socket_t::impl::flush() {
657#ifdef GGML_RPC_RDMA_APPLE
658 if (use_rdma) {
659 return rdma->flush();
660 }
661#endif
662 return true;
663}
664
665/////////////////////////////////////////////////////////////////////////////
666
667socket_t::socket_t(std::unique_ptr<impl> p) : pimpl(std::move(p)) {}
668
669socket_t::~socket_t() = default;
670
671bool socket_t::send_data(const void * data, size_t size) {
672 return pimpl->send_data(data, size);
673}
674
675bool socket_t::recv_data(void * data, size_t size) {
676 return pimpl->recv_data(data, size);
677}
678
679bool socket_t::flush() {
680 return pimpl->flush();
681}
682
683void socket_t::get_caps(uint8_t * local_caps) {
684 return pimpl->get_caps(local_caps);
685}
686
687void socket_t::update_caps(const uint8_t * remote_caps) {
688 return pimpl->update_caps(remote_caps);
689}
690
691const char * socket_t::transport_name() const {
692 return pimpl->use_rdma ? "RDMA" : "TCP";
693}
694
695static bool is_valid_fd(sockfd_t sockfd) {
696#ifdef _WIN32
697 return sockfd != INVALID_SOCKET;
698#else
699 return sockfd >= 0;
700#endif
701}
702
703static bool set_no_delay(sockfd_t sockfd) {
704 int flag = 1;
705 // set TCP_NODELAY to disable Nagle's algorithm
706 int ret = setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
707 return ret == 0;
708}
709
710static bool set_reuse_addr(sockfd_t sockfd) {
711 int flag = 1;
712 int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(int));
713 return ret == 0;
714}
715
716socket_ptr socket_t::accept() {
717 auto client_socket_fd = ::accept(pimpl->fd, NULL, NULL);
718 if (!is_valid_fd(client_socket_fd)) {
719 return nullptr;
720 }
721 if (!set_no_delay(client_socket_fd)) {
722 LOG_ERROR("Failed to set TCP_NODELAY\n");
723 return nullptr;
724 }
725 LOG_DBG("[%s] accepted client connection\n", __func__);
726 return socket_ptr(new socket_t(std::make_unique<impl>(client_socket_fd)));
727}
728
729socket_ptr socket_t::create_server(const char * host, int port) {
730 auto sockfd = socket(AF_INET, SOCK_STREAM, 0);
731 if (!is_valid_fd(sockfd)) {
732 return nullptr;
733 }
734 if (!set_reuse_addr(sockfd)) {
735 LOG_ERROR("Failed to set SO_REUSEADDR\n");
736 return nullptr;
737 }
738 if (inet_addr(host) == INADDR_NONE) {
739 LOG_ERROR("Invalid host address: %s\n", host);
740 return nullptr;
741 }
742 struct sockaddr_in serv_addr;
743 serv_addr.sin_family = AF_INET;
744 serv_addr.sin_addr.s_addr = inet_addr(host);
745 serv_addr.sin_port = htons(port);
746
747 if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
748 return nullptr;
749 }
750 if (listen(sockfd, 1) < 0) {
751 return nullptr;
752 }
753 LOG_DBG("[%s] listening on %s:%d\n", __func__, host, port);
754 return socket_ptr(new socket_t(std::make_unique<impl>(sockfd)));
755}
756
757socket_ptr socket_t::connect(const char * host, int port) {
758 auto sockfd = socket(AF_INET, SOCK_STREAM, 0);
759 if (!is_valid_fd(sockfd)) {
760 return nullptr;
761 }
762 if (!set_no_delay(sockfd)) {
763 LOG_ERROR("Failed to set TCP_NODELAY\n");
764 return nullptr;
765 }
766 struct sockaddr_in addr;
767 addr.sin_family = AF_INET;
768 addr.sin_port = htons(port);
769 struct hostent * server = gethostbyname(host);
770 if (server == NULL) {
771 LOG_ERROR("Cannot resolve host '%s'\n", host);
772 return nullptr;
773 }
774 memcpy(&addr.sin_addr.s_addr, server->h_addr, server->h_length);
775 if (::connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
776 return nullptr;
777 }
778 LOG_DBG("[%s] connected to %s:%d\n", __func__, host, port);
779 return socket_ptr(new socket_t(std::make_unique<impl>(sockfd)));
780}
781
782#ifdef _WIN32
783static std::mutex g_rpc_transport_mu;
784static bool g_rpc_transport_wsa_started = false;
785#endif
786
787bool rpc_transport_init() {
788#ifdef _WIN32
789 std::lock_guard<std::mutex> lock(g_rpc_transport_mu);
790 if (g_rpc_transport_wsa_started) {
791 return true;
792 }
793 WSADATA wsaData;
794 int res = WSAStartup(MAKEWORD(2, 2), &wsaData);
795 if (res != 0) {
796 return false;
797 }
798 g_rpc_transport_wsa_started = true;
799 return true;
800#else
801 return true;
802#endif
803}
804
805void rpc_transport_shutdown() {
806#ifdef _WIN32
807 std::lock_guard<std::mutex> lock(g_rpc_transport_mu);
808 if (!g_rpc_transport_wsa_started) {
809 return;
810 }
811 WSACleanup();
812 g_rpc_transport_wsa_started = false;
813#endif
814}