cpuworker.c 18 KB

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