1 // Copyright 2021 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #include "pw_multisink/multisink.h"
15
16 #include <cstring>
17
18 #include "pw_assert/check.h"
19 #include "pw_bytes/span.h"
20 #include "pw_function/function.h"
21 #include "pw_log/log.h"
22 #include "pw_result/result.h"
23 #include "pw_status/status.h"
24 #include "pw_status/try.h"
25 #include "pw_varint/varint.h"
26
27 namespace pw {
28 namespace multisink {
29
HandleEntry(ConstByteSpan entry)30 void MultiSink::HandleEntry(ConstByteSpan entry) {
31 std::lock_guard lock(lock_);
32 const Status push_back_status = ring_buffer_.PushBack(entry, sequence_id_++);
33 PW_DCHECK_OK(push_back_status);
34 NotifyListeners();
35 }
36
HandleDropped(uint32_t drop_count)37 void MultiSink::HandleDropped(uint32_t drop_count) {
38 std::lock_guard lock(lock_);
39 // Updating the sequence ID helps identify where the ingress drop happend when
40 // a drain peeks or pops.
41 sequence_id_ += drop_count;
42 total_ingress_drops_ += drop_count;
43 NotifyListeners();
44 }
45
PopEntry(Drain & drain,const Drain::PeekedEntry & entry)46 Status MultiSink::PopEntry(Drain& drain, const Drain::PeekedEntry& entry) {
47 std::lock_guard lock(lock_);
48 PW_DCHECK_PTR_EQ(drain.multisink_, this);
49
50 // Ignore the call if the entry has been handled already.
51 if (entry.sequence_id() == drain.last_handled_sequence_id_) {
52 return OkStatus();
53 }
54
55 uint32_t next_entry_sequence_id;
56 Status peek_status = drain.reader_.PeekFrontPreamble(next_entry_sequence_id);
57 if (!peek_status.ok()) {
58 // Ignore errors if the multisink is empty.
59 if (peek_status.IsOutOfRange()) {
60 return OkStatus();
61 }
62 return peek_status;
63 }
64 if (next_entry_sequence_id == entry.sequence_id()) {
65 // A crash should not happen, since the peek was successful and `lock_` is
66 // still held, there shouldn't be any modifications to the multisink in
67 // between peeking and popping.
68 PW_CHECK_OK(drain.reader_.PopFront());
69 }
70 // If the entry's sequence id is not the next one it means that the
71 // multisink advanced since PeekEntry() was called. Advance the last handled
72 // sequence id to the passed entry anyway to mark the fact that the dropped
73 // messages reported on PeekEntry() are handled.
74 drain.last_handled_sequence_id_ = entry.sequence_id();
75 return OkStatus();
76 }
77
PeekOrPopEntry(Drain & drain,ByteSpan buffer,Request request,uint32_t & drain_drop_count_out,uint32_t & ingress_drop_count_out,uint32_t & entry_sequence_id_out)78 Result<ConstByteSpan> MultiSink::PeekOrPopEntry(
79 Drain& drain,
80 ByteSpan buffer,
81 Request request,
82 uint32_t& drain_drop_count_out,
83 uint32_t& ingress_drop_count_out,
84 uint32_t& entry_sequence_id_out) {
85 size_t bytes_read = 0;
86 entry_sequence_id_out = 0;
87 drain_drop_count_out = 0;
88 ingress_drop_count_out = 0;
89
90 std::lock_guard lock(lock_);
91 PW_DCHECK_PTR_EQ(drain.multisink_, this);
92
93 const Status peek_status = drain.reader_.PeekFrontWithPreamble(
94 buffer, entry_sequence_id_out, bytes_read);
95
96 if (peek_status.IsOutOfRange()) {
97 // If the drain has caught up, report the last handled sequence ID so that
98 // it can still process any dropped entries.
99 entry_sequence_id_out = sequence_id_ - 1;
100 } else if (!peek_status.ok()) {
101 // Discard the entry if the result isn't OK or OUT_OF_RANGE and exit, as the
102 // entry_sequence_id_out cannot be used for computation. Later invocations
103 // will calculate the drop count.
104 PW_CHECK(drain.reader_.PopFront().ok());
105 return peek_status;
106 }
107
108 // Compute the drop count delta by comparing this entry's sequence ID with the
109 // last sequence ID this drain successfully read.
110 //
111 // The drop count calculation simply computes the difference between the
112 // current and last sequence IDs. Consecutive successful reads will always
113 // differ by one at least, so it is subtracted out. If the read was not
114 // successful, the difference is not adjusted.
115 drain_drop_count_out = entry_sequence_id_out -
116 drain.last_handled_sequence_id_ -
117 (peek_status.ok() ? 1 : 0);
118
119 // Only report the ingress drop count when the drain catches up to where the
120 // drop happened, accounting only for the drops found and no more, as
121 // indicated by the gap in sequence IDs.
122 if (drain_drop_count_out > 0) {
123 ingress_drop_count_out =
124 std::min(drain_drop_count_out,
125 total_ingress_drops_ - drain.last_handled_ingress_drop_count_);
126 // Remove the ingress drop count duplicated in drain_drop_count_out.
127 drain_drop_count_out -= ingress_drop_count_out;
128 // Check if all the ingress drops were reported.
129 drain.last_handled_ingress_drop_count_ =
130 total_ingress_drops_ > ingress_drop_count_out
131 ? total_ingress_drops_ - ingress_drop_count_out
132 : total_ingress_drops_;
133 }
134
135 // The Peek above may have failed due to OutOfRange, now that we've set the
136 // drop count see if we should return before attempting to pop.
137 if (peek_status.IsOutOfRange()) {
138 // No more entries, update the drain.
139 drain.last_handled_sequence_id_ = entry_sequence_id_out;
140 return peek_status;
141 }
142 if (request == Request::kPop) {
143 PW_CHECK(drain.reader_.PopFront().ok());
144 drain.last_handled_sequence_id_ = entry_sequence_id_out;
145 }
146 return as_bytes(buffer.first(bytes_read));
147 }
148
AttachDrain(Drain & drain)149 void MultiSink::AttachDrain(Drain& drain) {
150 std::lock_guard lock(lock_);
151 PW_DCHECK_PTR_EQ(drain.multisink_, nullptr);
152 drain.multisink_ = this;
153
154 PW_CHECK_OK(ring_buffer_.AttachReader(drain.reader_));
155 if (&drain == &oldest_entry_drain_) {
156 drain.last_handled_sequence_id_ = sequence_id_ - 1;
157 } else {
158 drain.last_handled_sequence_id_ =
159 oldest_entry_drain_.last_handled_sequence_id_;
160 }
161 drain.last_peek_sequence_id_ = drain.last_handled_sequence_id_;
162 drain.last_handled_ingress_drop_count_ = 0;
163 }
164
DetachDrain(Drain & drain)165 void MultiSink::DetachDrain(Drain& drain) {
166 std::lock_guard lock(lock_);
167 PW_DCHECK_PTR_EQ(drain.multisink_, this);
168 drain.multisink_ = nullptr;
169 PW_CHECK_OK(ring_buffer_.DetachReader(drain.reader_),
170 "The drain wasn't already attached.");
171 }
172
AttachListener(Listener & listener)173 void MultiSink::AttachListener(Listener& listener) {
174 std::lock_guard lock(lock_);
175 listeners_.push_back(listener);
176 // Notify the newly added entry, in case there are items in the sink.
177 listener.OnNewEntryAvailable();
178 }
179
DetachListener(Listener & listener)180 void MultiSink::DetachListener(Listener& listener) {
181 std::lock_guard lock(lock_);
182 [[maybe_unused]] bool was_detached = listeners_.remove(listener);
183 PW_DCHECK(was_detached, "The listener was already attached.");
184 }
185
Clear()186 void MultiSink::Clear() {
187 std::lock_guard lock(lock_);
188 ring_buffer_.Clear();
189 }
190
NotifyListeners()191 void MultiSink::NotifyListeners() {
192 for (auto& listener : listeners_) {
193 listener.OnNewEntryAvailable();
194 }
195 }
196
UnsafeForEachEntry(const Function<void (ConstByteSpan)> & callback,size_t max_num_entries)197 Status MultiSink::UnsafeForEachEntry(
198 const Function<void(ConstByteSpan)>& callback, size_t max_num_entries) {
199 MultiSink::UnsafeIterationWrapper multisink_iteration = UnsafeIteration();
200
201 // First count the number of entries.
202 size_t num_entries = 0;
203 for ([[maybe_unused]] ConstByteSpan entry : multisink_iteration) {
204 num_entries++;
205 }
206
207 // Log up to the max number of logs to avoid overflowing the crash log
208 // writer.
209 const size_t first_logged_offset =
210 max_num_entries > num_entries ? 0 : num_entries - max_num_entries;
211 pw::multisink::MultiSink::iterator it = multisink_iteration.begin();
212 for (size_t offset = 0; it != multisink_iteration.end(); ++it, ++offset) {
213 if (offset < first_logged_offset) {
214 continue; // Skip this log.
215 }
216 callback(*it);
217 }
218 if (!it.status().ok()) {
219 PW_LOG_WARN("Multisink corruption detected, some entries may be missing");
220 return Status::DataLoss();
221 }
222
223 return OkStatus();
224 }
225
PopEntry(const PeekedEntry & entry)226 Status MultiSink::Drain::PopEntry(const PeekedEntry& entry) {
227 PW_DCHECK_NOTNULL(multisink_);
228 return multisink_->PopEntry(*this, entry);
229 }
230
PeekEntry(ByteSpan buffer,uint32_t & drain_drop_count_out,uint32_t & ingress_drop_count_out)231 Result<MultiSink::Drain::PeekedEntry> MultiSink::Drain::PeekEntry(
232 ByteSpan buffer,
233 uint32_t& drain_drop_count_out,
234 uint32_t& ingress_drop_count_out) {
235 PW_DCHECK_NOTNULL(multisink_);
236 uint32_t entry_sequence_id_out;
237 Result<ConstByteSpan> peek_result =
238 multisink_->PeekOrPopEntry(*this,
239 buffer,
240 Request::kPeek,
241 drain_drop_count_out,
242 ingress_drop_count_out,
243 entry_sequence_id_out);
244 if (!peek_result.ok()) {
245 return peek_result.status();
246 }
247 return PeekedEntry(peek_result.value(), entry_sequence_id_out);
248 }
249
PopEntry(ByteSpan buffer,uint32_t & drain_drop_count_out,uint32_t & ingress_drop_count_out)250 Result<ConstByteSpan> MultiSink::Drain::PopEntry(
251 ByteSpan buffer,
252 uint32_t& drain_drop_count_out,
253 uint32_t& ingress_drop_count_out) {
254 PW_DCHECK_NOTNULL(multisink_);
255 uint32_t entry_sequence_id_out;
256 return multisink_->PeekOrPopEntry(*this,
257 buffer,
258 Request::kPop,
259 drain_drop_count_out,
260 ingress_drop_count_out,
261 entry_sequence_id_out);
262 }
263
264 } // namespace multisink
265 } // namespace pw
266