util.c 17 KB

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