util.c 16 KB

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