cpuworker.c 17 KB

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