util.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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. } else if (opt_socks_proxy) {
  264. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  265. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  266. }
  267. if (userpass) {
  268. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  269. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  270. }
  271. #ifdef CURL_HAS_SOCKOPT
  272. if (longpoll)
  273. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  274. #endif
  275. curl_easy_setopt(curl, CURLOPT_POST, 1);
  276. if (opt_protocol)
  277. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  278. upload_data.buf = rpc_req;
  279. upload_data.len = strlen(rpc_req);
  280. sprintf(len_hdr, "Content-Length: %lu",
  281. (unsigned long) upload_data.len);
  282. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  283. headers = curl_slist_append(headers,
  284. "Content-type: application/json");
  285. headers = curl_slist_append(headers,
  286. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  287. if (longpoll)
  288. headers = curl_slist_append(headers,
  289. "X-Minimum-Wait: 0");
  290. if (likely(global_hashrate)) {
  291. char ghashrate[255];
  292. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  293. headers = curl_slist_append(headers, ghashrate);
  294. }
  295. headers = curl_slist_append(headers, len_hdr);
  296. headers = curl_slist_append(headers, user_agent_hdr);
  297. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  298. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  299. if (opt_delaynet) {
  300. /* Don't delay share submission, but still track the nettime */
  301. if (!share) {
  302. long long now_msecs, last_msecs;
  303. struct timeval now, last;
  304. gettimeofday(&now, NULL);
  305. last_nettime(&last);
  306. now_msecs = (long long)now.tv_sec * 1000;
  307. now_msecs += now.tv_usec / 1000;
  308. last_msecs = (long long)last.tv_sec * 1000;
  309. last_msecs += last.tv_usec / 1000;
  310. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  311. struct timespec rgtp;
  312. rgtp.tv_sec = 0;
  313. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  314. nanosleep(&rgtp, NULL);
  315. }
  316. }
  317. set_nettime();
  318. }
  319. rc = curl_easy_perform(curl);
  320. if (rc) {
  321. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  322. goto err_out;
  323. }
  324. if (!all_data.buf) {
  325. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  326. goto err_out;
  327. }
  328. if (probing) {
  329. pool->probed = true;
  330. /* If X-Long-Polling was found, activate long polling */
  331. if (hi.lp_path) {
  332. if (pool->hdr_path != NULL)
  333. free(pool->hdr_path);
  334. pool->hdr_path = hi.lp_path;
  335. } else
  336. pool->hdr_path = NULL;
  337. } else if (hi.lp_path) {
  338. free(hi.lp_path);
  339. hi.lp_path = NULL;
  340. }
  341. *rolltime = hi.rolltime;
  342. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  343. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  344. pool->cgminer_pool_stats.canroll = hi.canroll;
  345. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  346. val = JSON_LOADS(all_data.buf, &err);
  347. if (!val) {
  348. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  349. if (opt_protocol)
  350. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  351. goto err_out;
  352. }
  353. if (opt_protocol) {
  354. char *s = json_dumps(val, JSON_INDENT(3));
  355. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  356. free(s);
  357. }
  358. /* JSON-RPC valid response returns a non-null 'result',
  359. * and a null 'error'.
  360. */
  361. res_val = json_object_get(val, "result");
  362. err_val = json_object_get(val, "error");
  363. if (!res_val || json_is_null(res_val) ||
  364. (err_val && !json_is_null(err_val))) {
  365. char *s;
  366. if (err_val)
  367. s = json_dumps(err_val, JSON_INDENT(3));
  368. else
  369. s = strdup("(unknown reason)");
  370. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  371. free(s);
  372. goto err_out;
  373. }
  374. if (hi.reason) {
  375. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  376. free(hi.reason);
  377. hi.reason = NULL;
  378. }
  379. successful_connect = true;
  380. databuf_free(&all_data);
  381. curl_slist_free_all(headers);
  382. curl_easy_reset(curl);
  383. return val;
  384. err_out:
  385. databuf_free(&all_data);
  386. curl_slist_free_all(headers);
  387. curl_easy_reset(curl);
  388. if (!successful_connect)
  389. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  390. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  391. return NULL;
  392. }
  393. bool our_curl_supports_proxy_uris()
  394. {
  395. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  396. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  397. }
  398. char *bin2hex(const unsigned char *p, size_t len)
  399. {
  400. char *s = malloc((len * 2) + 1);
  401. unsigned int i;
  402. if (!s)
  403. return NULL;
  404. for (i = 0; i < len; i++)
  405. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  406. return s;
  407. }
  408. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  409. {
  410. while (*hexstr && len) {
  411. char hex_byte[3];
  412. unsigned int v;
  413. if (!hexstr[1]) {
  414. applog(LOG_ERR, "hex2bin str truncated");
  415. return false;
  416. }
  417. hex_byte[0] = hexstr[0];
  418. hex_byte[1] = hexstr[1];
  419. hex_byte[2] = 0;
  420. if (sscanf(hex_byte, "%x", &v) != 1) {
  421. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  422. return false;
  423. }
  424. *p = (unsigned char) v;
  425. p++;
  426. hexstr += 2;
  427. len--;
  428. }
  429. return (len == 0 && *hexstr == 0) ? true : false;
  430. }
  431. bool fulltest(const unsigned char *hash, const unsigned char *target)
  432. {
  433. unsigned char hash_swap[32], target_swap[32];
  434. uint32_t *hash32 = (uint32_t *) hash_swap;
  435. uint32_t *target32 = (uint32_t *) target_swap;
  436. char *hash_str, *target_str;
  437. bool rc = true;
  438. int i;
  439. swap256(hash_swap, hash);
  440. swap256(target_swap, target);
  441. for (i = 0; i < 32/4; i++) {
  442. uint32_t h32tmp = swab32(hash32[i]);
  443. uint32_t t32tmp = target32[i];
  444. target32[i] = swab32(target32[i]); /* for printing */
  445. if (h32tmp > t32tmp) {
  446. rc = false;
  447. break;
  448. }
  449. if (h32tmp < t32tmp) {
  450. rc = true;
  451. break;
  452. }
  453. }
  454. if (opt_debug) {
  455. hash_str = bin2hex(hash_swap, 32);
  456. target_str = bin2hex(target_swap, 32);
  457. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  458. hash_str,
  459. target_str,
  460. rc ? "YES (hash < target)" :
  461. "no (false positive; hash > target)");
  462. free(hash_str);
  463. free(target_str);
  464. }
  465. return rc;
  466. }
  467. struct thread_q *tq_new(void)
  468. {
  469. struct thread_q *tq;
  470. tq = calloc(1, sizeof(*tq));
  471. if (!tq)
  472. return NULL;
  473. INIT_LIST_HEAD(&tq->q);
  474. pthread_mutex_init(&tq->mutex, NULL);
  475. pthread_cond_init(&tq->cond, NULL);
  476. return tq;
  477. }
  478. void tq_free(struct thread_q *tq)
  479. {
  480. struct tq_ent *ent, *iter;
  481. if (!tq)
  482. return;
  483. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  484. list_del(&ent->q_node);
  485. free(ent);
  486. }
  487. pthread_cond_destroy(&tq->cond);
  488. pthread_mutex_destroy(&tq->mutex);
  489. memset(tq, 0, sizeof(*tq)); /* poison */
  490. free(tq);
  491. }
  492. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  493. {
  494. mutex_lock(&tq->mutex);
  495. tq->frozen = frozen;
  496. pthread_cond_signal(&tq->cond);
  497. mutex_unlock(&tq->mutex);
  498. }
  499. void tq_freeze(struct thread_q *tq)
  500. {
  501. tq_freezethaw(tq, true);
  502. }
  503. void tq_thaw(struct thread_q *tq)
  504. {
  505. tq_freezethaw(tq, false);
  506. }
  507. bool tq_push(struct thread_q *tq, void *data)
  508. {
  509. struct tq_ent *ent;
  510. bool rc = true;
  511. ent = calloc(1, sizeof(*ent));
  512. if (!ent)
  513. return false;
  514. ent->data = data;
  515. INIT_LIST_HEAD(&ent->q_node);
  516. mutex_lock(&tq->mutex);
  517. if (!tq->frozen) {
  518. list_add_tail(&ent->q_node, &tq->q);
  519. } else {
  520. free(ent);
  521. rc = false;
  522. }
  523. pthread_cond_signal(&tq->cond);
  524. mutex_unlock(&tq->mutex);
  525. return rc;
  526. }
  527. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  528. {
  529. struct tq_ent *ent;
  530. void *rval = NULL;
  531. int rc;
  532. mutex_lock(&tq->mutex);
  533. if (!list_empty(&tq->q))
  534. goto pop;
  535. if (abstime)
  536. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  537. else
  538. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  539. if (rc)
  540. goto out;
  541. if (list_empty(&tq->q))
  542. goto out;
  543. pop:
  544. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  545. rval = ent->data;
  546. list_del(&ent->q_node);
  547. free(ent);
  548. out:
  549. mutex_unlock(&tq->mutex);
  550. return rval;
  551. }
  552. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  553. {
  554. return pthread_create(&thr->pth, attr, start, arg);
  555. }
  556. void thr_info_freeze(struct thr_info *thr)
  557. {
  558. struct tq_ent *ent, *iter;
  559. struct thread_q *tq;
  560. if (!thr)
  561. return;
  562. tq = thr->q;
  563. if (!tq)
  564. return;
  565. mutex_lock(&tq->mutex);
  566. tq->frozen = true;
  567. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  568. list_del(&ent->q_node);
  569. free(ent);
  570. }
  571. mutex_unlock(&tq->mutex);
  572. }
  573. void thr_info_cancel(struct thr_info *thr)
  574. {
  575. if (!thr)
  576. return;
  577. if (PTH(thr) != 0L) {
  578. pthread_cancel(thr->pth);
  579. PTH(thr) = 0L;
  580. }
  581. }
  582. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  583. * on SMP machines */
  584. void nmsleep(unsigned int msecs)
  585. {
  586. struct timespec twait, tleft;
  587. int ret;
  588. ldiv_t d;
  589. d = ldiv(msecs, 1000);
  590. tleft.tv_sec = d.quot;
  591. tleft.tv_nsec = d.rem * 1000000;
  592. do {
  593. twait.tv_sec = tleft.tv_sec;
  594. twait.tv_nsec = tleft.tv_nsec;
  595. ret = nanosleep(&twait, &tleft);
  596. } while (ret == -1 && errno == EINTR);
  597. }
  598. void rename_thr(const char* name) {
  599. #if defined(PR_SET_NAME)
  600. // Only the first 15 characters are used (16 - NUL terminator)
  601. prctl(PR_SET_NAME, name, 0, 0, 0);
  602. #elif defined(__APPLE__)
  603. pthread_setname_np(name);
  604. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  605. pthread_set_name_np(pthread_self(), name);
  606. #else
  607. // Prevent warnings for unused parameters...
  608. (void)name;
  609. #endif
  610. }