c_bridge.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. /*
  2. * c_bridge.c — XJKJ-STL Native C Runtime Bridge (v0.8.1.19)
  3. *
  4. * Compiled strictly with -O3 -march=x86-64 (pure SSE2 baseline, no AVX/POPCNT
  5. * emitted by the compiler) so dual-core Celeron/Pentium (Sandy Bridge..Coffee Lake)
  6. * never trigger SIGILL. Runtime CPUID + XGETBV dispatches SSE2 / SSE4.2 / AVX2
  7. * assembly kernels dynamically.
  8. */
  9. #define _GNU_SOURCE
  10. #include "stl_accel.h"
  11. #include <arpa/inet.h>
  12. #include <cpuid.h>
  13. #include <errno.h>
  14. #include <fcntl.h>
  15. #include <netdb.h>
  16. #include <netinet/in.h>
  17. #include <netinet/tcp.h>
  18. #include <poll.h>
  19. #include <pty.h>
  20. #include <pthread.h>
  21. #include <sched.h>
  22. #include <signal.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <sys/epoll.h>
  27. #include <sys/eventfd.h>
  28. #include <sys/mman.h>
  29. #include <sys/socket.h>
  30. #include <sys/timerfd.h>
  31. #include <sys/uio.h>
  32. #include <sys/wait.h>
  33. #include <termios.h>
  34. #include <time.h>
  35. #include <unistd.h>
  36. /* =========================================================================
  37. * 1. Runtime CPUID + XGETBV ISA Tier Detection & Dispatch
  38. * ========================================================================= */
  39. typedef struct {
  40. uint32_t isa_tier;
  41. uint32_t has_sse42;
  42. uint32_t has_avx2;
  43. uint32_t has_bmi2;
  44. char cpu_brand[64];
  45. char tier_name[32];
  46. } StlHwCapsCompat;
  47. static pthread_once_t g_hw_once = PTHREAD_ONCE_INIT;
  48. static int g_detected_tier = STL_ISA_SSE2;
  49. static int g_forced_tier = -1;
  50. static StlHwCapsCompat g_hw_caps;
  51. static void detect_hw_once(void) {
  52. memset(&g_hw_caps, 0, sizeof(g_hw_caps));
  53. unsigned int eax = 0, ebx = 0, ecx = 0, edx = 0;
  54. unsigned int max_leaf = __get_cpuid_max(0, NULL);
  55. int has_sse42 = 0;
  56. int has_popcnt = 0;
  57. int has_osxsave = 0;
  58. int has_avx = 0;
  59. int has_avx2 = 0;
  60. int has_bmi1 = 0;
  61. int has_bmi2 = 0;
  62. if (max_leaf >= 1 && __get_cpuid(1, &eax, &ebx, &ecx, &edx)) {
  63. has_sse42 = (ecx & (1u << 20)) != 0;
  64. has_popcnt = (ecx & (1u << 23)) != 0;
  65. has_osxsave = (ecx & (1u << 27)) != 0;
  66. has_avx = (ecx & (1u << 28)) != 0;
  67. }
  68. int ymm_os_ok = 0;
  69. if (has_osxsave && has_avx) {
  70. uint64_t xcr0 = asm_xgetbv_eax0();
  71. ymm_os_ok = ((xcr0 & 0x6ULL) == 0x6ULL);
  72. }
  73. if (max_leaf >= 7 && __get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx)) {
  74. has_bmi1 = (ebx & (1u << 3)) != 0;
  75. has_avx2 = (ebx & (1u << 5)) != 0;
  76. has_bmi2 = (ebx & (1u << 8)) != 0;
  77. }
  78. if (ymm_os_ok && has_avx2 && has_bmi1 && has_bmi2 && has_sse42 && has_popcnt) {
  79. g_detected_tier = STL_ISA_AVX2_BMI;
  80. } else if (has_sse42 && has_popcnt) {
  81. g_detected_tier = STL_ISA_SSE42_POPCNT;
  82. } else {
  83. g_detected_tier = STL_ISA_SSE2;
  84. }
  85. /* Read CPU brand string (leaves 0x80000002..0x80000004) */
  86. unsigned int max_ext = __get_cpuid_max(0x80000000u, NULL);
  87. if (max_ext >= 0x80000004u) {
  88. uint32_t brand_words[12];
  89. __get_cpuid(0x80000002u, &brand_words[0], &brand_words[1], &brand_words[2], &brand_words[3]);
  90. __get_cpuid(0x80000003u, &brand_words[4], &brand_words[5], &brand_words[6], &brand_words[7]);
  91. __get_cpuid(0x80000004u, &brand_words[8], &brand_words[9], &brand_words[10], &brand_words[11]);
  92. memcpy(g_hw_caps.cpu_brand, brand_words, 48);
  93. g_hw_caps.cpu_brand[48] = '\0';
  94. } else {
  95. snprintf(g_hw_caps.cpu_brand, sizeof(g_hw_caps.cpu_brand), "x86_64-generic");
  96. }
  97. g_hw_caps.isa_tier = (uint32_t)g_detected_tier;
  98. g_hw_caps.has_sse42 = (uint32_t)(has_sse42 && has_popcnt);
  99. g_hw_caps.has_avx2 = (uint32_t)(ymm_os_ok && has_avx2);
  100. g_hw_caps.has_bmi2 = (uint32_t)has_bmi2;
  101. snprintf(g_hw_caps.tier_name, sizeof(g_hw_caps.tier_name), "%s", stl_isa_tier_name(g_detected_tier));
  102. }
  103. void c_init_once_hw_dispatch(void) {
  104. pthread_once(&g_hw_once, detect_hw_once);
  105. }
  106. int stl_cpu_tier_detect(void) {
  107. pthread_once(&g_hw_once, detect_hw_once);
  108. return g_detected_tier;
  109. }
  110. int stl_active_isa_tier(void) {
  111. pthread_once(&g_hw_once, detect_hw_once);
  112. int forced = __atomic_load_n(&g_forced_tier, __ATOMIC_RELAXED);
  113. if (forced >= STL_ISA_SSE2 && forced <= STL_ISA_AVX2_BMI) {
  114. if (forced <= g_detected_tier) return forced;
  115. }
  116. return g_detected_tier;
  117. }
  118. void stl_force_isa_tier(int tier) {
  119. pthread_once(&g_hw_once, detect_hw_once);
  120. __atomic_store_n(&g_forced_tier, tier, __ATOMIC_RELAXED);
  121. }
  122. const char *stl_isa_tier_name(int tier) {
  123. switch (tier) {
  124. case STL_ISA_AVX2_BMI: return "AVX2+BMI1/2";
  125. case STL_ISA_SSE42_POPCNT: return "SSE4.2+POPCNT";
  126. default: return "SSE2-baseline";
  127. }
  128. }
  129. void c_get_hw_caps(StlHwCapsCompat *out_caps) {
  130. pthread_once(&g_hw_once, detect_hw_once);
  131. if (!out_caps) return;
  132. *out_caps = g_hw_caps;
  133. int active = stl_active_isa_tier();
  134. out_caps->isa_tier = (uint32_t)active;
  135. snprintf(out_caps->tier_name, sizeof(out_caps->tier_name), "%s", stl_isa_tier_name(active));
  136. }
  137. size_t stl_base64_encode(const uint8_t *src, size_t len, uint8_t *dst) {
  138. if (!src || !dst || len == 0) return 0;
  139. int tier = stl_active_isa_tier();
  140. if (tier >= STL_ISA_AVX2_BMI) {
  141. return asm_base64_encode_avx2(src, len, dst);
  142. }
  143. return asm_base64_encode_sse2(src, len, dst);
  144. }
  145. void stl_clean_stream_init(StlCleanStreamState *state) {
  146. if (!state) return;
  147. memset(state, 0, sizeof(*state));
  148. }
  149. void stl_clean_stream_clear_halfline(StlCleanStreamState *state) {
  150. if (!state) return;
  151. state->half_len = 0;
  152. state->tag_mask = 0;
  153. state->first_nonws = 0;
  154. state->cur_col = 0;
  155. state->prev_was_cr = 0;
  156. state->esc_state = 0;
  157. }
  158. void stl_clean_split_classify(
  159. StlCleanStreamState *state,
  160. const uint8_t *src,
  161. size_t src_len,
  162. StlCleanOutput *out) {
  163. if (!state || !out) return;
  164. if (!src || src_len == 0) {
  165. out->src_consumed = 0;
  166. return;
  167. }
  168. int tier = stl_active_isa_tier();
  169. if (tier >= STL_ISA_AVX2_BMI) {
  170. asm_clean_split_classify_avx2(state, src, src_len, out);
  171. } else if (tier >= STL_ISA_SSE42_POPCNT) {
  172. asm_clean_split_classify_sse42(state, src, src_len, out);
  173. } else {
  174. asm_clean_split_classify_sse2(state, src, src_len, out);
  175. }
  176. }
  177. /* Pure SSE2 helper for legacy single-buffer scan (zero rdtsc/lfence!) */
  178. size_t c_dispatch_scan_special(
  179. const uint8_t *buf,
  180. size_t len,
  181. uint64_t *out_newlines,
  182. uint64_t *out_specials) {
  183. uint64_t nl = 0;
  184. uint64_t sp = 0;
  185. size_t first_ctrl = len;
  186. for (size_t i = 0; i < len; i++) {
  187. uint8_t b = buf[i];
  188. if (b == '\n' || b == '\r') {
  189. nl++;
  190. } else if (b < 0x20 || b == 0x7f) {
  191. sp++;
  192. if (first_ctrl == len) first_ctrl = i;
  193. }
  194. }
  195. if (out_newlines) *out_newlines = nl;
  196. if (out_specials) *out_specials = sp;
  197. return first_ctrl;
  198. }
  199. /* =========================================================================
  200. * 2. Monotonic 64-Bit mmap Ring Buffer (Hugepage + 64B Pad + PROT_NONE Guard)
  201. * ========================================================================= */
  202. static size_t round_up_pow2_min2m(size_t v) {
  203. size_t cap = 2u * 1024u * 1024u; /* 2 MiB hugepage granularity */
  204. while (cap < v && cap < (1ULL << 30)) {
  205. cap <<= 1;
  206. }
  207. return cap;
  208. }
  209. int stl_ring_init(StlRingBuf *rb, size_t requested_cap) {
  210. if (!rb) return -1;
  211. memset(rb, 0, sizeof(*rb));
  212. size_t cap = round_up_pow2_min2m(requested_cap == 0 ? (8u * 1024u * 1024u) : requested_cap);
  213. size_t page_sz = 4096u;
  214. /* [0..cap): circular ring; [cap..cap+4096): 64B+ zeroed tail pad page; [cap+4096..cap+8192): PROT_NONE guard */
  215. size_t pad_bytes = page_sz;
  216. size_t guard_bytes = page_sz;
  217. size_t total = cap + pad_bytes + guard_bytes;
  218. void *mem = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  219. if (mem == MAP_FAILED) {
  220. return -1;
  221. }
  222. #ifdef MADV_HUGEPAGE
  223. (void)madvise(mem, cap, MADV_HUGEPAGE);
  224. #endif
  225. /* Arm hardware guard page immediately after the 4KB tail-padding page */
  226. uint8_t *base = (uint8_t *)mem;
  227. memset(base + cap, 0, pad_bytes);
  228. if (mprotect(base + cap + pad_bytes, guard_bytes, PROT_NONE) != 0) {
  229. munmap(mem, total);
  230. return -1;
  231. }
  232. rb->buf = base;
  233. rb->cap = cap;
  234. rb->mask = cap - 1;
  235. rb->mmap_total = total;
  236. rb->base_offset = 0;
  237. rb->write_offset = 0;
  238. return 0;
  239. }
  240. void stl_ring_destroy(StlRingBuf *rb) {
  241. if (!rb) return;
  242. if (rb->buf && rb->mmap_total > 0) {
  243. munmap(rb->buf, rb->mmap_total);
  244. }
  245. memset(rb, 0, sizeof(*rb));
  246. }
  247. uint64_t stl_ring_append(StlRingBuf *rb, const uint8_t *data, size_t len) {
  248. if (!rb || !rb->buf) return 0;
  249. if (!data || len == 0) return rb->write_offset;
  250. if (len >= rb->cap) {
  251. /* Input chunk exceeds entire ring capacity: retain trailing cap bytes */
  252. const uint8_t *tail = data + (len - rb->cap);
  253. uint64_t new_wo = rb->write_offset + (uint64_t)len;
  254. uint64_t new_bo = new_wo - (uint64_t)rb->cap;
  255. size_t pos = (size_t)(new_bo & rb->mask);
  256. size_t first = rb->cap - pos;
  257. memcpy(rb->buf + pos, tail, first);
  258. if (first < rb->cap) {
  259. memcpy(rb->buf, tail + first, rb->cap - first);
  260. }
  261. memset(rb->buf + rb->cap, 0, 64);
  262. rb->write_offset = new_wo;
  263. rb->base_offset = new_bo;
  264. return rb->write_offset;
  265. }
  266. size_t pos = (size_t)(rb->write_offset & rb->mask);
  267. size_t first = rb->cap - pos;
  268. if (first >= len) {
  269. memcpy(rb->buf + pos, data, len);
  270. } else {
  271. memcpy(rb->buf + pos, data, first);
  272. memcpy(rb->buf, data + first, len - first);
  273. }
  274. /* Ensure 64-byte SIMD tail padding stays zeroed */
  275. memset(rb->buf + rb->cap, 0, 64);
  276. rb->write_offset += (uint64_t)len;
  277. if (rb->write_offset - rb->base_offset > (uint64_t)rb->cap) {
  278. /* Slide oldest bound forward; write_offset NEVER regresses */
  279. rb->base_offset = rb->write_offset - (uint64_t)rb->cap;
  280. }
  281. return rb->write_offset;
  282. }
  283. size_t stl_ring_read(
  284. const StlRingBuf *rb,
  285. uint64_t req_offset,
  286. uint8_t *dst,
  287. size_t max_len,
  288. uint64_t *out_actual_start,
  289. uint64_t *out_next_offset) {
  290. if (!rb || !rb->buf) {
  291. if (out_actual_start) *out_actual_start = 0;
  292. if (out_next_offset) *out_next_offset = 0;
  293. return 0;
  294. }
  295. uint64_t start = req_offset;
  296. if (start < rb->base_offset) {
  297. /* Reader fell behind trimmed window: advance monotonically to base_offset */
  298. start = rb->base_offset;
  299. }
  300. if (start >= rb->write_offset || !dst || max_len == 0) {
  301. uint64_t cur = rb->write_offset;
  302. if (out_actual_start) *out_actual_start = cur;
  303. if (out_next_offset) *out_next_offset = cur;
  304. return 0;
  305. }
  306. uint64_t avail = rb->write_offset - start;
  307. size_t n = (avail < (uint64_t)max_len) ? (size_t)avail : max_len;
  308. size_t pos = (size_t)(start & rb->mask);
  309. size_t first = rb->cap - pos;
  310. if (first >= n) {
  311. memcpy(dst, rb->buf + pos, n);
  312. } else {
  313. memcpy(dst, rb->buf + pos, first);
  314. memcpy(dst + first, rb->buf, n - first);
  315. }
  316. if (out_actual_start) *out_actual_start = start;
  317. if (out_next_offset) *out_next_offset = start + (uint64_t)n;
  318. return n;
  319. }
  320. void stl_ring_clear_monotonic(StlRingBuf *rb) {
  321. if (!rb) return;
  322. /* Advance base_offset to write_offset so old data is logically trimmed WITHOUT resetting offset! */
  323. rb->base_offset = rb->write_offset;
  324. }
  325. /* =========================================================================
  326. * 3. epoll / timerfd / eventfd / TCP_NODELAY + writev / Core Affinity
  327. * ========================================================================= */
  328. int stl_epoll_create(void) {
  329. return epoll_create1(EPOLL_CLOEXEC);
  330. }
  331. int stl_epoll_ctl_fd(int epfd, int op, int fd, uint32_t events, uint64_t token) {
  332. struct epoll_event ev;
  333. memset(&ev, 0, sizeof(ev));
  334. ev.events = events;
  335. ev.data.u64 = token;
  336. return epoll_ctl(epfd, op, fd, &ev);
  337. }
  338. int stl_epoll_wait_tokens(
  339. int epfd,
  340. uint64_t *out_tokens,
  341. uint32_t *out_events,
  342. int max_ev,
  343. int timeout_ms) {
  344. if (epfd < 0 || max_ev <= 0) return 0;
  345. if (max_ev > 128) max_ev = 128;
  346. struct epoll_event evs[128];
  347. int n = epoll_wait(epfd, evs, max_ev, timeout_ms);
  348. if (n <= 0) return 0;
  349. for (int i = 0; i < n; i++) {
  350. if (out_tokens) out_tokens[i] = evs[i].data.u64;
  351. if (out_events) out_events[i] = evs[i].events;
  352. }
  353. return n;
  354. }
  355. int stl_timerfd_create_ms(uint64_t initial_ms, uint64_t interval_ms) {
  356. int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
  357. if (tfd < 0) return -1;
  358. if (stl_timerfd_arm_ms(tfd, initial_ms, interval_ms) != 0) {
  359. close(tfd);
  360. return -1;
  361. }
  362. return tfd;
  363. }
  364. int stl_timerfd_arm_ms(int tfd, uint64_t initial_ms, uint64_t interval_ms) {
  365. if (tfd < 0) return -1;
  366. struct itimerspec its;
  367. memset(&its, 0, sizeof(its));
  368. its.it_value.tv_sec = (time_t)(initial_ms / 1000ULL);
  369. its.it_value.tv_nsec = (long)((initial_ms % 1000ULL) * 1000000ULL);
  370. its.it_interval.tv_sec = (time_t)(interval_ms / 1000ULL);
  371. its.it_interval.tv_nsec = (long)((interval_ms % 1000ULL) * 1000000ULL);
  372. return timerfd_settime(tfd, 0, &its, NULL);
  373. }
  374. void stl_timerfd_drain(int tfd) {
  375. if (tfd < 0) return;
  376. uint64_t exp = 0;
  377. while (read(tfd, &exp, sizeof(exp)) > 0) {}
  378. }
  379. int stl_eventfd_create(void) {
  380. return eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
  381. }
  382. void stl_eventfd_notify(int efd) {
  383. if (efd < 0) return;
  384. uint64_t v = 1;
  385. ssize_t _r = write(efd, &v, sizeof(v));
  386. (void)_r;
  387. }
  388. void stl_eventfd_drain(int efd) {
  389. if (efd < 0) return;
  390. uint64_t v = 0;
  391. while (read(efd, &v, sizeof(v)) > 0) {}
  392. }
  393. int stl_set_nonblocking_nodelay(int fd, int is_tcp) {
  394. if (fd < 0) return -1;
  395. int flags = fcntl(fd, F_GETFL, 0);
  396. if (flags >= 0) {
  397. (void)fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  398. }
  399. if (is_tcp) {
  400. int one = 1;
  401. (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
  402. (void)setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
  403. }
  404. return 0;
  405. }
  406. /* Merged WebSocket header + payload writev (eliminates 44ms delayed-ACK stall) */
  407. int64_t stl_ws_writev2(
  408. int fd,
  409. const uint8_t *hdr,
  410. size_t hdr_len,
  411. const uint8_t *body,
  412. size_t body_len) {
  413. if (fd < 0) return -1;
  414. size_t off0 = 0;
  415. size_t off1 = 0;
  416. size_t total = hdr_len + body_len;
  417. size_t sent = 0;
  418. while (sent < total) {
  419. struct iovec iov[2];
  420. int iovcnt = 0;
  421. if (off0 < hdr_len) {
  422. iov[iovcnt].iov_base = (void *)(hdr + off0);
  423. iov[iovcnt].iov_len = hdr_len - off0;
  424. iovcnt++;
  425. }
  426. if (off1 < body_len) {
  427. iov[iovcnt].iov_base = (void *)(body + off1);
  428. iov[iovcnt].iov_len = body_len - off1;
  429. iovcnt++;
  430. }
  431. ssize_t n = writev(fd, iov, iovcnt);
  432. if (n > 0) {
  433. size_t adv = (size_t)n;
  434. sent += adv;
  435. if (off0 < hdr_len) {
  436. size_t rem0 = hdr_len - off0;
  437. if (adv <= rem0) {
  438. off0 += adv;
  439. adv = 0;
  440. } else {
  441. off0 = hdr_len;
  442. adv -= rem0;
  443. }
  444. }
  445. off1 += adv;
  446. continue;
  447. }
  448. if (n < 0 && errno == EINTR) continue;
  449. if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
  450. struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0 };
  451. int pr = poll(&pfd, 1, 2000);
  452. if (pr > 0) continue;
  453. return -1;
  454. }
  455. return -1;
  456. }
  457. return (int64_t)sent;
  458. }
  459. void stl_pin_thread_to_core(int core_index) {
  460. if (core_index < 0) return;
  461. long ncores = sysconf(_SC_NPROCESSORS_ONLN);
  462. if (ncores <= 0) return;
  463. int target = core_index % (int)ncores;
  464. cpu_set_t set;
  465. CPU_ZERO(&set);
  466. CPU_SET(target, &set);
  467. (void)pthread_setaffinity_np(pthread_self(), sizeof(set), &set);
  468. }
  469. /* =========================================================================
  470. * 4. Serial / TCP-RS232 / SSH Console (ignore known_hosts!) / IPMI SOL PTYs
  471. * ========================================================================= */
  472. int stl_open_tty_115200_raw(const char *path) {
  473. if (!path || path[0] == '\0') return -1;
  474. /* Safety guard: NEVER touch /dev/ttyUSB1 (reserved for unrelated board) */
  475. if (strstr(path, "ttyUSB1") != NULL) {
  476. return -1;
  477. }
  478. int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
  479. if (fd < 0) return -1;
  480. struct termios tio;
  481. if (tcgetattr(fd, &tio) != 0) {
  482. close(fd);
  483. return -1;
  484. }
  485. cfmakeraw(&tio);
  486. cfsetispeed(&tio, B115200);
  487. cfsetospeed(&tio, B115200);
  488. tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
  489. tio.c_cflag |= (CS8 | CLOCAL | CREAD);
  490. tio.c_iflag &= ~(IXON | IXOFF | IXANY);
  491. tio.c_cc[VMIN] = 0;
  492. tio.c_cc[VTIME] = 0;
  493. if (tcsetattr(fd, TCSANOW, &tio) != 0) {
  494. close(fd);
  495. return -1;
  496. }
  497. return fd;
  498. }
  499. int c_pty_open_serial_115200(const char *path) {
  500. return stl_open_tty_115200_raw(path);
  501. }
  502. /* Open serial with configurable baud rate (115200 / 230400 / 460800 / 921600) for thermal hood */
  503. int c_open_tty_baud_raw(const char *path, int baud) {
  504. if (!path || path[0] == '\0') return -1;
  505. if (strstr(path, "ttyUSB1") != NULL) return -1;
  506. int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
  507. if (fd < 0) return -1;
  508. struct termios tio;
  509. if (tcgetattr(fd, &tio) != 0) {
  510. close(fd);
  511. return -1;
  512. }
  513. cfmakeraw(&tio);
  514. speed_t sp = B115200;
  515. if (baud == 921600) sp = B921600;
  516. else if (baud == 460800) sp = B460800;
  517. else if (baud == 230400) sp = B230400;
  518. cfsetispeed(&tio, sp);
  519. cfsetospeed(&tio, sp);
  520. tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
  521. tio.c_cflag |= (CS8 | CLOCAL | CREAD);
  522. tio.c_iflag &= ~(IXON | IXOFF | IXANY);
  523. tio.c_cc[VMIN] = 0;
  524. tio.c_cc[VTIME] = 0;
  525. if (tcsetattr(fd, TCSANOW, &tio) != 0) {
  526. close(fd);
  527. return -1;
  528. }
  529. return fd;
  530. }
  531. int c_pty_open_tcp_serial(const char *host, int port, int timeout_ms) {
  532. if (!host || host[0] == '\0' || port <= 0) return -1;
  533. struct addrinfo hints, *res = NULL;
  534. memset(&hints, 0, sizeof(hints));
  535. hints.ai_family = AF_INET;
  536. hints.ai_socktype = SOCK_STREAM;
  537. char port_s[16];
  538. snprintf(port_s, sizeof(port_s), "%d", port);
  539. if (getaddrinfo(host, port_s, &hints, &res) != 0 || !res) return -1;
  540. int sfd = socket(res->ai_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
  541. if (sfd < 0) {
  542. freeaddrinfo(res);
  543. return -1;
  544. }
  545. int one = 1;
  546. (void)setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
  547. (void)setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
  548. int rc = connect(sfd, res->ai_addr, res->ai_addrlen);
  549. freeaddrinfo(res);
  550. if (rc != 0) {
  551. if (errno != EINPROGRESS) {
  552. close(sfd);
  553. return -1;
  554. }
  555. struct pollfd pfd = { .fd = sfd, .events = POLLOUT, .revents = 0 };
  556. int wait_ms = (timeout_ms > 0) ? timeout_ms : 1500;
  557. if (poll(&pfd, 1, wait_ms) <= 0) {
  558. close(sfd);
  559. return -1;
  560. }
  561. int so_err = 0;
  562. socklen_t slen = sizeof(so_err);
  563. if (getsockopt(sfd, SOL_SOCKET, SO_ERROR, &so_err, &slen) != 0 || so_err != 0) {
  564. close(sfd);
  565. return -1;
  566. }
  567. }
  568. return sfd;
  569. }
  570. /*
  571. * Spawn SSH console (port 2200) inside non-blocking PTY.
  572. * Explicitly ignores known_hosts host-key changes so swapping server motherboards
  573. * never blocks or fails with REMOTE HOST IDENTIFICATION HAS CHANGED.
  574. */
  575. int c_pty_spawn_ssh_console(
  576. const char *host,
  577. int port,
  578. const char *user,
  579. const char *password,
  580. const char *known_hosts_path,
  581. int *out_master_fd,
  582. int *out_child_pid) {
  583. (void)known_hosts_path; /* Ignored intentionally per motherboard-swap requirement */
  584. if (!host || !user || !password || !out_master_fd || !out_child_pid) return -1;
  585. int master_fd = -1;
  586. pid_t pid = forkpty(&master_fd, NULL, NULL, NULL);
  587. if (pid < 0) return -1;
  588. if (pid == 0) {
  589. char port_str[16];
  590. snprintf(port_str, sizeof(port_str), "%d", port > 0 ? port : 2200);
  591. setenv("SSHPASS", password, 1);
  592. setenv("TERM", "vt100", 1);
  593. execlp(
  594. "sshpass", "sshpass", "-e",
  595. "ssh",
  596. "-tt",
  597. "-p", port_str,
  598. "-o", "StrictHostKeyChecking=no",
  599. "-o", "UserKnownHostsFile=/dev/null",
  600. "-o", "GlobalKnownHostsFile=/dev/null",
  601. "-o", "LogLevel=ERROR",
  602. "-o", "ConnectTimeout=15",
  603. "-o", "ServerAliveInterval=10",
  604. "-o", "ServerAliveCountMax=3",
  605. "-l", user,
  606. host,
  607. (char *)NULL);
  608. _exit(127);
  609. }
  610. int flags = fcntl(master_fd, F_GETFL, 0);
  611. if (flags >= 0) (void)fcntl(master_fd, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC);
  612. *out_master_fd = master_fd;
  613. *out_child_pid = (int)pid;
  614. return 0;
  615. }
  616. int c_pty_spawn_ipmi_sol(
  617. const char *host,
  618. const char *user,
  619. const char *password,
  620. int *out_master_fd,
  621. int *out_child_pid) {
  622. if (!host || !user || !password || !out_master_fd || !out_child_pid) return -1;
  623. int master_fd = -1;
  624. pid_t pid = forkpty(&master_fd, NULL, NULL, NULL);
  625. if (pid < 0) return -1;
  626. if (pid == 0) {
  627. setenv("IPMI_PASSWORD", password, 1);
  628. setenv("TERM", "vt100", 1);
  629. execlp(
  630. "ipmitool", "ipmitool",
  631. "-I", "lanplus",
  632. "-C", "17",
  633. "-H", host,
  634. "-U", user,
  635. "-E",
  636. "sol", "activate",
  637. (char *)NULL);
  638. _exit(127);
  639. }
  640. int flags = fcntl(master_fd, F_GETFL, 0);
  641. if (flags >= 0) (void)fcntl(master_fd, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC);
  642. *out_master_fd = master_fd;
  643. *out_child_pid = (int)pid;
  644. return 0;
  645. }
  646. /*
  647. * Persistent non-blocking IPMI shell session per station:
  648. * Keeps a single RMCP+ session open via `ipmitool -I lanplus -C <cipher> -H <host> -U <user> -E shell`
  649. * connected to non-blocking stdin/stdout pipes so power & SDR queries execute with zero blocking!
  650. */
  651. int c_spawn_persistent_ipmi_shell(
  652. const char *host,
  653. const char *user,
  654. const char *password,
  655. int cipher_suite,
  656. int *out_stdin_fd,
  657. int *out_stdout_fd,
  658. int *out_child_pid) {
  659. if (!host || !user || !password || !out_stdin_fd || !out_stdout_fd || !out_child_pid) return -1;
  660. int in_pipe[2] = {-1, -1};
  661. int out_pipe[2] = {-1, -1};
  662. if (pipe2(in_pipe, O_CLOEXEC) != 0) return -1;
  663. if (pipe2(out_pipe, O_CLOEXEC) != 0) {
  664. close(in_pipe[0]);
  665. close(in_pipe[1]);
  666. return -1;
  667. }
  668. pid_t pid = fork();
  669. if (pid < 0) {
  670. close(in_pipe[0]); close(in_pipe[1]);
  671. close(out_pipe[0]); close(out_pipe[1]);
  672. return -1;
  673. }
  674. if (pid == 0) {
  675. dup2(in_pipe[0], STDIN_FILENO);
  676. dup2(out_pipe[1], STDOUT_FILENO);
  677. dup2(out_pipe[1], STDERR_FILENO);
  678. close(in_pipe[0]); close(in_pipe[1]);
  679. close(out_pipe[0]); close(out_pipe[1]);
  680. setenv("IPMI_PASSWORD", password, 1);
  681. char ciph[16];
  682. snprintf(ciph, sizeof(ciph), "%d", cipher_suite > 0 ? cipher_suite : 17);
  683. execlp(
  684. "ipmitool", "ipmitool",
  685. "-I", "lanplus",
  686. "-C", ciph,
  687. "-N", "2",
  688. "-R", "1",
  689. "-H", host,
  690. "-U", user,
  691. "-E",
  692. "shell",
  693. (char *)NULL);
  694. _exit(127);
  695. }
  696. close(in_pipe[0]);
  697. close(out_pipe[1]);
  698. (void)stl_set_nonblocking_nodelay(in_pipe[1], 0);
  699. (void)stl_set_nonblocking_nodelay(out_pipe[0], 0);
  700. *out_stdin_fd = in_pipe[1];
  701. *out_stdout_fd = out_pipe[0];
  702. *out_child_pid = (int)pid;
  703. return 0;
  704. }
  705. ssize_t c_pty_read_nonblock(int master_fd, uint8_t *buf, size_t cap) {
  706. if (master_fd < 0 || !buf || cap == 0) return -1;
  707. ssize_t n = read(master_fd, buf, cap);
  708. if (n > 0) return n;
  709. if (n == 0) return -2; /* EOF */
  710. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
  711. return -2; /* EIO / closed */
  712. }
  713. ssize_t c_pty_write_bytes(int master_fd, const uint8_t *buf, size_t len) {
  714. if (master_fd < 0 || !buf || len == 0) return 0;
  715. ssize_t n = write(master_fd, buf, len);
  716. if (n >= 0) return n;
  717. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
  718. return -1;
  719. }
  720. int c_pty_is_alive(int child_pid) {
  721. if (child_pid <= 0) return 0;
  722. int status = 0;
  723. pid_t r = waitpid((pid_t)child_pid, &status, WNOHANG);
  724. if (r == 0) return 1;
  725. return 0;
  726. }
  727. void c_pty_close(int master_fd, int child_pid) {
  728. if (master_fd >= 0) close(master_fd);
  729. if (child_pid > 0 && kill((pid_t)child_pid, 0) == 0) {
  730. kill((pid_t)child_pid, SIGTERM);
  731. int status = 0;
  732. for (int i = 0; i < 10; i++) {
  733. if (waitpid((pid_t)child_pid, &status, WNOHANG) != 0) return;
  734. struct timespec ts = { .tv_sec = 0, .tv_nsec = 5000000L };
  735. nanosleep(&ts, NULL);
  736. }
  737. kill((pid_t)child_pid, SIGKILL);
  738. (void)waitpid((pid_t)child_pid, &status, 0);
  739. }
  740. }