cpuworker.c 18 KB

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