util.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. * Copyright 2012 Giel van Schijndel
  5. * Copyright 2012 Gavin Andresen
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #define _GNU_SOURCE
  13. #include "config.h"
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <ctype.h>
  17. #include <stdarg.h>
  18. #include <string.h>
  19. #include <pthread.h>
  20. #include <jansson.h>
  21. #include <curl/curl.h>
  22. #include <time.h>
  23. #include <errno.h>
  24. #include <unistd.h>
  25. #include <sys/types.h>
  26. #ifdef HAVE_SYS_PRCTL_H
  27. # include <sys/prctl.h>
  28. #endif
  29. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  30. # include <pthread_np.h>
  31. #endif
  32. #ifndef WIN32
  33. # include <sys/socket.h>
  34. # include <netinet/in.h>
  35. # include <netinet/tcp.h>
  36. #else
  37. # include <winsock2.h>
  38. # include <mstcpip.h>
  39. #endif
  40. #include "miner.h"
  41. #include "elist.h"
  42. #include "compat.h"
  43. #if JANSSON_MAJOR_VERSION >= 2
  44. #define JSON_LOADS(str, err_ptr) json_loads((str), 0, (err_ptr))
  45. #else
  46. #define JSON_LOADS(str, err_ptr) json_loads((str), (err_ptr))
  47. #endif
  48. bool successful_connect = false;
  49. struct timeval nettime;
  50. struct data_buffer {
  51. void *buf;
  52. size_t len;
  53. };
  54. struct upload_buffer {
  55. const void *buf;
  56. size_t len;
  57. };
  58. struct header_info {
  59. char *lp_path;
  60. int rolltime;
  61. char *reason;
  62. bool hadrolltime;
  63. bool canroll;
  64. bool hadexpire;
  65. };
  66. struct tq_ent {
  67. void *data;
  68. struct list_head q_node;
  69. };
  70. static void databuf_free(struct data_buffer *db)
  71. {
  72. if (!db)
  73. return;
  74. free(db->buf);
  75. memset(db, 0, sizeof(*db));
  76. }
  77. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  78. void *user_data)
  79. {
  80. struct data_buffer *db = user_data;
  81. size_t len = size * nmemb;
  82. size_t oldlen, newlen;
  83. void *newmem;
  84. static const unsigned char zero = 0;
  85. oldlen = db->len;
  86. newlen = oldlen + len;
  87. newmem = realloc(db->buf, newlen + 1);
  88. if (!newmem)
  89. return 0;
  90. db->buf = newmem;
  91. db->len = newlen;
  92. memcpy(db->buf + oldlen, ptr, len);
  93. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  94. return len;
  95. }
  96. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  97. void *user_data)
  98. {
  99. struct upload_buffer *ub = user_data;
  100. unsigned int len = size * nmemb;
  101. if (len > ub->len)
  102. len = ub->len;
  103. if (len) {
  104. memcpy(ptr, ub->buf, len);
  105. ub->buf += len;
  106. ub->len -= len;
  107. }
  108. return len;
  109. }
  110. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  111. {
  112. struct header_info *hi = user_data;
  113. size_t remlen, slen, ptrlen = size * nmemb;
  114. char *rem, *val = NULL, *key = NULL;
  115. void *tmp;
  116. val = calloc(1, ptrlen);
  117. key = calloc(1, ptrlen);
  118. if (!key || !val)
  119. goto out;
  120. tmp = memchr(ptr, ':', ptrlen);
  121. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  122. goto out;
  123. slen = tmp - ptr;
  124. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  125. goto out;
  126. memcpy(key, ptr, slen); /* store & nul term key */
  127. key[slen] = 0;
  128. rem = ptr + slen + 1; /* trim value's leading whitespace */
  129. remlen = ptrlen - slen - 1;
  130. while ((remlen > 0) && (isspace(*rem))) {
  131. remlen--;
  132. rem++;
  133. }
  134. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  135. val[remlen] = 0;
  136. while ((*val) && (isspace(val[strlen(val) - 1])))
  137. val[strlen(val) - 1] = 0;
  138. if (!*val) /* skip blank value */
  139. goto out;
  140. if (opt_protocol)
  141. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  142. if (!strcasecmp("X-Roll-Ntime", key)) {
  143. hi->hadrolltime = true;
  144. if (!strncasecmp("N", val, 1))
  145. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  146. else {
  147. hi->canroll = true;
  148. /* Check to see if expire= is supported and if not, set
  149. * the rolltime to the default scantime */
  150. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  151. sscanf(val + 7, "%d", &hi->rolltime);
  152. hi->hadexpire = true;
  153. } else
  154. hi->rolltime = opt_scantime;
  155. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  156. }
  157. }
  158. if (!strcasecmp("X-Long-Polling", key)) {
  159. hi->lp_path = val; /* steal memory reference */
  160. val = NULL;
  161. }
  162. if (!strcasecmp("X-Reject-Reason", key)) {
  163. hi->reason = val; /* steal memory reference */
  164. val = NULL;
  165. }
  166. out:
  167. free(key);
  168. free(val);
  169. return ptrlen;
  170. }
  171. #ifdef CURL_HAS_SOCKOPT
  172. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  173. curlsocktype __maybe_unused purpose)
  174. {
  175. int tcp_keepidle = 120;
  176. int tcp_keepintvl = 120;
  177. #ifndef WIN32
  178. int keepalive = 1;
  179. int tcp_keepcnt = 5;
  180. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  181. return 1;
  182. # ifdef __linux
  183. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  184. return 1;
  185. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  186. return 1;
  187. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  188. return 1;
  189. # endif /* __linux */
  190. # ifdef __APPLE_CC__
  191. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  192. return 1;
  193. # endif /* __APPLE_CC__ */
  194. #else /* WIN32 */
  195. struct tcp_keepalive vals;
  196. vals.onoff = 1;
  197. vals.keepalivetime = tcp_keepidle * 1000;
  198. vals.keepaliveinterval = tcp_keepintvl * 1000;
  199. DWORD outputBytes;
  200. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  201. return 1;
  202. #endif /* WIN32 */
  203. return 0;
  204. }
  205. #endif
  206. static void last_nettime(struct timeval *last)
  207. {
  208. rd_lock(&netacc_lock);
  209. last->tv_sec = nettime.tv_sec;
  210. last->tv_usec = nettime.tv_usec;
  211. rd_unlock(&netacc_lock);
  212. }
  213. static void set_nettime(void)
  214. {
  215. wr_lock(&netacc_lock);
  216. gettimeofday(&nettime, NULL);
  217. wr_unlock(&netacc_lock);
  218. }
  219. json_t *json_rpc_call(CURL *curl, const char *url,
  220. const char *userpass, const char *rpc_req,
  221. bool probe, bool longpoll, int *rolltime,
  222. struct pool *pool, bool share)
  223. {
  224. long timeout = longpoll ? (60 * 60) : 60;
  225. struct data_buffer all_data = {NULL, 0};
  226. struct header_info hi = {NULL, 0, NULL, false, false, false};
  227. char len_hdr[64], user_agent_hdr[128];
  228. char curl_err_str[CURL_ERROR_SIZE];
  229. struct curl_slist *headers = NULL;
  230. struct upload_buffer upload_data;
  231. json_t *val, *err_val, *res_val;
  232. bool probing = false;
  233. json_error_t err;
  234. int rc;
  235. memset(&err, 0, sizeof(err));
  236. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  237. if (probe)
  238. probing = !pool->probed;
  239. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  240. #if 0 /* Disable curl debugging since it spews to stderr */
  241. if (opt_protocol)
  242. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  243. #endif
  244. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  245. curl_easy_setopt(curl, CURLOPT_URL, url);
  246. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  247. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  248. /* Shares are staggered already and delays in submission can be costly
  249. * so do not delay them */
  250. if (!opt_delaynet || share)
  251. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  252. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  253. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  254. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  255. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  256. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  257. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  258. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  259. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  260. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  261. if (pool->rpc_proxy) {
  262. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  263. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  264. } else if (opt_socks_proxy) {
  265. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  266. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  267. }
  268. if (userpass) {
  269. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  270. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  271. }
  272. #ifdef CURL_HAS_SOCKOPT
  273. if (longpoll)
  274. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  275. #endif
  276. curl_easy_setopt(curl, CURLOPT_POST, 1);
  277. if (opt_protocol)
  278. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  279. upload_data.buf = rpc_req;
  280. upload_data.len = strlen(rpc_req);
  281. sprintf(len_hdr, "Content-Length: %lu",
  282. (unsigned long) upload_data.len);
  283. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  284. headers = curl_slist_append(headers,
  285. "Content-type: application/json");
  286. headers = curl_slist_append(headers,
  287. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  288. if (longpoll)
  289. headers = curl_slist_append(headers,
  290. "X-Minimum-Wait: 0");
  291. if (likely(global_hashrate)) {
  292. char ghashrate[255];
  293. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  294. headers = curl_slist_append(headers, ghashrate);
  295. }
  296. headers = curl_slist_append(headers, len_hdr);
  297. headers = curl_slist_append(headers, user_agent_hdr);
  298. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  299. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  300. if (opt_delaynet) {
  301. /* Don't delay share submission, but still track the nettime */
  302. if (!share) {
  303. long long now_msecs, last_msecs;
  304. struct timeval now, last;
  305. gettimeofday(&now, NULL);
  306. last_nettime(&last);
  307. now_msecs = (long long)now.tv_sec * 1000;
  308. now_msecs += now.tv_usec / 1000;
  309. last_msecs = (long long)last.tv_sec * 1000;
  310. last_msecs += last.tv_usec / 1000;
  311. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  312. struct timespec rgtp;
  313. rgtp.tv_sec = 0;
  314. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  315. nanosleep(&rgtp, NULL);
  316. }
  317. }
  318. set_nettime();
  319. }
  320. rc = curl_easy_perform(curl);
  321. if (rc) {
  322. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  323. goto err_out;
  324. }
  325. if (!all_data.buf) {
  326. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  327. goto err_out;
  328. }
  329. if (probing) {
  330. pool->probed = true;
  331. /* If X-Long-Polling was found, activate long polling */
  332. if (hi.lp_path) {
  333. if (pool->hdr_path != NULL)
  334. free(pool->hdr_path);
  335. pool->hdr_path = hi.lp_path;
  336. } else
  337. pool->hdr_path = NULL;
  338. } else if (hi.lp_path) {
  339. free(hi.lp_path);
  340. hi.lp_path = NULL;
  341. }
  342. *rolltime = hi.rolltime;
  343. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  344. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  345. pool->cgminer_pool_stats.canroll = hi.canroll;
  346. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  347. val = JSON_LOADS(all_data.buf, &err);
  348. if (!val) {
  349. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  350. if (opt_protocol)
  351. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  352. goto err_out;
  353. }
  354. if (opt_protocol) {
  355. char *s = json_dumps(val, JSON_INDENT(3));
  356. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  357. free(s);
  358. }
  359. /* JSON-RPC valid response returns a non-null 'result',
  360. * and a null 'error'.
  361. */
  362. res_val = json_object_get(val, "result");
  363. err_val = json_object_get(val, "error");
  364. if (!res_val || json_is_null(res_val) ||
  365. (err_val && !json_is_null(err_val))) {
  366. char *s;
  367. if (err_val)
  368. s = json_dumps(err_val, JSON_INDENT(3));
  369. else
  370. s = strdup("(unknown reason)");
  371. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  372. free(s);
  373. goto err_out;
  374. }
  375. if (hi.reason) {
  376. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  377. free(hi.reason);
  378. hi.reason = NULL;
  379. }
  380. successful_connect = true;
  381. databuf_free(&all_data);
  382. curl_slist_free_all(headers);
  383. curl_easy_reset(curl);
  384. return val;
  385. err_out:
  386. databuf_free(&all_data);
  387. curl_slist_free_all(headers);
  388. curl_easy_reset(curl);
  389. if (!successful_connect)
  390. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  391. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  392. return NULL;
  393. }
  394. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  395. static struct {
  396. const char *name;
  397. curl_proxytype proxytype;
  398. } proxynames[] = {
  399. { "http:", CURLPROXY_HTTP },
  400. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 19) || (LIBCURL_VERSION_MINOR == 19 && LIBCURL_VERSION_PATCH >= 4)
  401. { "http0:", CURLPROXY_HTTP_1_0 },
  402. #endif
  403. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 15) || (LIBCURL_VERSION_MINOR == 15 && LIBCURL_VERSION_PATCH >= 2)
  404. { "socks4:", CURLPROXY_SOCKS4 },
  405. #endif
  406. { "socks5:", CURLPROXY_SOCKS5 },
  407. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR >= 18)
  408. { "socks4a:", CURLPROXY_SOCKS4A },
  409. { "socks5h:", CURLPROXY_SOCKS5_HOSTNAME },
  410. #endif
  411. };
  412. #endif
  413. const char *proxytype(curl_proxytype proxytype)
  414. {
  415. int i;
  416. for (i = 0; proxynames[i].name; i++)
  417. if (proxynames[i].proxytype == proxytype)
  418. return proxynames[i].name;
  419. return "invalid";
  420. }
  421. char *get_proxy(char *url, struct pool *pool)
  422. {
  423. pool->rpc_proxy = NULL;
  424. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  425. char *split;
  426. int plen, len, i;
  427. for (i = 0; proxynames[i].name; i++) {
  428. plen = strlen(proxynames[i].name);
  429. if (strncmp(url, proxynames[i].name, plen) == 0) {
  430. if (!(split = strchr(url, '|')))
  431. return url;
  432. *split = '\0';
  433. len = split - url;
  434. pool->rpc_proxy = malloc(1 + len - plen);
  435. if (!(pool->rpc_proxy))
  436. quit(1, "Failed to malloc rpc_proxy");
  437. strcpy(pool->rpc_proxy, url + plen);
  438. pool->rpc_proxytype = proxynames[i].proxytype;
  439. url = split + 1;
  440. break;
  441. }
  442. }
  443. #endif
  444. return url;
  445. }
  446. char *bin2hex(const unsigned char *p, size_t len)
  447. {
  448. char *s = malloc((len * 2) + 1);
  449. unsigned int i;
  450. if (!s)
  451. return NULL;
  452. for (i = 0; i < len; i++)
  453. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  454. return s;
  455. }
  456. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  457. {
  458. while (*hexstr && len) {
  459. char hex_byte[3];
  460. unsigned int v;
  461. if (!hexstr[1]) {
  462. applog(LOG_ERR, "hex2bin str truncated");
  463. return false;
  464. }
  465. hex_byte[0] = hexstr[0];
  466. hex_byte[1] = hexstr[1];
  467. hex_byte[2] = 0;
  468. if (sscanf(hex_byte, "%x", &v) != 1) {
  469. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  470. return false;
  471. }
  472. *p = (unsigned char) v;
  473. p++;
  474. hexstr += 2;
  475. len--;
  476. }
  477. return (len == 0 && *hexstr == 0) ? true : false;
  478. }
  479. bool fulltest(const unsigned char *hash, const unsigned char *target)
  480. {
  481. unsigned char hash_swap[32], target_swap[32];
  482. uint32_t *hash32 = (uint32_t *) hash_swap;
  483. uint32_t *target32 = (uint32_t *) target_swap;
  484. char *hash_str, *target_str;
  485. bool rc = true;
  486. int i;
  487. swap256(hash_swap, hash);
  488. swap256(target_swap, target);
  489. for (i = 0; i < 32/4; i++) {
  490. uint32_t h32tmp = swab32(hash32[i]);
  491. uint32_t t32tmp = target32[i];
  492. target32[i] = swab32(target32[i]); /* for printing */
  493. if (h32tmp > t32tmp) {
  494. rc = false;
  495. break;
  496. }
  497. if (h32tmp < t32tmp) {
  498. rc = true;
  499. break;
  500. }
  501. }
  502. if (opt_debug) {
  503. hash_str = bin2hex(hash_swap, 32);
  504. target_str = bin2hex(target_swap, 32);
  505. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  506. hash_str,
  507. target_str,
  508. rc ? "YES (hash < target)" :
  509. "no (false positive; hash > target)");
  510. free(hash_str);
  511. free(target_str);
  512. }
  513. return rc;
  514. }
  515. struct thread_q *tq_new(void)
  516. {
  517. struct thread_q *tq;
  518. tq = calloc(1, sizeof(*tq));
  519. if (!tq)
  520. return NULL;
  521. INIT_LIST_HEAD(&tq->q);
  522. pthread_mutex_init(&tq->mutex, NULL);
  523. pthread_cond_init(&tq->cond, NULL);
  524. return tq;
  525. }
  526. void tq_free(struct thread_q *tq)
  527. {
  528. struct tq_ent *ent, *iter;
  529. if (!tq)
  530. return;
  531. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  532. list_del(&ent->q_node);
  533. free(ent);
  534. }
  535. pthread_cond_destroy(&tq->cond);
  536. pthread_mutex_destroy(&tq->mutex);
  537. memset(tq, 0, sizeof(*tq)); /* poison */
  538. free(tq);
  539. }
  540. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  541. {
  542. mutex_lock(&tq->mutex);
  543. tq->frozen = frozen;
  544. pthread_cond_signal(&tq->cond);
  545. mutex_unlock(&tq->mutex);
  546. }
  547. void tq_freeze(struct thread_q *tq)
  548. {
  549. tq_freezethaw(tq, true);
  550. }
  551. void tq_thaw(struct thread_q *tq)
  552. {
  553. tq_freezethaw(tq, false);
  554. }
  555. bool tq_push(struct thread_q *tq, void *data)
  556. {
  557. struct tq_ent *ent;
  558. bool rc = true;
  559. ent = calloc(1, sizeof(*ent));
  560. if (!ent)
  561. return false;
  562. ent->data = data;
  563. INIT_LIST_HEAD(&ent->q_node);
  564. mutex_lock(&tq->mutex);
  565. if (!tq->frozen) {
  566. list_add_tail(&ent->q_node, &tq->q);
  567. } else {
  568. free(ent);
  569. rc = false;
  570. }
  571. pthread_cond_signal(&tq->cond);
  572. mutex_unlock(&tq->mutex);
  573. return rc;
  574. }
  575. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  576. {
  577. struct tq_ent *ent;
  578. void *rval = NULL;
  579. int rc;
  580. mutex_lock(&tq->mutex);
  581. if (!list_empty(&tq->q))
  582. goto pop;
  583. if (abstime)
  584. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  585. else
  586. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  587. if (rc)
  588. goto out;
  589. if (list_empty(&tq->q))
  590. goto out;
  591. pop:
  592. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  593. rval = ent->data;
  594. list_del(&ent->q_node);
  595. free(ent);
  596. out:
  597. mutex_unlock(&tq->mutex);
  598. return rval;
  599. }
  600. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  601. {
  602. return pthread_create(&thr->pth, attr, start, arg);
  603. }
  604. void thr_info_freeze(struct thr_info *thr)
  605. {
  606. struct tq_ent *ent, *iter;
  607. struct thread_q *tq;
  608. if (!thr)
  609. return;
  610. tq = thr->q;
  611. if (!tq)
  612. return;
  613. mutex_lock(&tq->mutex);
  614. tq->frozen = true;
  615. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  616. list_del(&ent->q_node);
  617. free(ent);
  618. }
  619. mutex_unlock(&tq->mutex);
  620. }
  621. void thr_info_cancel(struct thr_info *thr)
  622. {
  623. if (!thr)
  624. return;
  625. if (PTH(thr) != 0L) {
  626. pthread_cancel(thr->pth);
  627. PTH(thr) = 0L;
  628. }
  629. }
  630. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  631. * on SMP machines */
  632. void nmsleep(unsigned int msecs)
  633. {
  634. struct timespec twait, tleft;
  635. int ret;
  636. ldiv_t d;
  637. d = ldiv(msecs, 1000);
  638. tleft.tv_sec = d.quot;
  639. tleft.tv_nsec = d.rem * 1000000;
  640. do {
  641. twait.tv_sec = tleft.tv_sec;
  642. twait.tv_nsec = tleft.tv_nsec;
  643. ret = nanosleep(&twait, &tleft);
  644. } while (ret == -1 && errno == EINTR);
  645. }
  646. void rename_thr(const char* name) {
  647. #if defined(PR_SET_NAME)
  648. // Only the first 15 characters are used (16 - NUL terminator)
  649. prctl(PR_SET_NAME, name, 0, 0, 0);
  650. #elif defined(__APPLE__)
  651. pthread_setname_np(name);
  652. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  653. pthread_set_name_np(pthread_self(), name);
  654. #else
  655. // Prevent warnings for unused parameters...
  656. (void)name;
  657. #endif
  658. }