-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathreactor.cc
5117 lines (4562 loc) · 189 KB
/
reactor.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2014 Cloudius Systems
*/
#ifdef SEASTAR_MODULE
module;
#endif
#include <atomic>
#include <cassert>
#include <chrono>
#include <cmath>
#include <exception>
#include <filesystem>
#include <fstream>
#include <regex>
#include <thread>
#include <spawn.h>
#include <sys/syscall.h>
#include <sys/vfs.h>
#include <sys/statfs.h>
#include <sys/statvfs.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/inotify.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/eventfd.h>
#include <poll.h>
#include <netinet/in.h>
#include <boost/lexical_cast.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/constants.hpp>
#include <boost/algorithm/string/find_iterator.hpp>
#include <boost/algorithm/string/finder.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/container/small_vector.hpp>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/intrusive/list.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/irange.hpp>
#include <boost/range/numeric.hpp>
#include <boost/range/algorithm/sort.hpp>
#include <boost/range/algorithm/remove_if.hpp>
#include <boost/range/algorithm/find_if.hpp>
#include <boost/algorithm/clamp.hpp>
#include <boost/version.hpp>
#include <dirent.h>
#define __user /* empty */ // for xfs includes, below
#include <linux/types.h> // for xfs, below
#include <sys/ioctl.h>
#include <linux/perf_event.h>
#include <xfs/linux.h>
/*
* With package xfsprogs-devel >= 5.14.1, `fallthrough` has defined to
* fix compilation warning in header <xfs/linux.h>,
* (see: https://git.kernel.org/pub/scm/fs/xfs/xfsprogs-dev.git/commit/?id=df9c7d8d8f3ed0785ed83e7fd0c7ddc92cbfbe15)
* There is a confliction with c++ keyword `fallthrough`, so undefine fallthrough here.
*/
#undef fallthrough
#define min min /* prevent xfs.h from defining min() as a macro */
#include <xfs/xfs.h>
#undef min
#include <fmt/ostream.h>
#include <fmt/ranges.h>
#ifdef SEASTAR_SHUFFLE_TASK_QUEUE
#include <random>
#endif
#include <sys/mman.h>
#include <sys/utsname.h>
#include <linux/falloc.h>
#ifdef SEASTAR_HAVE_SYSTEMTAP_SDT
#include <sys/sdt.h>
#else
#define STAP_PROBE(provider, name)
#endif
#if defined(__x86_64__) || defined(__i386__)
#include <xmmintrin.h>
#endif
#ifdef SEASTAR_HAVE_DPDK
#include <rte_lcore.h>
#include <rte_launch.h>
#endif
#ifdef __GNUC__
#include <iostream>
#include <system_error>
#include <cxxabi.h>
#endif
#include <yaml-cpp/yaml.h>
#ifdef SEASTAR_TASK_HISTOGRAM
#include <typeinfo>
#endif
#ifdef SEASTAR_MODULE
module seastar;
#else
#include <seastar/core/abort_on_ebadf.hh>
#include <seastar/core/alien.hh>
#include <seastar/core/exception_hacks.hh>
#include <seastar/core/execution_stage.hh>
#include <seastar/core/io_queue.hh>
#include <seastar/core/loop.hh>
#include <seastar/core/make_task.hh>
#include <seastar/core/memory.hh>
#include <seastar/core/metrics.hh>
#include <seastar/core/posix.hh>
#include <seastar/core/prefetch.hh>
#include <seastar/core/print.hh>
#include <seastar/core/reactor.hh>
#include <seastar/core/report_exception.hh>
#include <seastar/core/resource.hh>
#include <seastar/core/scheduling.hh>
#include <seastar/core/scheduling_specific.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/smp.hh>
#include <seastar/core/smp_options.hh>
#include <seastar/core/stall_sampler.hh>
#include <seastar/core/systemwide_memory_barrier.hh>
#include <seastar/core/task.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/thread_cputime_clock.hh>
#include <seastar/core/when_all.hh>
#include <seastar/core/with_scheduling_group.hh>
#include <seastar/core/internal/buffer_allocator.hh>
#include <seastar/core/internal/io_desc.hh>
#include <seastar/core/internal/uname.hh>
#include <seastar/core/internal/stall_detector.hh>
#include <seastar/core/internal/run_in_background.hh>
#include <seastar/net/native-stack.hh>
#include <seastar/net/packet.hh>
#include <seastar/net/posix-stack.hh>
#include <seastar/net/stack.hh>
#include <seastar/util/backtrace.hh>
#include <seastar/util/conversions.hh>
#include <seastar/util/defer.hh>
#include <seastar/util/log.hh>
#include <seastar/util/memory_diagnostics.hh>
#include <seastar/util/noncopyable_function.hh>
#include <seastar/util/print_safe.hh>
#include <seastar/util/process.hh>
#include <seastar/util/read_first_line.hh>
#include <seastar/util/spinlock.hh>
#include <seastar/util/internal/iovec_utils.hh>
#include <seastar/util/internal/magic.hh>
#include "core/reactor_backend.hh"
#include "core/syscall_result.hh"
#include "core/thread_pool.hh"
#include "syscall_work_queue.hh"
#include "cgroup.hh"
#ifdef SEASTAR_HAVE_DPDK
#include <seastar/core/dpdk_rte.hh>
#endif
#endif // SEASTAR_MODULE
namespace seastar {
static_assert(posix::shutdown_mask(SHUT_RD) == posix::rcv_shutdown);
static_assert(posix::shutdown_mask(SHUT_WR) == posix::snd_shutdown);
static_assert(posix::shutdown_mask(SHUT_RDWR) == (posix::snd_shutdown | posix::rcv_shutdown));
struct mountpoint_params {
std::string mountpoint = "none";
uint64_t read_bytes_rate = std::numeric_limits<uint64_t>::max();
uint64_t write_bytes_rate = std::numeric_limits<uint64_t>::max();
uint64_t read_req_rate = std::numeric_limits<uint64_t>::max();
uint64_t write_req_rate = std::numeric_limits<uint64_t>::max();
uint64_t read_saturation_length = std::numeric_limits<uint64_t>::max();
uint64_t write_saturation_length = std::numeric_limits<uint64_t>::max();
bool duplex = false;
float rate_factor = 1.0;
};
}
namespace YAML {
template<>
struct convert<seastar::mountpoint_params> {
static bool decode(const Node& node, seastar::mountpoint_params& mp) {
using namespace seastar;
mp.mountpoint = node["mountpoint"].as<std::string>().c_str();
mp.read_bytes_rate = parse_memory_size(node["read_bandwidth"].as<std::string>());
mp.read_req_rate = parse_memory_size(node["read_iops"].as<std::string>());
mp.write_bytes_rate = parse_memory_size(node["write_bandwidth"].as<std::string>());
mp.write_req_rate = parse_memory_size(node["write_iops"].as<std::string>());
if (node["read_saturation_length"]) {
mp.read_saturation_length = parse_memory_size(node["read_saturation_length"].as<std::string>());
}
if (node["write_saturation_length"]) {
mp.write_saturation_length = parse_memory_size(node["write_saturation_length"].as<std::string>());
}
if (node["duplex"]) {
mp.duplex = node["duplex"].as<bool>();
}
if (node["rate_factor"]) {
mp.rate_factor = node["rate_factor"].as<float>();
}
return true;
}
};
}
namespace seastar {
seastar::logger seastar_logger("seastar");
seastar::logger sched_logger("scheduler");
shard_id reactor::cpu_id() const {
assert(_id == this_shard_id());
return _id;
}
#if SEASTAR_API_LEVEL < 7
io_priority_class
reactor::register_one_priority_class(sstring name, uint32_t shares) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
return io_priority_class::register_one(std::move(name), shares);
#pragma GCC diagnostic pop
}
future<>
reactor::update_shares_for_class(io_priority_class pc, uint32_t shares) {
return pc.update_shares(shares);
}
future<>
reactor::rename_priority_class(io_priority_class pc, sstring new_name) noexcept {
return pc.rename(std::move(new_name));
}
#endif
void reactor::update_shares_for_queues(internal::priority_class pc, uint32_t shares) {
for (auto&& q : _io_queues) {
q.second->update_shares_for_class(pc, shares);
}
}
future<> reactor::update_bandwidth_for_queues(internal::priority_class pc, uint64_t bandwidth) {
return smp::invoke_on_all([pc, bandwidth = bandwidth / _num_io_groups] {
return parallel_for_each(engine()._io_queues, [pc, bandwidth] (auto& queue) {
return queue.second->update_bandwidth_for_class(pc, bandwidth);
});
});
}
void reactor::rename_queues(internal::priority_class pc, sstring new_name) {
for (auto&& queue : _io_queues) {
queue.second->rename_priority_class(pc, new_name);
}
}
future<std::tuple<pollable_fd, socket_address>>
reactor::do_accept(pollable_fd_state& listenfd) {
return readable_or_writeable(listenfd).then([this, &listenfd] () mutable {
socket_address sa;
listenfd.maybe_no_more_recv();
auto maybe_fd = listenfd.fd.try_accept(sa, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (!maybe_fd) {
// We speculated that we will have an another connection, but got a false
// positive. Try again without speculation.
return do_accept(listenfd);
}
// Speculate that there is another connection on this listening socket, to avoid
// a task-quota delay. Usually this will fail, but accept is a rare-enough operation
// that it is worth the false positive in order to withstand a connection storm
// without having to accept at a rate of 1 per task quota.
listenfd.speculate_epoll(EPOLLIN);
pollable_fd pfd(std::move(*maybe_fd), pollable_fd::speculation(EPOLLOUT));
return make_ready_future<std::tuple<pollable_fd, socket_address>>(std::make_tuple(std::move(pfd), std::move(sa)));
});
}
future<> reactor::do_connect(pollable_fd_state& pfd, socket_address& sa) {
pfd.fd.connect(sa.u.sa, sa.length());
return pfd.writeable().then([&pfd]() mutable {
auto err = pfd.fd.getsockopt<int>(SOL_SOCKET, SO_ERROR);
if (err != 0) {
throw std::system_error(err, std::system_category());
}
return make_ready_future<>();
});
}
future<size_t>
reactor::do_read(pollable_fd_state& fd, void* buffer, size_t len) {
return readable(fd).then([this, &fd, buffer, len] () mutable {
auto r = fd.fd.read(buffer, len);
if (!r) {
return do_read(fd, buffer, len);
}
if (size_t(*r) == len) {
fd.speculate_epoll(EPOLLIN);
}
return make_ready_future<size_t>(*r);
});
}
future<temporary_buffer<char>>
reactor::do_read_some(pollable_fd_state& fd, internal::buffer_allocator* ba) {
return fd.readable().then([this, &fd, ba] {
auto buffer = ba->allocate_buffer();
auto r = fd.fd.read(buffer.get_write(), buffer.size());
if (!r) {
// Speculation failure, try again with real polling this time
// Note we release the buffer and will reallocate it when poll
// completes.
return do_read_some(fd, ba);
}
if (size_t(*r) == buffer.size()) {
fd.speculate_epoll(EPOLLIN);
}
buffer.trim(*r);
return make_ready_future<temporary_buffer<char>>(std::move(buffer));
});
}
future<size_t>
reactor::do_recvmsg(pollable_fd_state& fd, const std::vector<iovec>& iov) {
return readable(fd).then([this, &fd, iov = iov] () mutable {
::msghdr mh = {};
mh.msg_iov = &iov[0];
mh.msg_iovlen = iov.size();
auto r = fd.fd.recvmsg(&mh, 0);
if (!r) {
return do_recvmsg(fd, iov);
}
if (size_t(*r) == internal::iovec_len(iov)) {
fd.speculate_epoll(EPOLLIN);
}
return make_ready_future<size_t>(*r);
});
}
future<size_t>
reactor::do_send(pollable_fd_state& fd, const void* buffer, size_t len) {
return writeable(fd).then([this, &fd, buffer, len] () mutable {
auto r = fd.fd.send(buffer, len, MSG_NOSIGNAL);
if (!r) {
return do_send(fd, buffer, len);
}
if (size_t(*r) == len) {
fd.speculate_epoll(EPOLLOUT);
}
return make_ready_future<size_t>(*r);
});
}
future<size_t>
reactor::do_sendmsg(pollable_fd_state& fd, net::packet& p) {
return writeable(fd).then([this, &fd, &p] () mutable {
static_assert(offsetof(iovec, iov_base) == offsetof(net::fragment, base) &&
sizeof(iovec::iov_base) == sizeof(net::fragment::base) &&
offsetof(iovec, iov_len) == offsetof(net::fragment, size) &&
sizeof(iovec::iov_len) == sizeof(net::fragment::size) &&
alignof(iovec) == alignof(net::fragment) &&
sizeof(iovec) == sizeof(net::fragment)
, "net::fragment and iovec should be equivalent");
iovec* iov = reinterpret_cast<iovec*>(p.fragment_array());
msghdr mh = {};
mh.msg_iov = iov;
mh.msg_iovlen = std::min<size_t>(p.nr_frags(), IOV_MAX);
auto r = fd.fd.sendmsg(&mh, MSG_NOSIGNAL);
if (!r) {
return do_sendmsg(fd, p);
}
if (size_t(*r) == p.len()) {
fd.speculate_epoll(EPOLLOUT);
}
return make_ready_future<size_t>(*r);
});
}
future<>
reactor::send_all_part(pollable_fd_state& fd, const void* buffer, size_t len, size_t completed) {
if (completed == len) {
return make_ready_future<>();
} else {
return _backend->send(fd, static_cast<const char*>(buffer) + completed, len - completed).then(
[&fd, buffer, len, completed, this] (size_t part) mutable {
return send_all_part(fd, buffer, len, completed + part);
});
}
}
future<temporary_buffer<char>>
reactor::do_recv_some(pollable_fd_state& fd, internal::buffer_allocator* ba) {
return fd.readable().then([this, &fd, ba] {
auto buffer = ba->allocate_buffer();
auto r = fd.fd.recv(buffer.get_write(), buffer.size(), MSG_DONTWAIT);
if (!r) {
return do_recv_some(fd, ba);
}
if (size_t(*r) == buffer.size()) {
fd.speculate_epoll(EPOLLIN);
}
buffer.trim(*r);
return make_ready_future<temporary_buffer<char>>(std::move(buffer));
});
}
future<>
reactor::send_all(pollable_fd_state& fd, const void* buffer, size_t len) {
assert(len);
return send_all_part(fd, buffer, len, 0);
}
future<size_t> pollable_fd_state::read_some(char* buffer, size_t size) {
return engine()._backend->read(*this, buffer, size);
}
future<size_t> pollable_fd_state::read_some(uint8_t* buffer, size_t size) {
return engine()._backend->read(*this, buffer, size);
}
future<size_t> pollable_fd_state::read_some(const std::vector<iovec>& iov) {
return engine()._backend->recvmsg(*this, iov);
}
future<temporary_buffer<char>> pollable_fd_state::read_some(internal::buffer_allocator* ba) {
return engine()._backend->read_some(*this, ba);
}
future<size_t> pollable_fd_state::write_some(net::packet& p) {
return engine()._backend->sendmsg(*this, p);
}
future<> pollable_fd_state::write_all(const char* buffer, size_t size) {
return engine().send_all(*this, buffer, size);
}
future<> pollable_fd_state::write_all(const uint8_t* buffer, size_t size) {
return engine().send_all(*this, buffer, size);
}
future<> pollable_fd_state::write_all(net::packet& p) {
return write_some(p).then([this, &p] (size_t size) {
if (p.len() == size) {
return make_ready_future<>();
}
p.trim_front(size);
return write_all(p);
});
}
future<> pollable_fd_state::readable() {
return engine().readable(*this);
}
future<> pollable_fd_state::writeable() {
return engine().writeable(*this);
}
future<> pollable_fd_state::poll_rdhup() {
return engine().poll_rdhup(*this);
}
future<> pollable_fd_state::readable_or_writeable() {
return engine().readable_or_writeable(*this);
}
future<std::tuple<pollable_fd, socket_address>> pollable_fd_state::accept() {
return engine()._backend->accept(*this);
}
future<> pollable_fd_state::connect(socket_address& sa) {
return engine()._backend->connect(*this, sa);
}
future<temporary_buffer<char>> pollable_fd_state::recv_some(internal::buffer_allocator* ba) {
maybe_no_more_recv();
return engine()._backend->recv_some(*this, ba);
}
future<size_t> pollable_fd_state::recvmsg(struct msghdr *msg) {
maybe_no_more_recv();
return engine().readable(*this).then([this, msg] {
auto r = fd.recvmsg(msg, 0);
if (!r) {
return recvmsg(msg);
}
// We always speculate here to optimize for throughput in a workload
// with multiple outstanding requests. This way the caller can consume
// all messages without resorting to epoll. However this adds extra
// recvmsg() call when we hit the empty queue condition, so it may
// hurt request-response workload in which the queue is empty when we
// initially enter recvmsg(). If that turns out to be a problem, we can
// improve speculation by using recvmmsg().
speculate_epoll(EPOLLIN);
return make_ready_future<size_t>(*r);
});
}
future<size_t> pollable_fd_state::sendmsg(struct msghdr* msg) {
maybe_no_more_send();
return engine().writeable(*this).then([this, msg] () mutable {
auto r = fd.sendmsg(msg, 0);
if (!r) {
return sendmsg(msg);
}
// For UDP this will always speculate. We can't know if there's room
// or not, but most of the time there should be so the cost of mis-
// speculation is amortized.
if (size_t(*r) == internal::iovec_len(msg->msg_iov, msg->msg_iovlen)) {
speculate_epoll(EPOLLOUT);
}
return make_ready_future<size_t>(*r);
});
}
future<size_t> pollable_fd_state::sendto(socket_address addr, const void* buf, size_t len) {
maybe_no_more_send();
return engine().writeable(*this).then([this, buf, len, addr] () mutable {
auto r = fd.sendto(addr, buf, len, 0);
if (!r) {
return sendto(std::move(addr), buf, len);
}
// See the comment about speculation in sendmsg().
if (size_t(*r) == len) {
speculate_epoll(EPOLLOUT);
}
return make_ready_future<size_t>(*r);
});
}
namespace internal {
#ifdef SEASTAR_BUILD_SHARED_LIBS
const preemption_monitor*& get_need_preempt_var() {
static preemption_monitor bootstrap_preemption_monitor;
static thread_local const preemption_monitor* g_need_preempt = &bootstrap_preemption_monitor;
return g_need_preempt;
}
#endif
void set_need_preempt_var(const preemption_monitor* np) {
get_need_preempt_var() = np;
}
#ifdef SEASTAR_TASK_HISTOGRAM
class task_histogram {
static constexpr unsigned max_countdown = 1'000'000;
std::unordered_map<std::type_index, uint64_t> _histogram;
unsigned _countdown_to_print = max_countdown;
public:
void add(const task& t) {
++_histogram[std::type_index(typeid(t))];
if (!--_countdown_to_print) {
print();
_countdown_to_print = max_countdown;
_histogram.clear();
}
}
void print() const {
seastar::fmt::print("task histogram, {:d} task types {:d} tasks\n", _histogram.size(), max_countdown - _countdown_to_print);
for (auto&& type_count : _histogram) {
auto&& type = type_count.first;
auto&& count = type_count.second;
seastar::fmt::print(" {:10d} {}\n", count, type.name());
}
}
};
thread_local task_histogram this_thread_task_histogram;
void task_histogram_add_task(const task& t) {
this_thread_task_histogram.add(t);
}
#else
void task_histogram_add_task(const task& t) {
}
#endif
}
using namespace std::chrono_literals;
namespace fs = std::filesystem;
using namespace net;
using namespace internal::linux_abi;
std::atomic<manual_clock::rep> manual_clock::_now;
// Base version where this works; some filesystems were only fixed later, so
// this value is mixed in with filesystem-provided values later.
bool aio_nowait_supported = internal::kernel_uname().whitelisted({"4.13"});
static bool sched_debug() {
return false;
}
template <typename... Args>
void
#if SEASTAR_LOGGER_COMPILE_TIME_FMT
sched_print(fmt::format_string<Args...> fmt, Args&&... args) {
#else
sched_print(const char* fmt, Args&&... args) {
#endif
if (sched_debug()) {
sched_logger.trace(fmt, std::forward<Args>(args)...);
}
}
static std::atomic<bool> abort_on_ebadf = { false };
void set_abort_on_ebadf(bool do_abort) {
abort_on_ebadf.store(do_abort);
}
bool is_abort_on_ebadf_enabled() {
return abort_on_ebadf.load();
}
timespec to_timespec(steady_clock_type::time_point t) {
using ns = std::chrono::nanoseconds;
auto n = std::chrono::duration_cast<ns>(t.time_since_epoch()).count();
return { n / 1'000'000'000, n % 1'000'000'000 };
}
void lowres_clock::update() noexcept {
lowres_clock::_now = lowres_clock::time_point(std::chrono::steady_clock::now().time_since_epoch());
lowres_system_clock::_now = lowres_system_clock::time_point(std::chrono::system_clock::now().time_since_epoch());
}
template <typename Clock>
inline
timer<Clock>::~timer() {
if (_queued) {
engine().del_timer(this);
}
}
template <typename Clock>
inline
void timer<Clock>::arm(time_point until, std::optional<duration> period) noexcept {
arm_state(until, period);
engine().add_timer(this);
}
template <typename Clock>
inline
void timer<Clock>::readd_periodic() noexcept {
arm_state(Clock::now() + _period.value(), {_period.value()});
engine().queue_timer(this);
}
template <typename Clock>
inline
bool timer<Clock>::cancel() noexcept {
if (!_armed) {
return false;
}
_armed = false;
if (_queued) {
engine().del_timer(this);
_queued = false;
}
return true;
}
template class timer<steady_clock_type>;
template class timer<lowres_clock>;
template class timer<manual_clock>;
#ifdef SEASTAR_BUILD_SHARED_LIBS
thread_local lowres_clock::time_point lowres_clock::_now;
thread_local lowres_system_clock::time_point lowres_system_clock::_now;
#endif
reactor::signals::signals() : _pending_signals(0) {
}
reactor::signals::~signals() {
sigset_t mask;
sigfillset(&mask);
::pthread_sigmask(SIG_BLOCK, &mask, NULL);
}
reactor::signals::signal_handler::signal_handler(int signo, noncopyable_function<void ()>&& handler)
: _handler(std::move(handler)) {
}
void
reactor::signals::handle_signal(int signo, noncopyable_function<void ()>&& handler) {
signal_handler h(signo, std::move(handler));
auto [_, inserted] = _signal_handlers.insert_or_assign(signo, std::move(h));
if (!inserted) {
// since we register the same handler to OS for all signals, we could
// skip sigaction when a handler has already been registered before.
return;
}
struct sigaction sa;
sa.sa_sigaction = [](int sig, siginfo_t *info, void *p) {
engine()._backend->signal_received(sig, info, p);
};
sa.sa_mask = make_empty_sigset_mask();
sa.sa_flags = SA_SIGINFO | SA_RESTART;
auto r = ::sigaction(signo, &sa, nullptr);
throw_system_error_on(r == -1);
auto mask = make_sigset_mask(signo);
r = ::pthread_sigmask(SIG_UNBLOCK, &mask, NULL);
throw_pthread_error(r);
}
void
reactor::signals::handle_signal_once(int signo, noncopyable_function<void ()>&& handler) {
return handle_signal(signo, [fired = false, handler = std::move(handler)] () mutable {
if (!fired) {
fired = true;
handler();
}
});
}
bool reactor::signals::poll_signal() {
auto signals = _pending_signals.load(std::memory_order_relaxed);
if (signals) {
_pending_signals.fetch_and(~signals, std::memory_order_relaxed);
for (size_t i = 0; i < sizeof(signals)*8; i++) {
if (signals & (1ull << i)) {
_signal_handlers.at(i)._handler();
}
}
}
return signals;
}
bool reactor::signals::pure_poll_signal() const {
return _pending_signals.load(std::memory_order_relaxed);
}
void reactor::signals::action(int signo, siginfo_t* siginfo, void* ignore) {
engine().start_handling_signal();
engine()._signals._pending_signals.fetch_or(1ull << signo, std::memory_order_relaxed);
}
void reactor::signals::failed_to_handle(int signo) {
char tname[64];
pthread_getname_np(pthread_self(), tname, sizeof(tname));
auto tid = syscall(SYS_gettid);
seastar_logger.error("Failed to handle signal {} on thread {} ({}): engine not ready", signo, tid, tname);
}
void reactor::handle_signal(int signo, noncopyable_function<void ()>&& handler) {
_signals.handle_signal(signo, std::move(handler));
}
// Accumulates an in-memory backtrace and flush to stderr eventually.
// Async-signal safe.
class backtrace_buffer {
static constexpr unsigned _max_size = 8 << 10;
unsigned _pos = 0;
char _buf[_max_size];
public:
void flush() noexcept {
print_safe(_buf, _pos);
_pos = 0;
}
void reserve(size_t len) noexcept {
assert(len < _max_size);
if (_pos + len >= _max_size) {
flush();
}
}
void append(const char* str, size_t len) noexcept {
reserve(len);
memcpy(_buf + _pos, str, len);
_pos += len;
}
void append(const char* str) noexcept { append(str, strlen(str)); }
template <typename Integral>
void append_decimal(Integral n) noexcept {
char buf[sizeof(n) * 3];
auto len = convert_decimal_safe(buf, sizeof(buf), n);
append(buf, len);
}
template <typename Integral>
void append_hex(Integral ptr) noexcept {
char buf[sizeof(ptr) * 2];
auto p = convert_hex_safe(buf, sizeof(buf), ptr);
append(p, (buf + sizeof(buf)) - p);
}
void append_backtrace() noexcept {
backtrace([this] (frame f) {
append(" ");
if (!f.so->name.empty()) {
append(f.so->name.c_str(), f.so->name.size());
append("+");
}
append("0x");
append_hex(f.addr);
append("\n");
});
}
void append_backtrace_oneline() noexcept {
backtrace([this] (frame f) noexcept {
reserve(3 + sizeof(f.addr) * 2);
append(" 0x");
append_hex(f.addr);
});
}
};
static void print_with_backtrace(backtrace_buffer& buf, bool oneline) noexcept {
if (local_engine) {
buf.append(" on shard ");
buf.append_decimal(this_shard_id());
buf.append(", in scheduling group ");
buf.append(current_scheduling_group().name().c_str());
}
if (!oneline) {
buf.append(".\nBacktrace:\n");
buf.append_backtrace();
} else {
buf.append(". Backtrace:");
buf.append_backtrace_oneline();
buf.append("\n");
}
buf.flush();
}
static void print_with_backtrace(const char* cause, bool oneline = false) noexcept {
backtrace_buffer buf;
buf.append(cause);
print_with_backtrace(buf, oneline);
}
#if !defined(SEASTAR_ASAN_ENABLED) && !defined(SEASTAR_TSAN_ENABLED)
// Installs signal handler stack for current thread.
// The stack remains installed as long as the returned object is kept alive.
// When it goes out of scope the previous handler is restored.
static decltype(auto) install_signal_handler_stack() {
size_t size = SIGSTKSZ;
auto mem = std::make_unique<char[]>(size);
stack_t stack;
stack_t prev_stack;
stack.ss_sp = mem.get();
stack.ss_flags = 0;
stack.ss_size = size;
auto r = sigaltstack(&stack, &prev_stack);
throw_system_error_on(r == -1);
return defer([mem = std::move(mem), prev_stack] () mutable noexcept {
try {
auto r = sigaltstack(&prev_stack, NULL);
throw_system_error_on(r == -1);
} catch (...) {
mem.release(); // We failed to restore previous stack, must leak it.
seastar_logger.error("Failed to restore signal stack: {}", std::current_exception());
}
});
}
#else
// SIGSTKSZ is too small when using asan. We also don't need to
// handle SIGSEGV ourselves when using asan/tsan, so just don't install
// a signal handler stack.
auto install_signal_handler_stack() {
struct nothing { ~nothing() {} };
return nothing{};
}
#endif
static sstring shorten_name(const sstring& name, size_t length) {
assert(!name.empty());
assert(length > 0);
namespace ba = boost::algorithm;
using split_iter_t = ba::split_iterator<sstring::const_iterator>;
static constexpr auto delimiter = "_";
sstring shortname(typename sstring::initialized_later{}, length);
auto output = shortname.begin();
auto last = shortname.end();
if (name.find(delimiter) == name.npos) {
// use the prefix as the fallback, if the name is not underscore
// delimited
size_t n = std::min(length, name.size());
output = std::copy_n(name.begin(), n, output);
} else {
for (split_iter_t split_it = ba::make_split_iterator(
name,
ba::token_finder(ba::is_any_of("_"),
ba::token_compress_on)), split_last{};
output != last && split_it != split_last;
++split_it) {
auto& part = *split_it;
assert(part.size() > 0);
// convert "hello_world" to "hw"
*output++ = part[0];
}
}
// pad the remaining part with spaces, so the shortened name is always
// of length long.
std::fill(output, last, ' ');
return shortname;
}
reactor::task_queue::task_queue(unsigned id, sstring name, sstring shortname, float shares)
: _shares(std::max(shares, 1.0f))
, _reciprocal_shares_times_2_power_32((uint64_t(1) << 32) / _shares)
, _id(id)
, _ts(now()) {
rename(name, shortname);
}
void
reactor::task_queue::register_stats() {
seastar::metrics::metric_groups new_metrics;
namespace sm = seastar::metrics;
static auto group = sm::label("group");
auto group_label = group(_name);
new_metrics.add_group("scheduler", {
sm::make_counter("runtime_ms", [this] {
return std::chrono::duration_cast<std::chrono::milliseconds>(_runtime).count();
}, sm::description("Accumulated runtime of this task queue; an increment rate of 1000ms per second indicates full utilization"),
{group_label}),
sm::make_counter("waittime_ms", [this] {
return std::chrono::duration_cast<std::chrono::milliseconds>(_waittime).count();
}, sm::description("Accumulated waittime of this task queue; an increment rate of 1000ms per second indicates queue is waiting for something (e.g. IO)"),
{group_label}),
sm::make_counter("starvetime_ms", [this] {
return std::chrono::duration_cast<std::chrono::milliseconds>(_starvetime).count();
}, sm::description("Accumulated starvation time of this task queue; an increment rate of 1000ms per second indicates the scheduler feels really bad"),
{group_label}),
sm::make_counter("tasks_processed", _tasks_processed,
sm::description("Count of tasks executing on this queue; indicates together with runtime_ms indicates length of tasks"),
{group_label}),
sm::make_gauge("queue_length", [this] { return _q.size(); },
sm::description("Size of backlog on this queue, in tasks; indicates whether the queue is busy and/or contended"),
{group_label}),
sm::make_gauge("shares", [this] { return _shares; },
sm::description("Shares allocated to this queue"),
{group_label}),
sm::make_counter("time_spent_on_task_quota_violations_ms", [this] {
return _time_spent_on_task_quota_violations / 1ms;
}, sm::description("Total amount in milliseconds we were in violation of the task quota"),
{group_label}),
});
_metrics = std::exchange(new_metrics, {});
}
void
reactor::task_queue::rename(sstring new_name, sstring new_shortname) {
assert(!new_name.empty());
if (_name != new_name) {
_name = new_name;
if (new_shortname.empty()) {
_shortname = shorten_name(_name, shortname_size);
} else {
_shortname = fmt::format("{:>{}}", new_shortname, shortname_size);
}
register_stats();
}
}
#ifdef __clang__
__attribute__((no_sanitize("undefined"))) // multiplication below may overflow; we check for that
#elif defined(__GNUC__)
[[gnu::no_sanitize_undefined]]