cpuworker.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /* Copyright (c) 2003-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file cpuworker.c
  7. * \brief Uses the workqueue/threadpool code to farm CPU-intensive activities
  8. * out to subprocesses.
  9. *
  10. * The multithreading backend for this module is in workqueue.c; this module
  11. * specializes workqueue.c.
  12. *
  13. * Right now, we use this infrastructure
  14. * <ul><li>for processing onionskins in onion.c
  15. * <li>for compressing consensuses in consdiffmgr.c,
  16. * <li>and for calculating diffs and compressing them in consdiffmgr.c.
  17. * </ul>
  18. **/
  19. #include "core/or/or.h"
  20. #include "core/or/channel.h"
  21. #include "core/or/circuitbuild.h"
  22. #include "core/or/circuitlist.h"
  23. #include "core/or/connection_or.h"
  24. #include "app/config/config.h"
  25. #include "core/mainloop/cpuworker.h"
  26. #include "lib/crypt_ops/crypto_rand.h"
  27. #include "lib/crypt_ops/crypto_util.h"
  28. #include "core/or/onion.h"
  29. #include "feature/relay/onion_queue.h"
  30. #include "feature/stats/rephist.h"
  31. #include "feature/relay/router.h"
  32. #include "lib/evloop/workqueue.h"
  33. #include "core/crypto/onion_crypto.h"
  34. #include "core/or/or_circuit_st.h"
  35. #include "lib/intmath/weakrng.h"
  36. static void queue_pending_tasks(void);
  37. typedef struct worker_state_s {
  38. int generation;
  39. server_onion_keys_t *onion_keys;
  40. } worker_state_t;
  41. static void *
  42. worker_state_new(void *arg)
  43. {
  44. worker_state_t *ws;
  45. (void)arg;
  46. ws = tor_malloc_zero(sizeof(worker_state_t));
  47. ws->onion_keys = server_onion_keys_new();
  48. return ws;
  49. }
  50. #define worker_state_free(ws) \
  51. FREE_AND_NULL(worker_state_t, worker_state_free_, (ws))
  52. static void
  53. worker_state_free_(worker_state_t *ws)
  54. {
  55. if (!ws)
  56. return;
  57. server_onion_keys_free(ws->onion_keys);
  58. tor_free(ws);
  59. }
  60. static void
  61. worker_state_free_void(void *arg)
  62. {
  63. worker_state_free_(arg);
  64. }
  65. static replyqueue_t *replyqueue = NULL;
  66. static threadpool_t *threadpool = NULL;
  67. static tor_weak_rng_t request_sample_rng = TOR_WEAK_RNG_INIT;
  68. static int total_pending_tasks = 0;
  69. static int max_pending_tasks = 128;
  70. /** Initialize the cpuworker subsystem. It is OK to call this more than once
  71. * during Tor's lifetime.
  72. */
  73. void
  74. cpu_init(void)
  75. {
  76. if (!replyqueue) {
  77. replyqueue = replyqueue_new(0);
  78. }
  79. if (!threadpool) {
  80. /*
  81. In our threadpool implementation, half the threads are permissive and
  82. half are strict (when it comes to running lower-priority tasks). So we
  83. always make sure we have at least two threads, so that there will be at
  84. least one thread of each kind.
  85. */
  86. const int n_threads = get_num_cpus(get_options()) + 1;
  87. threadpool = threadpool_new(n_threads,
  88. replyqueue,
  89. worker_state_new,
  90. worker_state_free_void,
  91. NULL);
  92. int r = threadpool_register_reply_event(threadpool, NULL);
  93. tor_assert(r == 0);
  94. }
  95. /* Total voodoo. Can we make this more sensible? */
  96. max_pending_tasks = get_num_cpus(get_options()) * 64;
  97. crypto_seed_weak_rng(&request_sample_rng);
  98. }
  99. /** Magic numbers to make sure our cpuworker_requests don't grow any
  100. * mis-framing bugs. */
  101. #define CPUWORKER_REQUEST_MAGIC 0xda4afeed
  102. #define CPUWORKER_REPLY_MAGIC 0x5eedf00d
  103. /** A request sent to a cpuworker. */
  104. typedef struct cpuworker_request_t {
  105. /** Magic number; must be CPUWORKER_REQUEST_MAGIC. */
  106. uint32_t magic;
  107. /** Flag: Are we timing this request? */
  108. unsigned timed : 1;
  109. /** If we're timing this request, when was it sent to the cpuworker? */
  110. struct timeval started_at;
  111. /** A create cell for the cpuworker to process. */
  112. create_cell_t create_cell;
  113. /* Turn the above into a tagged union if needed. */
  114. } cpuworker_request_t;
  115. /** A reply sent by a cpuworker. */
  116. typedef struct cpuworker_reply_t {
  117. /** Magic number; must be CPUWORKER_REPLY_MAGIC. */
  118. uint32_t magic;
  119. /** True iff we got a successful request. */
  120. uint8_t success;
  121. /** Are we timing this request? */
  122. unsigned int timed : 1;
  123. /** What handshake type was the request? (Used for timing) */
  124. uint16_t handshake_type;
  125. /** When did we send the request to the cpuworker? */
  126. struct timeval started_at;
  127. /** Once the cpuworker received the request, how many microseconds did it
  128. * take? (This shouldn't overflow; 4 billion micoseconds is over an hour,
  129. * and we'll never have an onion handshake that takes so long.) */
  130. uint32_t n_usec;
  131. /** Output of processing a create cell
  132. *
  133. * @{
  134. */
  135. /** The created cell to send back. */
  136. created_cell_t created_cell;
  137. /** The keys to use on this circuit. */
  138. uint8_t keys[CPATH_KEY_MATERIAL_LEN];
  139. /** Input to use for authenticating introduce1 cells. */
  140. uint8_t rend_auth_material[DIGEST_LEN];
  141. } cpuworker_reply_t;
  142. typedef struct cpuworker_job_u {
  143. or_circuit_t *circ;
  144. union {
  145. cpuworker_request_t request;
  146. cpuworker_reply_t reply;
  147. } u;
  148. } cpuworker_job_t;
  149. static workqueue_reply_t
  150. update_state_threadfn(void *state_, void *work_)
  151. {
  152. worker_state_t *state = state_;
  153. worker_state_t *update = work_;
  154. server_onion_keys_free(state->onion_keys);
  155. state->onion_keys = update->onion_keys;
  156. update->onion_keys = NULL;
  157. worker_state_free(update);
  158. ++state->generation;
  159. return WQ_RPL_REPLY;
  160. }
  161. /** Called when the onion key has changed so update all CPU worker(s) with
  162. * new function pointers with which a new state will be generated.
  163. */
  164. void
  165. cpuworkers_rotate_keyinfo(void)
  166. {
  167. if (!threadpool) {
  168. /* If we're a client, then we won't have cpuworkers, and we won't need
  169. * to tell them to rotate their state.
  170. */
  171. return;
  172. }
  173. if (threadpool_queue_update(threadpool,
  174. worker_state_new,
  175. update_state_threadfn,
  176. worker_state_free_void,
  177. NULL)) {
  178. log_warn(LD_OR, "Failed to queue key update for worker threads.");
  179. }
  180. }
  181. /** Indexed by handshake type: how many onionskins have we processed and
  182. * counted of that type? */
  183. static uint64_t onionskins_n_processed[MAX_ONION_HANDSHAKE_TYPE+1];
  184. /** Indexed by handshake type, corresponding to the onionskins counted in
  185. * onionskins_n_processed: how many microseconds have we spent in cpuworkers
  186. * processing that kind of onionskin? */
  187. static uint64_t onionskins_usec_internal[MAX_ONION_HANDSHAKE_TYPE+1];
  188. /** Indexed by handshake type, corresponding to onionskins counted in
  189. * onionskins_n_processed: how many microseconds have we spent waiting for
  190. * cpuworkers to give us answers for that kind of onionskin?
  191. */
  192. static uint64_t onionskins_usec_roundtrip[MAX_ONION_HANDSHAKE_TYPE+1];
  193. /** If any onionskin takes longer than this, we clip them to this
  194. * time. (microseconds) */
  195. #define MAX_BELIEVABLE_ONIONSKIN_DELAY (2*1000*1000)
  196. /** Return true iff we'd like to measure a handshake of type
  197. * <b>onionskin_type</b>. Call only from the main thread. */
  198. static int
  199. should_time_request(uint16_t onionskin_type)
  200. {
  201. /* If we've never heard of this type, we shouldn't even be here. */
  202. if (onionskin_type > MAX_ONION_HANDSHAKE_TYPE)
  203. return 0;
  204. /* Measure the first N handshakes of each type, to ensure we have a
  205. * sample */
  206. if (onionskins_n_processed[onionskin_type] < 4096)
  207. return 1;
  208. /** Otherwise, measure with P=1/128. We avoid doing this for every
  209. * handshake, since the measurement itself can take a little time. */
  210. return tor_weak_random_one_in_n(&request_sample_rng, 128);
  211. }
  212. /** Return an estimate of how many microseconds we will need for a single
  213. * cpuworker to process <b>n_requests</b> onionskins of type
  214. * <b>onionskin_type</b>. */
  215. uint64_t
  216. estimated_usec_for_onionskins(uint32_t n_requests, uint16_t onionskin_type)
  217. {
  218. if (onionskin_type > MAX_ONION_HANDSHAKE_TYPE) /* should be impossible */
  219. return 1000 * (uint64_t)n_requests;
  220. if (PREDICT_UNLIKELY(onionskins_n_processed[onionskin_type] < 100)) {
  221. /* Until we have 100 data points, just asssume everything takes 1 msec. */
  222. return 1000 * (uint64_t)n_requests;
  223. } else {
  224. /* This can't overflow: we'll never have more than 500000 onionskins
  225. * measured in onionskin_usec_internal, and they won't take anything near
  226. * 1 sec each, and we won't have anything like 1 million queued
  227. * onionskins. But that's 5e5 * 1e6 * 1e6, which is still less than
  228. * UINT64_MAX. */
  229. return (onionskins_usec_internal[onionskin_type] * n_requests) /
  230. onionskins_n_processed[onionskin_type];
  231. }
  232. }
  233. /** Compute the absolute and relative overhead of using the cpuworker
  234. * framework for onionskins of type <b>onionskin_type</b>.*/
  235. static int
  236. get_overhead_for_onionskins(uint32_t *usec_out, double *frac_out,
  237. uint16_t onionskin_type)
  238. {
  239. uint64_t overhead;
  240. *usec_out = 0;
  241. *frac_out = 0.0;
  242. if (onionskin_type > MAX_ONION_HANDSHAKE_TYPE) /* should be impossible */
  243. return -1;
  244. if (onionskins_n_processed[onionskin_type] == 0 ||
  245. onionskins_usec_internal[onionskin_type] == 0 ||
  246. onionskins_usec_roundtrip[onionskin_type] == 0)
  247. return -1;
  248. overhead = onionskins_usec_roundtrip[onionskin_type] -
  249. onionskins_usec_internal[onionskin_type];
  250. *usec_out = (uint32_t)(overhead / onionskins_n_processed[onionskin_type]);
  251. *frac_out = ((double)overhead) / onionskins_usec_internal[onionskin_type];
  252. return 0;
  253. }
  254. /** If we've measured overhead for onionskins of type <b>onionskin_type</b>,
  255. * log it. */
  256. void
  257. cpuworker_log_onionskin_overhead(int severity, int onionskin_type,
  258. const char *onionskin_type_name)
  259. {
  260. uint32_t overhead;
  261. double relative_overhead;
  262. int r;
  263. r = get_overhead_for_onionskins(&overhead, &relative_overhead,
  264. onionskin_type);
  265. if (!overhead || r<0)
  266. return;
  267. log_fn(severity, LD_OR,
  268. "%s onionskins have averaged %u usec overhead (%.2f%%) in "
  269. "cpuworker code ",
  270. onionskin_type_name, (unsigned)overhead, relative_overhead*100);
  271. }
  272. /** Handle a reply from the worker threads. */
  273. static void
  274. cpuworker_onion_handshake_replyfn(void *work_)
  275. {
  276. cpuworker_job_t *job = work_;
  277. cpuworker_reply_t rpl;
  278. or_circuit_t *circ = NULL;
  279. tor_assert(total_pending_tasks > 0);
  280. --total_pending_tasks;
  281. /* Could avoid this, but doesn't matter. */
  282. memcpy(&rpl, &job->u.reply, sizeof(rpl));
  283. tor_assert(rpl.magic == CPUWORKER_REPLY_MAGIC);
  284. if (rpl.timed && rpl.success &&
  285. rpl.handshake_type <= MAX_ONION_HANDSHAKE_TYPE) {
  286. /* Time how long this request took. The handshake_type check should be
  287. needless, but let's leave it in to be safe. */
  288. struct timeval tv_end, tv_diff;
  289. int64_t usec_roundtrip;
  290. tor_gettimeofday(&tv_end);
  291. timersub(&tv_end, &rpl.started_at, &tv_diff);
  292. usec_roundtrip = ((int64_t)tv_diff.tv_sec)*1000000 + tv_diff.tv_usec;
  293. if (usec_roundtrip >= 0 &&
  294. usec_roundtrip < MAX_BELIEVABLE_ONIONSKIN_DELAY) {
  295. ++onionskins_n_processed[rpl.handshake_type];
  296. onionskins_usec_internal[rpl.handshake_type] += rpl.n_usec;
  297. onionskins_usec_roundtrip[rpl.handshake_type] += usec_roundtrip;
  298. if (onionskins_n_processed[rpl.handshake_type] >= 500000) {
  299. /* Scale down every 500000 handshakes. On a busy server, that's
  300. * less impressive than it sounds. */
  301. onionskins_n_processed[rpl.handshake_type] /= 2;
  302. onionskins_usec_internal[rpl.handshake_type] /= 2;
  303. onionskins_usec_roundtrip[rpl.handshake_type] /= 2;
  304. }
  305. }
  306. }
  307. circ = job->circ;
  308. log_debug(LD_OR,
  309. "Unpacking cpuworker reply %p, circ=%p, success=%d",
  310. job, circ, rpl.success);
  311. if (circ->base_.magic == DEAD_CIRCUIT_MAGIC) {
  312. /* The circuit was supposed to get freed while the reply was
  313. * pending. Instead, it got left for us to free so that we wouldn't freak
  314. * out when the job->circ field wound up pointing to nothing. */
  315. log_debug(LD_OR, "Circuit died while reply was pending. Freeing memory.");
  316. circ->base_.magic = 0;
  317. tor_free(circ);
  318. goto done_processing;
  319. }
  320. circ->workqueue_entry = NULL;
  321. if (TO_CIRCUIT(circ)->marked_for_close) {
  322. /* We already marked this circuit; we can't call it open. */
  323. log_debug(LD_OR,"circuit is already marked.");
  324. goto done_processing;
  325. }
  326. if (rpl.success == 0) {
  327. log_debug(LD_OR,
  328. "decoding onionskin failed. "
  329. "(Old key or bad software.) Closing.");
  330. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  331. goto done_processing;
  332. }
  333. if (onionskin_answer(circ,
  334. &rpl.created_cell,
  335. (const char*)rpl.keys, sizeof(rpl.keys),
  336. rpl.rend_auth_material) < 0) {
  337. log_warn(LD_OR,"onionskin_answer failed. Closing.");
  338. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  339. goto done_processing;
  340. }
  341. log_debug(LD_OR,"onionskin_answer succeeded. Yay.");
  342. done_processing:
  343. memwipe(&rpl, 0, sizeof(rpl));
  344. memwipe(job, 0, sizeof(*job));
  345. tor_free(job);
  346. queue_pending_tasks();
  347. }
  348. /** Implementation function for onion handshake requests. */
  349. static workqueue_reply_t
  350. cpuworker_onion_handshake_threadfn(void *state_, void *work_)
  351. {
  352. worker_state_t *state = state_;
  353. cpuworker_job_t *job = work_;
  354. /* variables for onion processing */
  355. server_onion_keys_t *onion_keys = state->onion_keys;
  356. cpuworker_request_t req;
  357. cpuworker_reply_t rpl;
  358. memcpy(&req, &job->u.request, sizeof(req));
  359. tor_assert(req.magic == CPUWORKER_REQUEST_MAGIC);
  360. memset(&rpl, 0, sizeof(rpl));
  361. const create_cell_t *cc = &req.create_cell;
  362. created_cell_t *cell_out = &rpl.created_cell;
  363. struct timeval tv_start = {0,0}, tv_end;
  364. int n;
  365. rpl.timed = req.timed;
  366. rpl.started_at = req.started_at;
  367. rpl.handshake_type = cc->handshake_type;
  368. if (req.timed)
  369. tor_gettimeofday(&tv_start);
  370. n = onion_skin_server_handshake(cc->handshake_type,
  371. cc->onionskin, cc->handshake_len,
  372. onion_keys,
  373. cell_out->reply,
  374. rpl.keys, CPATH_KEY_MATERIAL_LEN,
  375. rpl.rend_auth_material);
  376. if (n < 0) {
  377. /* failure */
  378. log_debug(LD_OR,"onion_skin_server_handshake failed.");
  379. memset(&rpl, 0, sizeof(rpl));
  380. rpl.success = 0;
  381. } else {
  382. /* success */
  383. log_debug(LD_OR,"onion_skin_server_handshake succeeded.");
  384. cell_out->handshake_len = n;
  385. switch (cc->cell_type) {
  386. case CELL_CREATE:
  387. cell_out->cell_type = CELL_CREATED; break;
  388. case CELL_CREATE2:
  389. cell_out->cell_type = CELL_CREATED2; break;
  390. case CELL_CREATE_FAST:
  391. cell_out->cell_type = CELL_CREATED_FAST; break;
  392. default:
  393. tor_assert(0);
  394. return WQ_RPL_SHUTDOWN;
  395. }
  396. rpl.success = 1;
  397. }
  398. rpl.magic = CPUWORKER_REPLY_MAGIC;
  399. if (req.timed) {
  400. struct timeval tv_diff;
  401. int64_t usec;
  402. tor_gettimeofday(&tv_end);
  403. timersub(&tv_end, &tv_start, &tv_diff);
  404. usec = ((int64_t)tv_diff.tv_sec)*1000000 + tv_diff.tv_usec;
  405. if (usec < 0 || usec > MAX_BELIEVABLE_ONIONSKIN_DELAY)
  406. rpl.n_usec = MAX_BELIEVABLE_ONIONSKIN_DELAY;
  407. else
  408. rpl.n_usec = (uint32_t) usec;
  409. }
  410. memcpy(&job->u.reply, &rpl, sizeof(rpl));
  411. memwipe(&req, 0, sizeof(req));
  412. memwipe(&rpl, 0, sizeof(req));
  413. return WQ_RPL_REPLY;
  414. }
  415. /** Take pending tasks from the queue and assign them to cpuworkers. */
  416. static void
  417. queue_pending_tasks(void)
  418. {
  419. or_circuit_t *circ;
  420. create_cell_t *onionskin = NULL;
  421. while (total_pending_tasks < max_pending_tasks) {
  422. circ = onion_next_task(&onionskin);
  423. if (!circ)
  424. return;
  425. if (assign_onionskin_to_cpuworker(circ, onionskin) < 0)
  426. log_info(LD_OR,"assign_to_cpuworker failed. Ignoring.");
  427. }
  428. }
  429. /** DOCDOC */
  430. MOCK_IMPL(workqueue_entry_t *,
  431. cpuworker_queue_work,(workqueue_priority_t priority,
  432. workqueue_reply_t (*fn)(void *, void *),
  433. void (*reply_fn)(void *),
  434. void *arg))
  435. {
  436. tor_assert(threadpool);
  437. return threadpool_queue_work_priority(threadpool,
  438. priority,
  439. fn,
  440. reply_fn,
  441. arg);
  442. }
  443. /** Try to tell a cpuworker to perform the public key operations necessary to
  444. * respond to <b>onionskin</b> for the circuit <b>circ</b>.
  445. *
  446. * Return 0 if we successfully assign the task, or -1 on failure.
  447. */
  448. int
  449. assign_onionskin_to_cpuworker(or_circuit_t *circ,
  450. create_cell_t *onionskin)
  451. {
  452. workqueue_entry_t *queue_entry;
  453. cpuworker_job_t *job;
  454. cpuworker_request_t req;
  455. int should_time;
  456. tor_assert(threadpool);
  457. if (!circ->p_chan) {
  458. log_info(LD_OR,"circ->p_chan gone. Failing circ.");
  459. tor_free(onionskin);
  460. return -1;
  461. }
  462. if (total_pending_tasks >= max_pending_tasks) {
  463. log_debug(LD_OR,"No idle cpuworkers. Queuing.");
  464. if (onion_pending_add(circ, onionskin) < 0) {
  465. tor_free(onionskin);
  466. return -1;
  467. }
  468. return 0;
  469. }
  470. if (!channel_is_client(circ->p_chan))
  471. rep_hist_note_circuit_handshake_assigned(onionskin->handshake_type);
  472. should_time = should_time_request(onionskin->handshake_type);
  473. memset(&req, 0, sizeof(req));
  474. req.magic = CPUWORKER_REQUEST_MAGIC;
  475. req.timed = should_time;
  476. memcpy(&req.create_cell, onionskin, sizeof(create_cell_t));
  477. tor_free(onionskin);
  478. if (should_time)
  479. tor_gettimeofday(&req.started_at);
  480. job = tor_malloc_zero(sizeof(cpuworker_job_t));
  481. job->circ = circ;
  482. memcpy(&job->u.request, &req, sizeof(req));
  483. memwipe(&req, 0, sizeof(req));
  484. ++total_pending_tasks;
  485. queue_entry = threadpool_queue_work_priority(threadpool,
  486. WQ_PRI_HIGH,
  487. cpuworker_onion_handshake_threadfn,
  488. cpuworker_onion_handshake_replyfn,
  489. job);
  490. if (!queue_entry) {
  491. log_warn(LD_BUG, "Couldn't queue work on threadpool");
  492. tor_free(job);
  493. return -1;
  494. }
  495. log_debug(LD_OR, "Queued task %p (qe=%p, circ=%p)",
  496. job, queue_entry, job->circ);
  497. circ->workqueue_entry = queue_entry;
  498. return 0;
  499. }
  500. /** If <b>circ</b> has a pending handshake that hasn't been processed yet,
  501. * remove it from the worker queue. */
  502. void
  503. cpuworker_cancel_circ_handshake(or_circuit_t *circ)
  504. {
  505. cpuworker_job_t *job;
  506. if (circ->workqueue_entry == NULL)
  507. return;
  508. job = workqueue_entry_cancel(circ->workqueue_entry);
  509. if (job) {
  510. /* It successfully cancelled. */
  511. memwipe(job, 0xe0, sizeof(*job));
  512. tor_free(job);
  513. tor_assert(total_pending_tasks > 0);
  514. --total_pending_tasks;
  515. /* if (!job), this is done in cpuworker_onion_handshake_replyfn. */
  516. circ->workqueue_entry = NULL;
  517. }
  518. }