cpuworker.c 18 KB

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