write_thread.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. #include "db/write_thread.h"
  6. #include <chrono>
  7. #include <thread>
  8. #include "db/column_family.h"
  9. #include "monitoring/perf_context_imp.h"
  10. #include "port/port.h"
  11. #include "test_util/sync_point.h"
  12. #include "util/random.h"
  13. namespace ROCKSDB_NAMESPACE {
  14. WriteThread::WriteThread(const ImmutableDBOptions& db_options)
  15. : max_yield_usec_(db_options.enable_write_thread_adaptive_yield
  16. ? db_options.write_thread_max_yield_usec
  17. : 0),
  18. slow_yield_usec_(db_options.write_thread_slow_yield_usec),
  19. allow_concurrent_memtable_write_(
  20. db_options.allow_concurrent_memtable_write),
  21. enable_pipelined_write_(db_options.enable_pipelined_write),
  22. max_write_batch_group_size_bytes(
  23. db_options.max_write_batch_group_size_bytes),
  24. newest_writer_(nullptr),
  25. newest_memtable_writer_(nullptr),
  26. last_sequence_(0),
  27. write_stall_dummy_(),
  28. stall_mu_(),
  29. stall_cv_(&stall_mu_) {}
  30. uint8_t WriteThread::BlockingAwaitState(Writer* w, uint8_t goal_mask) {
  31. // We're going to block. Lazily create the mutex. We guarantee
  32. // propagation of this construction to the waker via the
  33. // STATE_LOCKED_WAITING state. The waker won't try to touch the mutex
  34. // or the condvar unless they CAS away the STATE_LOCKED_WAITING that
  35. // we install below.
  36. w->CreateMutex();
  37. auto state = w->state.load(std::memory_order_acquire);
  38. assert(state != STATE_LOCKED_WAITING);
  39. if ((state & goal_mask) == 0 &&
  40. w->state.compare_exchange_strong(state, STATE_LOCKED_WAITING)) {
  41. // we have permission (and an obligation) to use StateMutex
  42. std::unique_lock<std::mutex> guard(w->StateMutex());
  43. w->StateCV().wait(guard, [w] {
  44. return w->state.load(std::memory_order_relaxed) != STATE_LOCKED_WAITING;
  45. });
  46. state = w->state.load(std::memory_order_relaxed);
  47. }
  48. // else tricky. Goal is met or CAS failed. In the latter case the waker
  49. // must have changed the state, and compare_exchange_strong has updated
  50. // our local variable with the new one. At the moment WriteThread never
  51. // waits for a transition across intermediate states, so we know that
  52. // since a state change has occurred the goal must have been met.
  53. assert((state & goal_mask) != 0);
  54. return state;
  55. }
  56. uint8_t WriteThread::AwaitState(Writer* w, uint8_t goal_mask,
  57. AdaptationContext* ctx) {
  58. uint8_t state = 0;
  59. // 1. Busy loop using "pause" for 1 micro sec
  60. // 2. Else SOMETIMES busy loop using "yield" for 100 micro sec (default)
  61. // 3. Else blocking wait
  62. // On a modern Xeon each loop takes about 7 nanoseconds (most of which
  63. // is the effect of the pause instruction), so 200 iterations is a bit
  64. // more than a microsecond. This is long enough that waits longer than
  65. // this can amortize the cost of accessing the clock and yielding.
  66. for (uint32_t tries = 0; tries < 200; ++tries) {
  67. state = w->state.load(std::memory_order_acquire);
  68. if ((state & goal_mask) != 0) {
  69. return state;
  70. }
  71. port::AsmVolatilePause();
  72. }
  73. // This is below the fast path, so that the stat is zero when all writes are
  74. // from the same thread.
  75. PERF_TIMER_GUARD(write_thread_wait_nanos);
  76. // If we're only going to end up waiting a short period of time,
  77. // it can be a lot more efficient to call std::this_thread::yield()
  78. // in a loop than to block in StateMutex(). For reference, on my 4.0
  79. // SELinux test server with support for syscall auditing enabled, the
  80. // minimum latency between FUTEX_WAKE to returning from FUTEX_WAIT is
  81. // 2.7 usec, and the average is more like 10 usec. That can be a big
  82. // drag on RockDB's single-writer design. Of course, spinning is a
  83. // bad idea if other threads are waiting to run or if we're going to
  84. // wait for a long time. How do we decide?
  85. //
  86. // We break waiting into 3 categories: short-uncontended,
  87. // short-contended, and long. If we had an oracle, then we would always
  88. // spin for short-uncontended, always block for long, and our choice for
  89. // short-contended might depend on whether we were trying to optimize
  90. // RocksDB throughput or avoid being greedy with system resources.
  91. //
  92. // Bucketing into short or long is easy by measuring elapsed time.
  93. // Differentiating short-uncontended from short-contended is a bit
  94. // trickier, but not too bad. We could look for involuntary context
  95. // switches using getrusage(RUSAGE_THREAD, ..), but it's less work
  96. // (portability code and CPU) to just look for yield calls that take
  97. // longer than we expect. sched_yield() doesn't actually result in any
  98. // context switch overhead if there are no other runnable processes
  99. // on the current core, in which case it usually takes less than
  100. // a microsecond.
  101. //
  102. // There are two primary tunables here: the threshold between "short"
  103. // and "long" waits, and the threshold at which we suspect that a yield
  104. // is slow enough to indicate we should probably block. If these
  105. // thresholds are chosen well then CPU-bound workloads that don't
  106. // have more threads than cores will experience few context switches
  107. // (voluntary or involuntary), and the total number of context switches
  108. // (voluntary and involuntary) will not be dramatically larger (maybe
  109. // 2x) than the number of voluntary context switches that occur when
  110. // --max_yield_wait_micros=0.
  111. //
  112. // There's another constant, which is the number of slow yields we will
  113. // tolerate before reversing our previous decision. Solitary slow
  114. // yields are pretty common (low-priority small jobs ready to run),
  115. // so this should be at least 2. We set this conservatively to 3 so
  116. // that we can also immediately schedule a ctx adaptation, rather than
  117. // waiting for the next update_ctx.
  118. const size_t kMaxSlowYieldsWhileSpinning = 3;
  119. // Whether the yield approach has any credit in this context. The credit is
  120. // added by yield being succesfull before timing out, and decreased otherwise.
  121. auto& yield_credit = ctx->value;
  122. // Update the yield_credit based on sample runs or right after a hard failure
  123. bool update_ctx = false;
  124. // Should we reinforce the yield credit
  125. bool would_spin_again = false;
  126. // The samling base for updating the yeild credit. The sampling rate would be
  127. // 1/sampling_base.
  128. const int sampling_base = 256;
  129. if (max_yield_usec_ > 0) {
  130. update_ctx = Random::GetTLSInstance()->OneIn(sampling_base);
  131. if (update_ctx || yield_credit.load(std::memory_order_relaxed) >= 0) {
  132. // we're updating the adaptation statistics, or spinning has >
  133. // 50% chance of being shorter than max_yield_usec_ and causing no
  134. // involuntary context switches
  135. auto spin_begin = std::chrono::steady_clock::now();
  136. // this variable doesn't include the final yield (if any) that
  137. // causes the goal to be met
  138. size_t slow_yield_count = 0;
  139. auto iter_begin = spin_begin;
  140. while ((iter_begin - spin_begin) <=
  141. std::chrono::microseconds(max_yield_usec_)) {
  142. std::this_thread::yield();
  143. state = w->state.load(std::memory_order_acquire);
  144. if ((state & goal_mask) != 0) {
  145. // success
  146. would_spin_again = true;
  147. break;
  148. }
  149. auto now = std::chrono::steady_clock::now();
  150. if (now == iter_begin ||
  151. now - iter_begin >= std::chrono::microseconds(slow_yield_usec_)) {
  152. // conservatively count it as a slow yield if our clock isn't
  153. // accurate enough to measure the yield duration
  154. ++slow_yield_count;
  155. if (slow_yield_count >= kMaxSlowYieldsWhileSpinning) {
  156. // Not just one ivcsw, but several. Immediately update yield_credit
  157. // and fall back to blocking
  158. update_ctx = true;
  159. break;
  160. }
  161. }
  162. iter_begin = now;
  163. }
  164. }
  165. }
  166. if ((state & goal_mask) == 0) {
  167. TEST_SYNC_POINT_CALLBACK("WriteThread::AwaitState:BlockingWaiting", w);
  168. state = BlockingAwaitState(w, goal_mask);
  169. }
  170. if (update_ctx) {
  171. // Since our update is sample based, it is ok if a thread overwrites the
  172. // updates by other threads. Thus the update does not have to be atomic.
  173. auto v = yield_credit.load(std::memory_order_relaxed);
  174. // fixed point exponential decay with decay constant 1/1024, with +1
  175. // and -1 scaled to avoid overflow for int32_t
  176. //
  177. // On each update the positive credit is decayed by a facor of 1/1024 (i.e.,
  178. // 0.1%). If the sampled yield was successful, the credit is also increased
  179. // by X. Setting X=2^17 ensures that the credit never exceeds
  180. // 2^17*2^10=2^27, which is lower than 2^31 the upperbound of int32_t. Same
  181. // logic applies to negative credits.
  182. v = v - (v / 1024) + (would_spin_again ? 1 : -1) * 131072;
  183. yield_credit.store(v, std::memory_order_relaxed);
  184. }
  185. assert((state & goal_mask) != 0);
  186. return state;
  187. }
  188. void WriteThread::SetState(Writer* w, uint8_t new_state) {
  189. auto state = w->state.load(std::memory_order_acquire);
  190. if (state == STATE_LOCKED_WAITING ||
  191. !w->state.compare_exchange_strong(state, new_state)) {
  192. assert(state == STATE_LOCKED_WAITING);
  193. std::lock_guard<std::mutex> guard(w->StateMutex());
  194. assert(w->state.load(std::memory_order_relaxed) != new_state);
  195. w->state.store(new_state, std::memory_order_relaxed);
  196. w->StateCV().notify_one();
  197. }
  198. }
  199. bool WriteThread::LinkOne(Writer* w, std::atomic<Writer*>* newest_writer) {
  200. assert(newest_writer != nullptr);
  201. assert(w->state == STATE_INIT);
  202. Writer* writers = newest_writer->load(std::memory_order_relaxed);
  203. while (true) {
  204. // If write stall in effect, and w->no_slowdown is not true,
  205. // block here until stall is cleared. If its true, then return
  206. // immediately
  207. if (writers == &write_stall_dummy_) {
  208. if (w->no_slowdown) {
  209. w->status = Status::Incomplete("Write stall");
  210. SetState(w, STATE_COMPLETED);
  211. return false;
  212. }
  213. // Since no_slowdown is false, wait here to be notified of the write
  214. // stall clearing
  215. {
  216. MutexLock lock(&stall_mu_);
  217. writers = newest_writer->load(std::memory_order_relaxed);
  218. if (writers == &write_stall_dummy_) {
  219. stall_cv_.Wait();
  220. // Load newest_writers_ again since it may have changed
  221. writers = newest_writer->load(std::memory_order_relaxed);
  222. continue;
  223. }
  224. }
  225. }
  226. w->link_older = writers;
  227. if (newest_writer->compare_exchange_weak(writers, w)) {
  228. return (writers == nullptr);
  229. }
  230. }
  231. }
  232. bool WriteThread::LinkGroup(WriteGroup& write_group,
  233. std::atomic<Writer*>* newest_writer) {
  234. assert(newest_writer != nullptr);
  235. Writer* leader = write_group.leader;
  236. Writer* last_writer = write_group.last_writer;
  237. Writer* w = last_writer;
  238. while (true) {
  239. // Unset link_newer pointers to make sure when we call
  240. // CreateMissingNewerLinks later it create all missing links.
  241. w->link_newer = nullptr;
  242. w->write_group = nullptr;
  243. if (w == leader) {
  244. break;
  245. }
  246. w = w->link_older;
  247. }
  248. Writer* newest = newest_writer->load(std::memory_order_relaxed);
  249. while (true) {
  250. leader->link_older = newest;
  251. if (newest_writer->compare_exchange_weak(newest, last_writer)) {
  252. return (newest == nullptr);
  253. }
  254. }
  255. }
  256. void WriteThread::CreateMissingNewerLinks(Writer* head) {
  257. while (true) {
  258. Writer* next = head->link_older;
  259. if (next == nullptr || next->link_newer != nullptr) {
  260. assert(next == nullptr || next->link_newer == head);
  261. break;
  262. }
  263. next->link_newer = head;
  264. head = next;
  265. }
  266. }
  267. WriteThread::Writer* WriteThread::FindNextLeader(Writer* from,
  268. Writer* boundary) {
  269. assert(from != nullptr && from != boundary);
  270. Writer* current = from;
  271. while (current->link_older != boundary) {
  272. current = current->link_older;
  273. assert(current != nullptr);
  274. }
  275. return current;
  276. }
  277. void WriteThread::CompleteLeader(WriteGroup& write_group) {
  278. assert(write_group.size > 0);
  279. Writer* leader = write_group.leader;
  280. if (write_group.size == 1) {
  281. write_group.leader = nullptr;
  282. write_group.last_writer = nullptr;
  283. } else {
  284. assert(leader->link_newer != nullptr);
  285. leader->link_newer->link_older = nullptr;
  286. write_group.leader = leader->link_newer;
  287. }
  288. write_group.size -= 1;
  289. SetState(leader, STATE_COMPLETED);
  290. }
  291. void WriteThread::CompleteFollower(Writer* w, WriteGroup& write_group) {
  292. assert(write_group.size > 1);
  293. assert(w != write_group.leader);
  294. if (w == write_group.last_writer) {
  295. w->link_older->link_newer = nullptr;
  296. write_group.last_writer = w->link_older;
  297. } else {
  298. w->link_older->link_newer = w->link_newer;
  299. w->link_newer->link_older = w->link_older;
  300. }
  301. write_group.size -= 1;
  302. SetState(w, STATE_COMPLETED);
  303. }
  304. void WriteThread::BeginWriteStall() {
  305. LinkOne(&write_stall_dummy_, &newest_writer_);
  306. // Walk writer list until w->write_group != nullptr. The current write group
  307. // will not have a mix of slowdown/no_slowdown, so its ok to stop at that
  308. // point
  309. Writer* w = write_stall_dummy_.link_older;
  310. Writer* prev = &write_stall_dummy_;
  311. while (w != nullptr && w->write_group == nullptr) {
  312. if (w->no_slowdown) {
  313. prev->link_older = w->link_older;
  314. w->status = Status::Incomplete("Write stall");
  315. SetState(w, STATE_COMPLETED);
  316. if (prev->link_older) {
  317. prev->link_older->link_newer = prev;
  318. }
  319. w = prev->link_older;
  320. } else {
  321. prev = w;
  322. w = w->link_older;
  323. }
  324. }
  325. }
  326. void WriteThread::EndWriteStall() {
  327. MutexLock lock(&stall_mu_);
  328. // Unlink write_stall_dummy_ from the write queue. This will unblock
  329. // pending write threads to enqueue themselves
  330. assert(newest_writer_.load(std::memory_order_relaxed) == &write_stall_dummy_);
  331. assert(write_stall_dummy_.link_older != nullptr);
  332. write_stall_dummy_.link_older->link_newer = write_stall_dummy_.link_newer;
  333. newest_writer_.exchange(write_stall_dummy_.link_older);
  334. // Wake up writers
  335. stall_cv_.SignalAll();
  336. }
  337. static WriteThread::AdaptationContext jbg_ctx("JoinBatchGroup");
  338. void WriteThread::JoinBatchGroup(Writer* w) {
  339. TEST_SYNC_POINT_CALLBACK("WriteThread::JoinBatchGroup:Start", w);
  340. assert(w->batch != nullptr);
  341. bool linked_as_leader = LinkOne(w, &newest_writer_);
  342. if (linked_as_leader) {
  343. SetState(w, STATE_GROUP_LEADER);
  344. }
  345. TEST_SYNC_POINT_CALLBACK("WriteThread::JoinBatchGroup:Wait", w);
  346. if (!linked_as_leader) {
  347. /**
  348. * Wait util:
  349. * 1) An existing leader pick us as the new leader when it finishes
  350. * 2) An existing leader pick us as its follewer and
  351. * 2.1) finishes the memtable writes on our behalf
  352. * 2.2) Or tell us to finish the memtable writes in pralallel
  353. * 3) (pipelined write) An existing leader pick us as its follower and
  354. * finish book-keeping and WAL write for us, enqueue us as pending
  355. * memtable writer, and
  356. * 3.1) we become memtable writer group leader, or
  357. * 3.2) an existing memtable writer group leader tell us to finish memtable
  358. * writes in parallel.
  359. */
  360. TEST_SYNC_POINT_CALLBACK("WriteThread::JoinBatchGroup:BeganWaiting", w);
  361. AwaitState(w, STATE_GROUP_LEADER | STATE_MEMTABLE_WRITER_LEADER |
  362. STATE_PARALLEL_MEMTABLE_WRITER | STATE_COMPLETED,
  363. &jbg_ctx);
  364. TEST_SYNC_POINT_CALLBACK("WriteThread::JoinBatchGroup:DoneWaiting", w);
  365. }
  366. }
  367. size_t WriteThread::EnterAsBatchGroupLeader(Writer* leader,
  368. WriteGroup* write_group) {
  369. assert(leader->link_older == nullptr);
  370. assert(leader->batch != nullptr);
  371. assert(write_group != nullptr);
  372. size_t size = WriteBatchInternal::ByteSize(leader->batch);
  373. // Allow the group to grow up to a maximum size, but if the
  374. // original write is small, limit the growth so we do not slow
  375. // down the small write too much.
  376. size_t max_size = max_write_batch_group_size_bytes;
  377. const uint64_t min_batch_size_bytes = max_write_batch_group_size_bytes / 8;
  378. if (size <= min_batch_size_bytes) {
  379. max_size = size + min_batch_size_bytes;
  380. }
  381. leader->write_group = write_group;
  382. write_group->leader = leader;
  383. write_group->last_writer = leader;
  384. write_group->size = 1;
  385. Writer* newest_writer = newest_writer_.load(std::memory_order_acquire);
  386. // This is safe regardless of any db mutex status of the caller. Previous
  387. // calls to ExitAsGroupLeader either didn't call CreateMissingNewerLinks
  388. // (they emptied the list and then we added ourself as leader) or had to
  389. // explicitly wake us up (the list was non-empty when we added ourself,
  390. // so we have already received our MarkJoined).
  391. CreateMissingNewerLinks(newest_writer);
  392. // Tricky. Iteration start (leader) is exclusive and finish
  393. // (newest_writer) is inclusive. Iteration goes from old to new.
  394. Writer* w = leader;
  395. while (w != newest_writer) {
  396. w = w->link_newer;
  397. if (w->sync && !leader->sync) {
  398. // Do not include a sync write into a batch handled by a non-sync write.
  399. break;
  400. }
  401. if (w->no_slowdown != leader->no_slowdown) {
  402. // Do not mix writes that are ok with delays with the ones that
  403. // request fail on delays.
  404. break;
  405. }
  406. if (w->disable_wal != leader->disable_wal) {
  407. // Do not mix writes that enable WAL with the ones whose
  408. // WAL disabled.
  409. break;
  410. }
  411. if (w->batch == nullptr) {
  412. // Do not include those writes with nullptr batch. Those are not writes,
  413. // those are something else. They want to be alone
  414. break;
  415. }
  416. if (w->callback != nullptr && !w->callback->AllowWriteBatching()) {
  417. // dont batch writes that don't want to be batched
  418. break;
  419. }
  420. auto batch_size = WriteBatchInternal::ByteSize(w->batch);
  421. if (size + batch_size > max_size) {
  422. // Do not make batch too big
  423. break;
  424. }
  425. w->write_group = write_group;
  426. size += batch_size;
  427. write_group->last_writer = w;
  428. write_group->size++;
  429. }
  430. TEST_SYNC_POINT_CALLBACK("WriteThread::EnterAsBatchGroupLeader:End", w);
  431. return size;
  432. }
  433. void WriteThread::EnterAsMemTableWriter(Writer* leader,
  434. WriteGroup* write_group) {
  435. assert(leader != nullptr);
  436. assert(leader->link_older == nullptr);
  437. assert(leader->batch != nullptr);
  438. assert(write_group != nullptr);
  439. size_t size = WriteBatchInternal::ByteSize(leader->batch);
  440. // Allow the group to grow up to a maximum size, but if the
  441. // original write is small, limit the growth so we do not slow
  442. // down the small write too much.
  443. size_t max_size = max_write_batch_group_size_bytes;
  444. const uint64_t min_batch_size_bytes = max_write_batch_group_size_bytes / 8;
  445. if (size <= min_batch_size_bytes) {
  446. max_size = size + min_batch_size_bytes;
  447. }
  448. leader->write_group = write_group;
  449. write_group->leader = leader;
  450. write_group->size = 1;
  451. Writer* last_writer = leader;
  452. if (!allow_concurrent_memtable_write_ || !leader->batch->HasMerge()) {
  453. Writer* newest_writer = newest_memtable_writer_.load();
  454. CreateMissingNewerLinks(newest_writer);
  455. Writer* w = leader;
  456. while (w != newest_writer) {
  457. w = w->link_newer;
  458. if (w->batch == nullptr) {
  459. break;
  460. }
  461. if (w->batch->HasMerge()) {
  462. break;
  463. }
  464. if (!allow_concurrent_memtable_write_) {
  465. auto batch_size = WriteBatchInternal::ByteSize(w->batch);
  466. if (size + batch_size > max_size) {
  467. // Do not make batch too big
  468. break;
  469. }
  470. size += batch_size;
  471. }
  472. w->write_group = write_group;
  473. last_writer = w;
  474. write_group->size++;
  475. }
  476. }
  477. write_group->last_writer = last_writer;
  478. write_group->last_sequence =
  479. last_writer->sequence + WriteBatchInternal::Count(last_writer->batch) - 1;
  480. }
  481. void WriteThread::ExitAsMemTableWriter(Writer* /*self*/,
  482. WriteGroup& write_group) {
  483. Writer* leader = write_group.leader;
  484. Writer* last_writer = write_group.last_writer;
  485. Writer* newest_writer = last_writer;
  486. if (!newest_memtable_writer_.compare_exchange_strong(newest_writer,
  487. nullptr)) {
  488. CreateMissingNewerLinks(newest_writer);
  489. Writer* next_leader = last_writer->link_newer;
  490. assert(next_leader != nullptr);
  491. next_leader->link_older = nullptr;
  492. SetState(next_leader, STATE_MEMTABLE_WRITER_LEADER);
  493. }
  494. Writer* w = leader;
  495. while (true) {
  496. if (!write_group.status.ok()) {
  497. w->status = write_group.status;
  498. }
  499. Writer* next = w->link_newer;
  500. if (w != leader) {
  501. SetState(w, STATE_COMPLETED);
  502. }
  503. if (w == last_writer) {
  504. break;
  505. }
  506. w = next;
  507. }
  508. // Note that leader has to exit last, since it owns the write group.
  509. SetState(leader, STATE_COMPLETED);
  510. }
  511. void WriteThread::LaunchParallelMemTableWriters(WriteGroup* write_group) {
  512. assert(write_group != nullptr);
  513. write_group->running.store(write_group->size);
  514. for (auto w : *write_group) {
  515. SetState(w, STATE_PARALLEL_MEMTABLE_WRITER);
  516. }
  517. }
  518. static WriteThread::AdaptationContext cpmtw_ctx("CompleteParallelMemTableWriter");
  519. // This method is called by both the leader and parallel followers
  520. bool WriteThread::CompleteParallelMemTableWriter(Writer* w) {
  521. auto* write_group = w->write_group;
  522. if (!w->status.ok()) {
  523. std::lock_guard<std::mutex> guard(write_group->leader->StateMutex());
  524. write_group->status = w->status;
  525. }
  526. if (write_group->running-- > 1) {
  527. // we're not the last one
  528. AwaitState(w, STATE_COMPLETED, &cpmtw_ctx);
  529. return false;
  530. }
  531. // else we're the last parallel worker and should perform exit duties.
  532. w->status = write_group->status;
  533. return true;
  534. }
  535. void WriteThread::ExitAsBatchGroupFollower(Writer* w) {
  536. auto* write_group = w->write_group;
  537. assert(w->state == STATE_PARALLEL_MEMTABLE_WRITER);
  538. assert(write_group->status.ok());
  539. ExitAsBatchGroupLeader(*write_group, write_group->status);
  540. assert(w->status.ok());
  541. assert(w->state == STATE_COMPLETED);
  542. SetState(write_group->leader, STATE_COMPLETED);
  543. }
  544. static WriteThread::AdaptationContext eabgl_ctx("ExitAsBatchGroupLeader");
  545. void WriteThread::ExitAsBatchGroupLeader(WriteGroup& write_group,
  546. Status status) {
  547. Writer* leader = write_group.leader;
  548. Writer* last_writer = write_group.last_writer;
  549. assert(leader->link_older == nullptr);
  550. // Propagate memtable write error to the whole group.
  551. if (status.ok() && !write_group.status.ok()) {
  552. status = write_group.status;
  553. }
  554. if (enable_pipelined_write_) {
  555. // Notify writers don't write to memtable to exit.
  556. for (Writer* w = last_writer; w != leader;) {
  557. Writer* next = w->link_older;
  558. w->status = status;
  559. if (!w->ShouldWriteToMemtable()) {
  560. CompleteFollower(w, write_group);
  561. }
  562. w = next;
  563. }
  564. if (!leader->ShouldWriteToMemtable()) {
  565. CompleteLeader(write_group);
  566. }
  567. Writer* next_leader = nullptr;
  568. // Look for next leader before we call LinkGroup. If there isn't
  569. // pending writers, place a dummy writer at the tail of the queue
  570. // so we know the boundary of the current write group.
  571. Writer dummy;
  572. Writer* expected = last_writer;
  573. bool has_dummy = newest_writer_.compare_exchange_strong(expected, &dummy);
  574. if (!has_dummy) {
  575. // We find at least one pending writer when we insert dummy. We search
  576. // for next leader from there.
  577. next_leader = FindNextLeader(expected, last_writer);
  578. assert(next_leader != nullptr && next_leader != last_writer);
  579. }
  580. // Link the ramaining of the group to memtable writer list.
  581. //
  582. // We have to link our group to memtable writer queue before wake up the
  583. // next leader or set newest_writer_ to null, otherwise the next leader
  584. // can run ahead of us and link to memtable writer queue before we do.
  585. if (write_group.size > 0) {
  586. if (LinkGroup(write_group, &newest_memtable_writer_)) {
  587. // The leader can now be different from current writer.
  588. SetState(write_group.leader, STATE_MEMTABLE_WRITER_LEADER);
  589. }
  590. }
  591. // If we have inserted dummy in the queue, remove it now and check if there
  592. // are pending writer join the queue since we insert the dummy. If so,
  593. // look for next leader again.
  594. if (has_dummy) {
  595. assert(next_leader == nullptr);
  596. expected = &dummy;
  597. bool has_pending_writer =
  598. !newest_writer_.compare_exchange_strong(expected, nullptr);
  599. if (has_pending_writer) {
  600. next_leader = FindNextLeader(expected, &dummy);
  601. assert(next_leader != nullptr && next_leader != &dummy);
  602. }
  603. }
  604. if (next_leader != nullptr) {
  605. next_leader->link_older = nullptr;
  606. SetState(next_leader, STATE_GROUP_LEADER);
  607. }
  608. AwaitState(leader, STATE_MEMTABLE_WRITER_LEADER |
  609. STATE_PARALLEL_MEMTABLE_WRITER | STATE_COMPLETED,
  610. &eabgl_ctx);
  611. } else {
  612. Writer* head = newest_writer_.load(std::memory_order_acquire);
  613. if (head != last_writer ||
  614. !newest_writer_.compare_exchange_strong(head, nullptr)) {
  615. // Either w wasn't the head during the load(), or it was the head
  616. // during the load() but somebody else pushed onto the list before
  617. // we did the compare_exchange_strong (causing it to fail). In the
  618. // latter case compare_exchange_strong has the effect of re-reading
  619. // its first param (head). No need to retry a failing CAS, because
  620. // only a departing leader (which we are at the moment) can remove
  621. // nodes from the list.
  622. assert(head != last_writer);
  623. // After walking link_older starting from head (if not already done)
  624. // we will be able to traverse w->link_newer below. This function
  625. // can only be called from an active leader, only a leader can
  626. // clear newest_writer_, we didn't, and only a clear newest_writer_
  627. // could cause the next leader to start their work without a call
  628. // to MarkJoined, so we can definitely conclude that no other leader
  629. // work is going on here (with or without db mutex).
  630. CreateMissingNewerLinks(head);
  631. assert(last_writer->link_newer->link_older == last_writer);
  632. last_writer->link_newer->link_older = nullptr;
  633. // Next leader didn't self-identify, because newest_writer_ wasn't
  634. // nullptr when they enqueued (we were definitely enqueued before them
  635. // and are still in the list). That means leader handoff occurs when
  636. // we call MarkJoined
  637. SetState(last_writer->link_newer, STATE_GROUP_LEADER);
  638. }
  639. // else nobody else was waiting, although there might already be a new
  640. // leader now
  641. while (last_writer != leader) {
  642. last_writer->status = status;
  643. // we need to read link_older before calling SetState, because as soon
  644. // as it is marked committed the other thread's Await may return and
  645. // deallocate the Writer.
  646. auto next = last_writer->link_older;
  647. SetState(last_writer, STATE_COMPLETED);
  648. last_writer = next;
  649. }
  650. }
  651. }
  652. static WriteThread::AdaptationContext eu_ctx("EnterUnbatched");
  653. void WriteThread::EnterUnbatched(Writer* w, InstrumentedMutex* mu) {
  654. assert(w != nullptr && w->batch == nullptr);
  655. mu->Unlock();
  656. bool linked_as_leader = LinkOne(w, &newest_writer_);
  657. if (!linked_as_leader) {
  658. TEST_SYNC_POINT("WriteThread::EnterUnbatched:Wait");
  659. // Last leader will not pick us as a follower since our batch is nullptr
  660. AwaitState(w, STATE_GROUP_LEADER, &eu_ctx);
  661. }
  662. if (enable_pipelined_write_) {
  663. WaitForMemTableWriters();
  664. }
  665. mu->Lock();
  666. }
  667. void WriteThread::ExitUnbatched(Writer* w) {
  668. assert(w != nullptr);
  669. Writer* newest_writer = w;
  670. if (!newest_writer_.compare_exchange_strong(newest_writer, nullptr)) {
  671. CreateMissingNewerLinks(newest_writer);
  672. Writer* next_leader = w->link_newer;
  673. assert(next_leader != nullptr);
  674. next_leader->link_older = nullptr;
  675. SetState(next_leader, STATE_GROUP_LEADER);
  676. }
  677. }
  678. static WriteThread::AdaptationContext wfmw_ctx("WaitForMemTableWriters");
  679. void WriteThread::WaitForMemTableWriters() {
  680. assert(enable_pipelined_write_);
  681. if (newest_memtable_writer_.load() == nullptr) {
  682. return;
  683. }
  684. Writer w;
  685. if (!LinkOne(&w, &newest_memtable_writer_)) {
  686. AwaitState(&w, STATE_MEMTABLE_WRITER_LEADER, &wfmw_ctx);
  687. }
  688. newest_memtable_writer_.store(nullptr);
  689. }
  690. } // namespace ROCKSDB_NAMESPACE