util.c 18 KB

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