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