1 /*****************************************************************************
2 
3 Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
4 
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License, version 2.0,
7 as published by the Free Software Foundation.
8 
9 This program is also distributed with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation.  The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have included with MySQL.
15 
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 GNU General Public License, version 2.0, for more details.
20 
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
24 
25 Portions of this file contain modifications contributed and copyrighted by
26 Google, Inc. Those modifications are gratefully acknowledged and are described
27 briefly in the InnoDB documentation. The contributions by Google are
28 incorporated with their permission, and subject to the conditions contained in
29 the file COPYING.Google.
30 
31 *****************************************************************************/
32 
33 /**************************************************/ /**
34  @file include/ut0link_buf.h
35 
36  Link buffer - concurrent data structure which allows:
37          - concurrent addition of links
38          - single-threaded tracking of connected path created by links
39          - limited size of window with holes (missing links)
40 
41  Created 2017-08-30 Paweł Olchawa
42  *******************************************************/
43 
44 #ifndef ut0link_buf_h
45 #define ut0link_buf_h
46 
47 #include <atomic>
48 #include <cstdint>
49 
50 #include "ut0counter.h"
51 #include "ut0dbg.h"
52 #include "ut0new.h"
53 #include "ut0ut.h"
54 
55 /** Concurrent data structure, which allows to track concurrently
56 performed operations which locally might be dis-ordered.
57 
58 This data structure is informed about finished concurrent operations
59 and tracks up to which point in a total order all operations have
60 been finished (there are no holes).
61 
62 It also allows to limit the last period in which there might be holes.
63 These holes refer to unfinished concurrent operations, which preceed
64 in the total order some operations that are already finished.
65 
66 Threads might concurrently report finished operations (lock-free).
67 
68 Threads might ask for maximum currently known position in total order,
69 up to which all operations are already finished (lock-free).
70 
71 Single thread might track the reported finished operations and update
72 maximum position in total order, up to which all operations are done.
73 
74 You might look at current usages of this data structure in log0buf.cc.
75 */
76 template <typename Position = uint64_t>
77 class Link_buf {
78  public:
79   /** Type used to express distance between two positions.
80   It could become a parameter of template if it was useful.
81   However there is no such need currently. */
82   typedef Position Distance;
83 
84   /** Constructs the link buffer. Allocated memory for the links.
85   Initializes the tail pointer with 0.
86 
87   @param[in]	capacity	number of slots in the ring buffer */
88   explicit Link_buf(size_t capacity);
89 
90   Link_buf();
91 
92   Link_buf(Link_buf &&rhs);
93 
94   Link_buf(const Link_buf &rhs) = delete;
95 
96   Link_buf &operator=(Link_buf &&rhs);
97 
98   Link_buf &operator=(const Link_buf &rhs) = delete;
99 
100   /** Destructs the link buffer. Deallocates memory for the links. */
101   ~Link_buf();
102 
103   /** Add a directed link between two given positions. It is user's
104   responsibility to ensure that there is space for the link. This is
105   because it can be useful to ensure much earlier that there is space.
106 
107   @param[in]	from	position where the link starts
108   @param[in]	to	position where the link ends (from -> to) */
109   void add_link(Position from, Position to);
110 
111   /** Advances the tail pointer in the buffer by following connected
112   path created by links. Starts at current position of the pointer.
113   Stops when the provided function returns true.
114 
115   @param[in]	stop_condition	function used as a stop condition;
116                                   (lsn_t prev, lsn_t next) -> bool;
117                                   returns false if we should follow
118                                   the link prev->next, true to stop
119 
120   @return true if and only if the pointer has been advanced */
121   template <typename Stop_condition>
122   bool advance_tail_until(Stop_condition stop_condition);
123 
124   /** Advances the tail pointer in the buffer without additional
125   condition for stop. Stops at missing outgoing link.
126 
127   @see advance_tail_until()
128 
129   @return true if and only if the pointer has been advanced */
130   bool advance_tail();
131 
132   /** @return capacity of the ring buffer */
133   size_t capacity() const;
134 
135   /** @return the tail pointer */
136   Position tail() const;
137 
138   /** Checks if there is space to add link at given position.
139   User has to use this function before adding the link, and
140   should wait until the free space exists.
141 
142   @param[in]	position	position to check
143 
144   @return true if and only if the space is free */
145   bool has_space(Position position) const;
146 
147   /** Validates (using assertions) that there are no links set
148   in the range [begin, end). */
149   void validate_no_links(Position begin, Position end);
150 
151   /** Validates (using assertions) that there no links at all. */
152   void validate_no_links();
153 
154  private:
155   /** Translates position expressed in original unit to position
156   in the m_links (which is a ring buffer).
157 
158   @param[in]	position	position in original unit
159 
160   @return position in the m_links */
161   size_t slot_index(Position position) const;
162 
163   /** Computes next position by looking into slots array and
164   following single link which starts in provided position.
165 
166   @param[in]	position	position to start
167   @param[out]	next		computed next position
168 
169   @return false if there was no link, true otherwise */
170   bool next_position(Position position, Position &next);
171 
172   /** Claims a link starting in provided position that has been
173   traversed and is no longer required (reclaims the slot).
174 
175   @param[in]	position	position where link starts */
176   void claim_position(Position position);
177 
178   /** Deallocated memory, if it was allocated. */
179   void free();
180 
181   /** Capacity of the buffer. */
182   size_t m_capacity;
183 
184   /** Pointer to the ring buffer (unaligned). */
185   std::atomic<Distance> *m_links;
186 
187   /** Tail pointer in the buffer (expressed in original unit). */
188   alignas(ut::INNODB_CACHE_LINE_SIZE) std::atomic<Position> m_tail;
189 };
190 
191 template <typename Position>
Link_buf(size_t capacity)192 Link_buf<Position>::Link_buf(size_t capacity)
193     : m_capacity(capacity), m_tail(0) {
194   if (capacity == 0) {
195     m_links = nullptr;
196     return;
197   }
198 
199   ut_a((capacity & (capacity - 1)) == 0);
200 
201   m_links = UT_NEW_ARRAY_NOKEY(std::atomic<Distance>, capacity);
202 
203   for (size_t i = 0; i < capacity; ++i) {
204     m_links[i].store(0);
205   }
206 }
207 
208 template <typename Position>
Link_buf()209 Link_buf<Position>::Link_buf() : Link_buf(0) {}
210 
211 template <typename Position>
Link_buf(Link_buf && rhs)212 Link_buf<Position>::Link_buf(Link_buf &&rhs)
213     : m_capacity(rhs.m_capacity), m_tail(rhs.m_tail.load()) {
214   m_links = rhs.m_links;
215   rhs.m_links = nullptr;
216 }
217 
218 template <typename Position>
219 Link_buf<Position> &Link_buf<Position>::operator=(Link_buf &&rhs) {
220   free();
221 
222   m_capacity = rhs.m_capacity;
223 
224   m_tail.store(rhs.m_tail.load());
225 
226   m_links = rhs.m_links;
227   rhs.m_links = nullptr;
228 
229   return *this;
230 }
231 
232 template <typename Position>
~Link_buf()233 Link_buf<Position>::~Link_buf() {
234   free();
235 }
236 
237 template <typename Position>
free()238 void Link_buf<Position>::free() {
239   if (m_links != nullptr) {
240     UT_DELETE_ARRAY(m_links);
241     m_links = nullptr;
242   }
243 }
244 
245 template <typename Position>
add_link(Position from,Position to)246 inline void Link_buf<Position>::add_link(Position from, Position to) {
247   ut_ad(to > from);
248   ut_ad(to - from <= std::numeric_limits<Distance>::max());
249 
250   const auto index = slot_index(from);
251 
252   auto &slot = m_links[index];
253 
254   ut_ad(slot.load() == 0);
255 
256   slot.store(to - from);
257 }
258 
259 template <typename Position>
next_position(Position position,Position & next)260 bool Link_buf<Position>::next_position(Position position, Position &next) {
261   const auto index = slot_index(position);
262 
263   auto &slot = m_links[index];
264 
265   const auto distance = slot.load();
266 
267   ut_ad(position < std::numeric_limits<Position>::max() - distance);
268 
269   next = position + distance;
270 
271   return distance == 0;
272 }
273 
274 template <typename Position>
claim_position(Position position)275 void Link_buf<Position>::claim_position(Position position) {
276   const auto index = slot_index(position);
277 
278   auto &slot = m_links[index];
279 
280   slot.store(0);
281 }
282 
283 template <typename Position>
284 template <typename Stop_condition>
advance_tail_until(Stop_condition stop_condition)285 bool Link_buf<Position>::advance_tail_until(Stop_condition stop_condition) {
286   auto position = m_tail.load();
287 
288   while (true) {
289     Position next;
290 
291     bool stop = next_position(position, next);
292 
293     if (stop || stop_condition(position, next)) {
294       break;
295     }
296 
297     /* Reclaim the slot. */
298     claim_position(position);
299 
300     position = next;
301   }
302 
303   if (position > m_tail.load()) {
304     m_tail.store(position);
305 
306     return true;
307 
308   } else {
309     return false;
310   }
311 }
312 
313 template <typename Position>
advance_tail()314 inline bool Link_buf<Position>::advance_tail() {
315   auto stop_condition = [](Position from, Position to) { return (to == from); };
316 
317   return advance_tail_until(stop_condition);
318 }
319 
320 template <typename Position>
capacity()321 inline size_t Link_buf<Position>::capacity() const {
322   return m_capacity;
323 }
324 
325 template <typename Position>
tail()326 inline Position Link_buf<Position>::tail() const {
327   return m_tail.load();
328 }
329 
330 template <typename Position>
has_space(Position position)331 inline bool Link_buf<Position>::has_space(Position position) const {
332   return tail() + m_capacity > position;
333 }
334 
335 template <typename Position>
slot_index(Position position)336 inline size_t Link_buf<Position>::slot_index(Position position) const {
337   return position & (m_capacity - 1);
338 }
339 
340 template <typename Position>
validate_no_links(Position begin,Position end)341 void Link_buf<Position>::validate_no_links(Position begin, Position end) {
342   /* After m_capacity iterations we would have all slots tested. */
343 
344   end = std::min(end, begin + m_capacity);
345 
346   for (; begin < end; ++begin) {
347     const size_t index = slot_index(begin);
348 
349     const auto &slot = m_links[index];
350 
351     ut_a(slot.load() == 0);
352   }
353 }
354 
355 template <typename Position>
validate_no_links()356 void Link_buf<Position>::validate_no_links() {
357   validate_no_links(0, m_capacity);
358 }
359 
360 #endif /* ut0link_buf_h */
361