lf_alloc-pin.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /* QQ: TODO multi-pinbox */
  2. /* Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License, version 2.0,
  5. as published by the Free Software Foundation.
  6. This program is also distributed with certain software (including
  7. but not limited to OpenSSL) that is licensed under separate terms,
  8. as designated in a particular file or component or in included license
  9. documentation. The authors of MySQL hereby grant you an additional
  10. permission to link the program and your derivative works with the
  11. separately licensed software that they have included with MySQL.
  12. Without limiting anything contained in the foregoing, this file,
  13. which is part of C Driver for MySQL (Connector/C), is also subject to the
  14. Universal FOSS Exception, version 1.0, a copy of which can be found at
  15. http://oss.oracle.com/licenses/universal-foss-exception.
  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. You should have received a copy of the GNU General Public License
  21. along with this program; if not, write to the Free Software
  22. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
  23. #include <stddef.h>
  24. #include <sys/types.h>
  25. #include <atomic>
  26. static_assert(sizeof(std::atomic<void *>) == sizeof(void *),
  27. "We happily cast to and from std::atomic<void *>, so they need "
  28. "to be at least"
  29. "nominally compatible.");
  30. /**
  31. @file mysys/lf_alloc-pin.cc
  32. wait-free concurrent allocator based on pinning addresses.
  33. It works as follows: every thread (strictly speaking - every CPU, but
  34. it's too difficult to do) has a small array of pointers. They're called
  35. "pins". Before using an object its address must be stored in this array
  36. (pinned). When an object is no longer necessary its address must be
  37. removed from this array (unpinned). When a thread wants to free() an
  38. object it scans all pins of all threads to see if somebody has this
  39. object pinned. If yes - the object is not freed (but stored in a
  40. "purgatory"). To reduce the cost of a single free() pins are not scanned
  41. on every free() but only added to (thread-local) purgatory. On every
  42. LF_PURGATORY_SIZE free() purgatory is scanned and all unpinned objects
  43. are freed.
  44. Pins are used to solve ABA problem. To use pins one must obey
  45. a pinning protocol:
  46. 1. Let's assume that PTR is a shared pointer to an object. Shared means
  47. that any thread may modify it anytime to point to a different object
  48. and free the old object. Later the freed object may be potentially
  49. allocated by another thread. If we're unlucky that other thread may
  50. set PTR to point to this object again. This is ABA problem.
  51. 2. Create a local pointer LOCAL_PTR.
  52. 3. Pin the PTR in a loop:
  53. do
  54. {
  55. LOCAL_PTR= PTR;
  56. pin(PTR, PIN_NUMBER);
  57. } while (LOCAL_PTR != PTR)
  58. 4. It is guaranteed that after the loop has ended, LOCAL_PTR
  59. points to an object (or NULL, if PTR may be NULL), that
  60. will never be freed. It is not guaranteed though
  61. that LOCAL_PTR == PTR (as PTR can change any time)
  62. 5. When done working with the object, remove the pin:
  63. unpin(PIN_NUMBER)
  64. 6. When copying pins (as in the list traversing loop:
  65. pin(CUR, 1);
  66. while ()
  67. {
  68. do // standard
  69. { // pinning
  70. NEXT=CUR->next; // loop
  71. pin(NEXT, 0); // see #3
  72. } while (NEXT != CUR->next); // above
  73. ...
  74. ...
  75. CUR=NEXT;
  76. pin(CUR, 1); // copy pin[0] to pin[1]
  77. }
  78. which keeps CUR address constantly pinned), note than pins may be
  79. copied only upwards (!!!), that is pin[N] to pin[M], M > N.
  80. 7. Don't keep the object pinned longer than necessary - the number of
  81. pins you have is limited (and small), keeping an object pinned
  82. prevents its reuse and cause unnecessary mallocs.
  83. Explanations:
  84. 3. The loop is important. The following can occur:
  85. thread1> LOCAL_PTR= PTR
  86. thread2> free(PTR); PTR=0;
  87. thread1> pin(PTR, PIN_NUMBER);
  88. now thread1 cannot access LOCAL_PTR, even if it's pinned,
  89. because it points to a freed memory. That is, it *must*
  90. verify that it has indeed pinned PTR, the shared pointer.
  91. 6. When a thread wants to free some LOCAL_PTR, and it scans
  92. all lists of pins to see whether it's pinned, it does it
  93. upwards, from low pin numbers to high. Thus another thread
  94. must copy an address from one pin to another in the same
  95. direction - upwards, otherwise the scanning thread may
  96. miss it.
  97. Implementation details:
  98. Pins are given away from a "pinbox". Pinbox is stack-based allocator.
  99. It used dynarray for storing pins, new elements are allocated by dynarray
  100. as necessary, old are pushed in the stack for reuse. ABA is solved by
  101. versioning a pointer - because we use an array, a pointer to pins is 16 bit,
  102. upper 16 bits are used for a version.
  103. */
  104. #include "lf.h"
  105. #include "my_atomic.h"
  106. #include "my_compiler.h"
  107. #include "my_dbug.h"
  108. #include "my_inttypes.h"
  109. #include "my_sys.h"
  110. #include "my_thread.h"
  111. #include "mysql/service_mysql_alloc.h"
  112. #include "mysys/mysys_priv.h" /* key_memory_lf_node */
  113. #define LF_PINBOX_MAX_PINS 65536
  114. static void lf_pinbox_real_free(LF_PINS *pins);
  115. /*
  116. Initialize a pinbox. Normally called from lf_alloc_init.
  117. See the latter for details.
  118. */
  119. void lf_pinbox_init(LF_PINBOX *pinbox, uint free_ptr_offset,
  120. lf_pinbox_free_func *free_func, void *free_func_arg) {
  121. DBUG_ASSERT(free_ptr_offset % sizeof(void *) == 0);
  122. static_assert(sizeof(LF_PINS) == 64, "");
  123. lf_dynarray_init(&pinbox->pinarray, sizeof(LF_PINS));
  124. pinbox->pinstack_top_ver = 0;
  125. pinbox->pins_in_array = 0;
  126. pinbox->free_ptr_offset = free_ptr_offset;
  127. pinbox->free_func = free_func;
  128. pinbox->free_func_arg = free_func_arg;
  129. }
  130. void lf_pinbox_destroy(LF_PINBOX *pinbox) {
  131. lf_dynarray_destroy(&pinbox->pinarray);
  132. }
  133. /*
  134. Get pins from a pinbox.
  135. SYNOPSYS
  136. pinbox -
  137. DESCRIPTION
  138. get a new LF_PINS structure from a stack of unused pins,
  139. or allocate a new one out of dynarray.
  140. */
  141. LF_PINS *lf_pinbox_get_pins(LF_PINBOX *pinbox) {
  142. uint32 pins, next, top_ver;
  143. LF_PINS *el;
  144. /*
  145. We have an array of max. 64k elements.
  146. The highest index currently allocated is pinbox->pins_in_array.
  147. Freed elements are in a lifo stack, pinstack_top_ver.
  148. pinstack_top_ver is 32 bits; 16 low bits are the index in the
  149. array, to the first element of the list. 16 high bits are a version
  150. (every time the 16 low bits are updated, the 16 high bits are
  151. incremented). Versioning prevents the ABA problem.
  152. */
  153. top_ver = pinbox->pinstack_top_ver;
  154. do {
  155. if (!(pins = top_ver % LF_PINBOX_MAX_PINS)) {
  156. /* the stack of free elements is empty */
  157. pins = pinbox->pins_in_array.fetch_add(1) + 1;
  158. if (unlikely(pins >= LF_PINBOX_MAX_PINS)) {
  159. return 0;
  160. }
  161. /*
  162. note that the first allocated element has index 1 (pins==1).
  163. index 0 is reserved to mean "NULL pointer"
  164. */
  165. el = (LF_PINS *)lf_dynarray_lvalue(&pinbox->pinarray, pins);
  166. if (unlikely(!el)) {
  167. return 0;
  168. }
  169. break;
  170. }
  171. el = (LF_PINS *)lf_dynarray_value(&pinbox->pinarray, pins);
  172. next = el->link;
  173. } while (!atomic_compare_exchange_strong(
  174. &pinbox->pinstack_top_ver, &top_ver,
  175. top_ver - pins + next + LF_PINBOX_MAX_PINS));
  176. /*
  177. set el->link to the index of el in the dynarray (el->link has two usages:
  178. - if element is allocated, it's its own index
  179. - if element is free, it's its next element in the free stack
  180. */
  181. el->link = pins;
  182. el->purgatory_count = 0;
  183. el->pinbox = pinbox;
  184. return el;
  185. }
  186. /*
  187. Put pins back to a pinbox.
  188. DESCRIPTION
  189. empty the purgatory (XXX deadlock warning below!),
  190. push LF_PINS structure to a stack
  191. */
  192. void lf_pinbox_put_pins(LF_PINS *pins) {
  193. LF_PINBOX *pinbox = pins->pinbox;
  194. uint32 top_ver, nr;
  195. nr = pins->link;
  196. #ifndef DBUG_OFF
  197. {
  198. /* This thread should not hold any pin. */
  199. int i;
  200. for (i = 0; i < LF_PINBOX_PINS; i++) {
  201. DBUG_ASSERT(pins->pin[i] == 0);
  202. }
  203. }
  204. #endif /* DBUG_OFF */
  205. /*
  206. XXX this will deadlock if other threads will wait for
  207. the caller to do something after _lf_pinbox_put_pins(),
  208. and they would have pinned addresses that the caller wants to free.
  209. Thus: only free pins when all work is done and nobody can wait for you!!!
  210. */
  211. while (pins->purgatory_count) {
  212. lf_pinbox_real_free(pins);
  213. if (pins->purgatory_count) {
  214. my_thread_yield();
  215. }
  216. }
  217. top_ver = pinbox->pinstack_top_ver;
  218. do {
  219. pins->link = top_ver % LF_PINBOX_MAX_PINS;
  220. } while (!atomic_compare_exchange_strong(
  221. &pinbox->pinstack_top_ver, &top_ver,
  222. top_ver - pins->link + nr + LF_PINBOX_MAX_PINS));
  223. }
  224. /*
  225. Get the next pointer in the purgatory list.
  226. Note that next_node is not used to avoid the extra volatile.
  227. */
  228. #define pnext_node(P, X) (*((void **)(((char *)(X)) + (P)->free_ptr_offset)))
  229. static inline void add_to_purgatory(LF_PINS *pins, void *addr) {
  230. pnext_node(pins->pinbox, addr) = pins->purgatory;
  231. pins->purgatory = addr;
  232. pins->purgatory_count++;
  233. }
  234. /*
  235. Free an object allocated via pinbox allocator
  236. DESCRIPTION
  237. add an object to purgatory. if necessary, call lf_pinbox_real_free()
  238. to actually free something.
  239. */
  240. void lf_pinbox_free(LF_PINS *pins, void *addr) {
  241. add_to_purgatory(pins, addr);
  242. if (pins->purgatory_count % LF_PURGATORY_SIZE == 0) {
  243. lf_pinbox_real_free(pins);
  244. }
  245. }
  246. struct st_match_and_save_arg {
  247. LF_PINS *pins;
  248. LF_PINBOX *pinbox;
  249. void *old_purgatory;
  250. };
  251. /*
  252. Callback for lf_dynarray_iterate:
  253. Scan all pins of all threads, for each active (non-null) pin,
  254. scan the current thread's purgatory. If present there, move it
  255. to a new purgatory. At the end, the old purgatory will contain
  256. pointers not pinned by any thread.
  257. */
  258. static int match_and_save(void *v_el, void *v_arg) {
  259. LF_PINS *el = static_cast<LF_PINS *>(v_el);
  260. st_match_and_save_arg *arg = static_cast<st_match_and_save_arg *>(v_arg);
  261. int i;
  262. LF_PINS *el_end = el + LF_DYNARRAY_LEVEL_LENGTH;
  263. for (; el < el_end; el++) {
  264. for (i = 0; i < LF_PINBOX_PINS; i++) {
  265. void *p = el->pin[i];
  266. if (p) {
  267. void *cur = arg->old_purgatory;
  268. void **list_prev = &arg->old_purgatory;
  269. while (cur) {
  270. void *next = pnext_node(arg->pinbox, cur);
  271. if (p == cur) {
  272. /* pinned - keeping */
  273. add_to_purgatory(arg->pins, cur);
  274. /* unlink from old purgatory */
  275. *list_prev = next;
  276. } else {
  277. list_prev = (void **)((char *)cur + arg->pinbox->free_ptr_offset);
  278. }
  279. cur = next;
  280. }
  281. if (!arg->old_purgatory) {
  282. return 1;
  283. }
  284. }
  285. }
  286. }
  287. return 0;
  288. }
  289. /*
  290. Scan the purgatory and free everything that can be freed
  291. */
  292. static void lf_pinbox_real_free(LF_PINS *pins) {
  293. LF_PINBOX *pinbox = pins->pinbox;
  294. /* Store info about current purgatory. */
  295. struct st_match_and_save_arg arg = {pins, pinbox, pins->purgatory};
  296. /* Reset purgatory. */
  297. pins->purgatory = NULL;
  298. pins->purgatory_count = 0;
  299. lf_dynarray_iterate(&pinbox->pinarray, match_and_save, &arg);
  300. if (arg.old_purgatory) {
  301. /* Some objects in the old purgatory were not pinned, free them. */
  302. void *last = arg.old_purgatory;
  303. while (pnext_node(pinbox, last)) {
  304. last = pnext_node(pinbox, last);
  305. }
  306. pinbox->free_func(arg.old_purgatory, last, pinbox->free_func_arg);
  307. }
  308. }
  309. static inline std::atomic<uchar *> &next_node(LF_PINBOX *P, uchar *X) {
  310. std::atomic<uchar *> *free_ptr =
  311. (std::atomic<uchar *> *)(X + P->free_ptr_offset);
  312. return *free_ptr;
  313. }
  314. #define anext_node(X) next_node(&allocator->pinbox, (X))
  315. /* lock-free memory allocator for fixed-size objects */
  316. LF_REQUIRE_PINS(1)
  317. /*
  318. callback for lf_pinbox_real_free to free a list of unpinned objects -
  319. add it back to the allocator stack
  320. DESCRIPTION
  321. 'first' and 'last' are the ends of the linked list of nodes:
  322. first->el->el->....->el->last. Use first==last to free only one element.
  323. */
  324. static void alloc_free(void *v_first, void *v_last, void *v_allocator) {
  325. uchar *first = static_cast<uchar *>(v_first);
  326. uchar *last = static_cast<uchar *>(v_last);
  327. LF_ALLOCATOR *allocator = static_cast<LF_ALLOCATOR *>(v_allocator);
  328. uchar *node = allocator->top;
  329. do {
  330. anext_node(last) = node;
  331. } while (!atomic_compare_exchange_strong(&allocator->top, &node, first) &&
  332. LF_BACKOFF);
  333. }
  334. /**
  335. Initialize lock-free allocator.
  336. @param allocator Allocator structure to initialize.
  337. @param size A size of an object to allocate.
  338. @param free_ptr_offset An offset inside the object to a sizeof(void *)
  339. memory that is guaranteed to be unused after
  340. the object is put in the purgatory. Unused by
  341. ANY thread, not only the purgatory owner.
  342. This memory will be used to link
  343. waiting-to-be-freed objects in a purgatory list.
  344. @param ctor Function to be called after object was
  345. malloc()'ed.
  346. @param dtor Function to be called before object is free()'d.
  347. */
  348. void lf_alloc_init2(LF_ALLOCATOR *allocator, uint size, uint free_ptr_offset,
  349. lf_allocator_func *ctor, lf_allocator_func *dtor) {
  350. lf_pinbox_init(&allocator->pinbox, free_ptr_offset, alloc_free, allocator);
  351. allocator->top = 0;
  352. allocator->mallocs = 0;
  353. allocator->element_size = size;
  354. allocator->constructor = ctor;
  355. allocator->destructor = dtor;
  356. DBUG_ASSERT(size >= sizeof(void *) + free_ptr_offset);
  357. }
  358. /*
  359. destroy the allocator, free everything that's in it
  360. NOTE
  361. As every other init/destroy function here and elsewhere it
  362. is not thread safe. No, this function is no different, ensure
  363. that no thread needs the allocator before destroying it.
  364. We are not responsible for any damage that may be caused by
  365. accessing the allocator when it is being or has been destroyed.
  366. Oh yes, and don't put your cat in a microwave.
  367. */
  368. void lf_alloc_destroy(LF_ALLOCATOR *allocator) {
  369. uchar *node = allocator->top;
  370. while (node) {
  371. uchar *tmp = anext_node(node);
  372. if (allocator->destructor) {
  373. allocator->destructor(node);
  374. }
  375. my_free(node);
  376. node = tmp;
  377. }
  378. lf_pinbox_destroy(&allocator->pinbox);
  379. allocator->top = 0;
  380. }
  381. /*
  382. Allocate and return an new object.
  383. DESCRIPTION
  384. Pop an unused object from the stack or malloc it is the stack is empty.
  385. pin[0] is used, it's removed on return.
  386. */
  387. void *lf_alloc_new(LF_PINS *pins) {
  388. LF_ALLOCATOR *allocator = (LF_ALLOCATOR *)(pins->pinbox->free_func_arg);
  389. uchar *node;
  390. for (;;) {
  391. do {
  392. node = allocator->top;
  393. lf_pin(pins, 0, node);
  394. } while (node != allocator->top && LF_BACKOFF);
  395. if (!node) {
  396. node = static_cast<uchar *>(
  397. my_malloc(key_memory_lf_node, allocator->element_size, MYF(MY_WME)));
  398. if (allocator->constructor) {
  399. allocator->constructor(node);
  400. }
  401. #ifdef MY_LF_EXTRA_DEBUG
  402. if (likely(node != 0)) {
  403. ++allocator->mallocs;
  404. }
  405. #endif
  406. break;
  407. }
  408. if (atomic_compare_exchange_strong(&allocator->top, &node,
  409. anext_node(node).load())) {
  410. break;
  411. }
  412. }
  413. lf_unpin(pins, 0);
  414. return node;
  415. }
  416. /*
  417. count the number of objects in a pool.
  418. NOTE
  419. This is NOT thread-safe !!!
  420. */
  421. uint lf_alloc_pool_count(LF_ALLOCATOR *allocator) {
  422. uint i;
  423. uchar *node;
  424. for (node = allocator->top, i = 0; node; node = anext_node(node), i++)
  425. /* no op */;
  426. return i;
  427. }