util.c 16 KB

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