| 6 |
| 7 | #include <stddef.h> |
| 8 |
| 9 | #include <utility> |
| 10 |
| 11 | #include "base/bind.h" |
| 12 | #include "base/bind_helpers.h" |
| 13 | #include "base/callback_helpers.h" |
| 14 | #include "base/feature_list.h" |
| 15 | #include "base/location.h" |
| 16 | #include "base/memory/ref_counted.h" |
| 17 | #include "base/metrics/histogram_macros.h" |
| 18 | #include "base/sequenced_task_runner.h" |
| 19 | #include "base/task/scoped_set_task_priority_for_current_thread.h" |
| 20 | #include "base/task_runner.h" |
| 21 | #include "base/threading/sequenced_task_runner_handle.h" |
| 22 |
| 23 | namespace base { |
| 24 |
| 25 | namespace { |
| 26 |
| 27 | void RunOrPostToTaskRunner(scoped_refptr<SequencedTaskRunner> task_runner, |
| 28 | OnceClosure closure) { |
| 29 | if (task_runner->RunsTasksInCurrentSequence()) |
| 30 | std::move(closure).Run(); |
| 31 | else |
| 32 | task_runner->PostTask(FROM_HERE, std::move(closure)); |
| 33 | } |
| 34 |
| 35 | // TODO(https://crbug.com/1009795): Remove these once we have established |
| 36 | // whether off-sequence cancelation is worthwhile. |
| 37 |
| 38 | // These values are persisted to logs. Entries should not be renumbered and |
| 39 | // numeric values should never be reused. |
| 40 | enum class TaskStatus { |
| 41 | kSameSequenceLive = 0, |
| 42 | kOffSequenceLive = 1, |
| 43 | kSameSequenceCanceled = 2, |
| 44 | kOffSequenceCanceled = 3, |
| 45 | kMaxValue = kOffSequenceCanceled, |
| 46 | }; |
| 47 |
| 48 | void UmaRecordTaskDuration(bool same_sequence, |
| 49 | bool background, |
| 50 | bool canceled, |
| 51 | TimeDelta duration) { |
| 52 | #define DECLARE_HISTOGRAM(suffix) \ |
| 53 | Histogram::FactoryTimeGet( \ |
| 54 | "Scheduler.CancelableTaskTracker.TaskDuration2_" suffix, \ |
| 55 | TimeDelta::FromMilliseconds(1), TimeDelta::FromSeconds(10), 50, \ |
| 56 | Histogram::kUmaTargetedHistogramFlag) |
| 57 |
| 58 | static HistogramBase* histograms[] = { |
| 59 | DECLARE_HISTOGRAM("LiveForegroundOffSequence"), |
| 60 | DECLARE_HISTOGRAM("LiveForegroundSameSequence"), |
| 61 | DECLARE_HISTOGRAM("LiveBackgroundOffSequence"), |
| 62 | DECLARE_HISTOGRAM("LiveBackgroundSameSequence"), |
| 63 | DECLARE_HISTOGRAM("CanceledForegroundOffSequence"), |
| 64 | DECLARE_HISTOGRAM("CanceledForegroundSameSequence"), |
| 65 | DECLARE_HISTOGRAM("CanceledBackgroundOffSequence"), |
| 66 | DECLARE_HISTOGRAM("CanceledBackgroundSameSequence")}; |
| 67 |
| 68 | int i = (same_sequence ? 1 : 0) + (background ? 2 : 0) + (canceled ? 4 : 0); |
| 69 | histograms[i]->AddTimeMillisecondsGranularity(duration); |
| 70 | } |
| 71 |
| 72 | const base::Feature kAllowOffSequenceTaskCancelation{ |
| 73 | "AllowOffSequenceTaskCancelation", base::FEATURE_ENABLED_BY_DEFAULT}; |
| 74 |
| 75 | bool AllowOffSequenceTaskCancelation() { |
| 76 | if (!base::FeatureList::GetInstance()) |
| 77 | return true; |
| 78 | return base::FeatureList::IsEnabled(kAllowOffSequenceTaskCancelation); |
| 79 | } |
| 80 |
| 81 | } // namespace |
| 82 |
| 83 | // static |
| 84 | const CancelableTaskTracker::TaskId CancelableTaskTracker::kBadTaskId = 0; |
| 85 |
| 86 | CancelableTaskTracker::CancelableTaskTracker() { |
| 87 | weak_this_ = weak_factory_.GetWeakPtr(); |
| 88 | } |
| 89 |
| 90 | CancelableTaskTracker::~CancelableTaskTracker() { |
| 91 | DCHECK(sequence_checker_.CalledOnValidSequence()); |
| 92 |
| 93 | TryCancelAll(); |
| 94 | } |
| 95 |
| 96 | CancelableTaskTracker::TaskId CancelableTaskTracker::PostTask( |
| 97 | TaskRunner* task_runner, |
| 98 | const Location& from_here, |
| 99 | OnceClosure task) { |
| 100 | DCHECK(sequence_checker_.CalledOnValidSequence()); |
| 101 | CHECK(weak_this_); |
| 102 |
| 103 | return PostTaskAndReply(task_runner, from_here, std::move(task), DoNothing()); |
| 104 | } |
| 105 |
| 106 | CancelableTaskTracker::TaskId CancelableTaskTracker::PostTaskAndReply( |
| 107 | TaskRunner* task_runner, |
| 108 | const Location& from_here, |
| 109 | OnceClosure task, |
| 110 | OnceClosure reply) { |
| 111 | DCHECK(sequence_checker_.CalledOnValidSequence()); |
| 112 | CHECK(weak_this_); |
| 113 |
| 114 | // We need a SequencedTaskRunnerHandle to run |reply|. |
| 115 | DCHECK(SequencedTaskRunnerHandle::IsSet()); |
| 116 |
| 117 | auto flag = MakeRefCounted<TaskCancellationFlag>(); |
| 118 |
| 119 | TaskId id = next_id_; |
| 120 | next_id_++; // int64_t is big enough that we ignore the potential overflow. |
| 121 |
| 122 | // Unretained(this) is safe because |flag| will have been set to the |
| 123 | // "canceled" state after |this| is deleted. |
| 124 | OnceClosure untrack_closure = |
| 125 | BindOnce(&CancelableTaskTracker::Untrack, Unretained(this), id); |
| 126 | bool success = task_runner->PostTaskAndReply( |
| 127 | from_here, |
| 128 | BindOnce(&RunIfNotCanceled, SequencedTaskRunnerHandle::Get(), flag, |
| 129 | std::move(task)), |
| 130 | BindOnce(&RunThenUntrackIfNotCanceled, SequencedTaskRunnerHandle::Get(), |
| 131 | flag, std::move(reply), std::move(untrack_closure))); |
| 132 |
| 133 | if (!success) |
| 134 | return kBadTaskId; |
| 135 |
| 136 | Track(id, std::move(flag)); |
| 137 | return id; |
| 138 | } |
| 139 |
| 140 | CancelableTaskTracker::TaskId CancelableTaskTracker::NewTrackedTaskId( |
| 141 | IsCanceledCallback* is_canceled_cb) { |
| 142 | DCHECK(sequence_checker_.CalledOnValidSequence()); |
| 143 | DCHECK(SequencedTaskRunnerHandle::IsSet()); |
| 144 |
| 145 | TaskId id = next_id_; |
| 146 | next_id_++; // int64_t is big enough that we ignore the potential overflow. |
| 147 |
| 148 | auto flag = MakeRefCounted<TaskCancellationFlag>(); |
| 149 |
| 150 | // Unretained(this) is safe because |flag| will have been set to the |
| 151 | // "canceled" state after |this| is deleted. |
| 152 | OnceClosure untrack_closure = |
| 153 | BindOnce(&CancelableTaskTracker::Untrack, Unretained(this), id); |
| 154 |
| 155 | // Will always run |untrack_closure| on current sequence. |
| 156 | ScopedClosureRunner untrack_runner( |
| 157 | BindOnce(&RunOrPostToTaskRunner, SequencedTaskRunnerHandle::Get(), |
| 158 | BindOnce(&RunIfNotCanceled, SequencedTaskRunnerHandle::Get(), |
| 159 | flag, std::move(untrack_closure)))); |
| 160 |
| 161 | *is_canceled_cb = BindRepeating(&IsCanceled, SequencedTaskRunnerHandle::Get(), |
| 162 | flag, std::move(untrack_runner)); |
| 163 |
| 164 | Track(id, std::move(flag)); |
| 165 | return id; |
| 166 | } |
| 167 |
| 168 | void CancelableTaskTracker::TryCancel(TaskId id) { |
| 169 | DCHECK(sequence_checker_.CalledOnValidSequence()); |
| 170 |
| 171 | const auto it = task_flags_.find(id); |
| 172 | if (it == task_flags_.end()) { |
| 173 | // Two possibilities: |
| 174 | // |
| 175 | // 1. The task has already been untracked. |
| 176 | // 2. The TaskId is bad or unknown. |
| 177 | // |
| 178 | // Since this function is best-effort, it's OK to ignore these. |
| 179 | return; |
| 180 | } |
| 181 | it->second->data.Set(); |
| 182 |
| 183 | // Remove |id| from |task_flags_| immediately, since we have no further |
| 184 | // use for tracking it. This allows the reply closures (see |
| 185 | // PostTaskAndReply()) for cancelled tasks to be skipped, since they have |
| 186 | // no clean-up to perform. |
| 187 | task_flags_.erase(it); |
| 188 | } |
| 189 |
| 190 | void CancelableTaskTracker::TryCancelAll() { |
| 191 | DCHECK(sequence_checker_.CalledOnValidSequence()); |
| 192 | for (const auto& it : task_flags_) |
| 193 | it.second->data.Set(); |
| 194 | task_flags_.clear(); |
| 195 | } |
| 196 |
| 197 | bool CancelableTaskTracker::HasTrackedTasks() const { |
| 198 | DCHECK(sequence_checker_.CalledOnValidSequence()); |
| 199 | return !task_flags_.empty(); |
| 200 | } |
| 201 |
| 202 | // static |
| 203 | void CancelableTaskTracker::RunIfNotCanceled( |
| 204 | const scoped_refptr<SequencedTaskRunner>& origin_task_runner, |
| 205 | const scoped_refptr<TaskCancellationFlag>& flag, |
| 206 | OnceClosure task) { |
| 207 | // TODO(https://crbug.com/1009795): Record durations for executed tasks, |
| 208 | // correlated with whether the task runs on a background or foreground |
| 209 | // sequence, and whether it is the same sequence as the CancelableTaskTracker. |
| 210 | // Also correlate with whether the task was run despite being canceled, to |
| 211 | // allow an experiment to assess the value of off-sequence cancelation. |
| 212 |
| 213 | // Record canceled & off-sequence status for all tasks. |
| 214 | const bool was_canceled = flag->data.IsSet(); |
| 215 | const bool same_sequence = origin_task_runner->RunsTasksInCurrentSequence(); |
| 216 | const TaskStatus task_status = |
| 217 | was_canceled ? (same_sequence ? TaskStatus::kSameSequenceCanceled |
| 218 | : TaskStatus::kOffSequenceCanceled) |
| 219 | : (same_sequence ? TaskStatus::kSameSequenceLive |
| 220 | : TaskStatus::kOffSequenceLive); |
| 221 | UMA_HISTOGRAM_ENUMERATION("Scheduler.CancelableTaskTracker.TaskStatus", |
| 222 | task_status); |
| 223 |
| 224 | // Skip tasks if they are canceled, taking into account the off-sequence |
| 225 | // cancelation experiment. |
| 226 | const bool skip_task = |
| 227 | was_canceled && (AllowOffSequenceTaskCancelation() || same_sequence); |
| 228 | if (skip_task) |
| 229 | return; |
| 230 |
| 231 | // Run the task and record its duration. |
| 232 | const TimeTicks before_task_ticks = TimeTicks::Now(); |
| 233 | std::move(task).Run(); |
| 234 | const TimeDelta duration = TimeTicks::Now() - before_task_ticks; |
| 235 | const bool is_background = |
| 236 | internal::GetTaskPriorityForCurrentThread() < TaskPriority::USER_VISIBLE; |
| 237 | UmaRecordTaskDuration(same_sequence, is_background, was_canceled, duration); |
| 238 | } |
| 239 |
| 240 | // static |
| 241 | void CancelableTaskTracker::RunThenUntrackIfNotCanceled( |
| 242 | const scoped_refptr<SequencedTaskRunner>& origin_task_runner, |
| 243 | const scoped_refptr<TaskCancellationFlag>& flag, |
| 244 | OnceClosure task, |
| 245 | OnceClosure untrack) { |
| 246 | RunIfNotCanceled(origin_task_runner, flag, std::move(task)); |
| 247 | RunIfNotCanceled(origin_task_runner, flag, std::move(untrack)); |
| 248 | } |
| 249 |
| 250 | // static |
| 251 | bool CancelableTaskTracker::IsCanceled( |
| 252 | const scoped_refptr<SequencedTaskRunner>& origin_task_runner, |
| 253 | const scoped_refptr<TaskCancellationFlag>& flag, |
| 254 | const ScopedClosureRunner& cleanup_runner) { |
| 255 | return flag->data.IsSet() && |
| 256 | (AllowOffSequenceTaskCancelation() || |
| 257 | origin_task_runner->RunsTasksInCurrentSequence()); |
| 258 | } |
| 259 |
| 260 | void CancelableTaskTracker::Track(TaskId id, |
| 261 | scoped_refptr<TaskCancellationFlag> flag) { |
| 262 | DCHECK(sequence_checker_.CalledOnValidSequence()); |
| 263 | CHECK(weak_this_); |
| 264 | bool success = task_flags_.insert(std::make_pair(id, std::move(flag))).second; |
| 265 | DCHECK(success); |
| 266 | } |
| 267 |
| 268 | void CancelableTaskTracker::Untrack(TaskId id) { |
| 269 | DCHECK(sequence_checker_.CalledOnValidSequence()); |
| 270 | CHECK(weak_this_); |
| 271 | size_t num = task_flags_.erase(id); |
| 272 | DCHECK_EQ(1u, num); |
| 273 | } |
| 274 |
| 275 | } // namespace base |
| 276 |