1
0

zstd_cwksp.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. /*
  2. * Copyright (c) Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #ifndef ZSTD_CWKSP_H
  11. #define ZSTD_CWKSP_H
  12. /*-*************************************
  13. * Dependencies
  14. ***************************************/
  15. #include "../common/zstd_internal.h"
  16. #if defined (__cplusplus)
  17. extern "C" {
  18. #endif
  19. /*-*************************************
  20. * Constants
  21. ***************************************/
  22. /* Since the workspace is effectively its own little malloc implementation /
  23. * arena, when we run under ASAN, we should similarly insert redzones between
  24. * each internal element of the workspace, so ASAN will catch overruns that
  25. * reach outside an object but that stay inside the workspace.
  26. *
  27. * This defines the size of that redzone.
  28. */
  29. #ifndef ZSTD_CWKSP_ASAN_REDZONE_SIZE
  30. #define ZSTD_CWKSP_ASAN_REDZONE_SIZE 128
  31. #endif
  32. /* Set our tables and aligneds to align by 64 bytes */
  33. #define ZSTD_CWKSP_ALIGNMENT_BYTES 64
  34. /*-*************************************
  35. * Structures
  36. ***************************************/
  37. typedef enum {
  38. ZSTD_cwksp_alloc_objects,
  39. ZSTD_cwksp_alloc_buffers,
  40. ZSTD_cwksp_alloc_aligned
  41. } ZSTD_cwksp_alloc_phase_e;
  42. /**
  43. * Used to describe whether the workspace is statically allocated (and will not
  44. * necessarily ever be freed), or if it's dynamically allocated and we can
  45. * expect a well-formed caller to free this.
  46. */
  47. typedef enum {
  48. ZSTD_cwksp_dynamic_alloc,
  49. ZSTD_cwksp_static_alloc
  50. } ZSTD_cwksp_static_alloc_e;
  51. /**
  52. * Zstd fits all its internal datastructures into a single continuous buffer,
  53. * so that it only needs to perform a single OS allocation (or so that a buffer
  54. * can be provided to it and it can perform no allocations at all). This buffer
  55. * is called the workspace.
  56. *
  57. * Several optimizations complicate that process of allocating memory ranges
  58. * from this workspace for each internal datastructure:
  59. *
  60. * - These different internal datastructures have different setup requirements:
  61. *
  62. * - The static objects need to be cleared once and can then be trivially
  63. * reused for each compression.
  64. *
  65. * - Various buffers don't need to be initialized at all--they are always
  66. * written into before they're read.
  67. *
  68. * - The matchstate tables have a unique requirement that they don't need
  69. * their memory to be totally cleared, but they do need the memory to have
  70. * some bound, i.e., a guarantee that all values in the memory they've been
  71. * allocated is less than some maximum value (which is the starting value
  72. * for the indices that they will then use for compression). When this
  73. * guarantee is provided to them, they can use the memory without any setup
  74. * work. When it can't, they have to clear the area.
  75. *
  76. * - These buffers also have different alignment requirements.
  77. *
  78. * - We would like to reuse the objects in the workspace for multiple
  79. * compressions without having to perform any expensive reallocation or
  80. * reinitialization work.
  81. *
  82. * - We would like to be able to efficiently reuse the workspace across
  83. * multiple compressions **even when the compression parameters change** and
  84. * we need to resize some of the objects (where possible).
  85. *
  86. * To attempt to manage this buffer, given these constraints, the ZSTD_cwksp
  87. * abstraction was created. It works as follows:
  88. *
  89. * Workspace Layout:
  90. *
  91. * [ ... workspace ... ]
  92. * [objects][tables ... ->] free space [<- ... aligned][<- ... buffers]
  93. *
  94. * The various objects that live in the workspace are divided into the
  95. * following categories, and are allocated separately:
  96. *
  97. * - Static objects: this is optionally the enclosing ZSTD_CCtx or ZSTD_CDict,
  98. * so that literally everything fits in a single buffer. Note: if present,
  99. * this must be the first object in the workspace, since ZSTD_customFree{CCtx,
  100. * CDict}() rely on a pointer comparison to see whether one or two frees are
  101. * required.
  102. *
  103. * - Fixed size objects: these are fixed-size, fixed-count objects that are
  104. * nonetheless "dynamically" allocated in the workspace so that we can
  105. * control how they're initialized separately from the broader ZSTD_CCtx.
  106. * Examples:
  107. * - Entropy Workspace
  108. * - 2 x ZSTD_compressedBlockState_t
  109. * - CDict dictionary contents
  110. *
  111. * - Tables: these are any of several different datastructures (hash tables,
  112. * chain tables, binary trees) that all respect a common format: they are
  113. * uint32_t arrays, all of whose values are between 0 and (nextSrc - base).
  114. * Their sizes depend on the cparams. These tables are 64-byte aligned.
  115. *
  116. * - Aligned: these buffers are used for various purposes that require 4 byte
  117. * alignment, but don't require any initialization before they're used. These
  118. * buffers are each aligned to 64 bytes.
  119. *
  120. * - Buffers: these buffers are used for various purposes that don't require
  121. * any alignment or initialization before they're used. This means they can
  122. * be moved around at no cost for a new compression.
  123. *
  124. * Allocating Memory:
  125. *
  126. * The various types of objects must be allocated in order, so they can be
  127. * correctly packed into the workspace buffer. That order is:
  128. *
  129. * 1. Objects
  130. * 2. Buffers
  131. * 3. Aligned/Tables
  132. *
  133. * Attempts to reserve objects of different types out of order will fail.
  134. */
  135. typedef struct {
  136. void* workspace;
  137. void* workspaceEnd;
  138. void* objectEnd;
  139. void* tableEnd;
  140. void* tableValidEnd;
  141. void* allocStart;
  142. BYTE allocFailed;
  143. int workspaceOversizedDuration;
  144. ZSTD_cwksp_alloc_phase_e phase;
  145. ZSTD_cwksp_static_alloc_e isStatic;
  146. } ZSTD_cwksp;
  147. /*-*************************************
  148. * Functions
  149. ***************************************/
  150. MEM_STATIC size_t ZSTD_cwksp_available_space(ZSTD_cwksp* ws);
  151. MEM_STATIC void ZSTD_cwksp_assert_internal_consistency(ZSTD_cwksp* ws) {
  152. (void)ws;
  153. assert(ws->workspace <= ws->objectEnd);
  154. assert(ws->objectEnd <= ws->tableEnd);
  155. assert(ws->objectEnd <= ws->tableValidEnd);
  156. assert(ws->tableEnd <= ws->allocStart);
  157. assert(ws->tableValidEnd <= ws->allocStart);
  158. assert(ws->allocStart <= ws->workspaceEnd);
  159. }
  160. /**
  161. * Align must be a power of 2.
  162. */
  163. MEM_STATIC size_t ZSTD_cwksp_align(size_t size, size_t const align) {
  164. size_t const mask = align - 1;
  165. assert((align & mask) == 0);
  166. return (size + mask) & ~mask;
  167. }
  168. /**
  169. * Use this to determine how much space in the workspace we will consume to
  170. * allocate this object. (Normally it should be exactly the size of the object,
  171. * but under special conditions, like ASAN, where we pad each object, it might
  172. * be larger.)
  173. *
  174. * Since tables aren't currently redzoned, you don't need to call through this
  175. * to figure out how much space you need for the matchState tables. Everything
  176. * else is though.
  177. *
  178. * Do not use for sizing aligned buffers. Instead, use ZSTD_cwksp_aligned_alloc_size().
  179. */
  180. MEM_STATIC size_t ZSTD_cwksp_alloc_size(size_t size) {
  181. if (size == 0)
  182. return 0;
  183. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  184. return size + 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  185. #else
  186. return size;
  187. #endif
  188. }
  189. /**
  190. * Returns an adjusted alloc size that is the nearest larger multiple of 64 bytes.
  191. * Used to determine the number of bytes required for a given "aligned".
  192. */
  193. MEM_STATIC size_t ZSTD_cwksp_aligned_alloc_size(size_t size) {
  194. return ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(size, ZSTD_CWKSP_ALIGNMENT_BYTES));
  195. }
  196. /**
  197. * Returns the amount of additional space the cwksp must allocate
  198. * for internal purposes (currently only alignment).
  199. */
  200. MEM_STATIC size_t ZSTD_cwksp_slack_space_required(void) {
  201. /* For alignment, the wksp will always allocate an additional n_1=[1, 64] bytes
  202. * to align the beginning of tables section, as well as another n_2=[0, 63] bytes
  203. * to align the beginning of the aligned secion.
  204. *
  205. * n_1 + n_2 == 64 bytes if the cwksp is freshly allocated, due to tables and
  206. * aligneds being sized in multiples of 64 bytes.
  207. */
  208. size_t const slackSpace = ZSTD_CWKSP_ALIGNMENT_BYTES;
  209. return slackSpace;
  210. }
  211. /**
  212. * Return the number of additional bytes required to align a pointer to the given number of bytes.
  213. * alignBytes must be a power of two.
  214. */
  215. MEM_STATIC size_t ZSTD_cwksp_bytes_to_align_ptr(void* ptr, const size_t alignBytes) {
  216. size_t const alignBytesMask = alignBytes - 1;
  217. size_t const bytes = (alignBytes - ((size_t)ptr & (alignBytesMask))) & alignBytesMask;
  218. assert((alignBytes & alignBytesMask) == 0);
  219. assert(bytes != ZSTD_CWKSP_ALIGNMENT_BYTES);
  220. return bytes;
  221. }
  222. /**
  223. * Internal function. Do not use directly.
  224. * Reserves the given number of bytes within the aligned/buffer segment of the wksp, which
  225. * counts from the end of the wksp. (as opposed to the object/table segment)
  226. *
  227. * Returns a pointer to the beginning of that space.
  228. */
  229. MEM_STATIC void* ZSTD_cwksp_reserve_internal_buffer_space(ZSTD_cwksp* ws, size_t const bytes) {
  230. void* const alloc = (BYTE*)ws->allocStart - bytes;
  231. void* const bottom = ws->tableEnd;
  232. DEBUGLOG(5, "cwksp: reserving %p %zd bytes, %zd bytes remaining",
  233. alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
  234. ZSTD_cwksp_assert_internal_consistency(ws);
  235. assert(alloc >= bottom);
  236. if (alloc < bottom) {
  237. DEBUGLOG(4, "cwksp: alloc failed!");
  238. ws->allocFailed = 1;
  239. return NULL;
  240. }
  241. if (alloc < ws->tableValidEnd) {
  242. ws->tableValidEnd = alloc;
  243. }
  244. ws->allocStart = alloc;
  245. return alloc;
  246. }
  247. /**
  248. * Moves the cwksp to the next phase, and does any necessary allocations.
  249. * Returns a 0 on success, or zstd error
  250. */
  251. MEM_STATIC size_t ZSTD_cwksp_internal_advance_phase(
  252. ZSTD_cwksp* ws, ZSTD_cwksp_alloc_phase_e phase) {
  253. assert(phase >= ws->phase);
  254. if (phase > ws->phase) {
  255. /* Going from allocating objects to allocating buffers */
  256. if (ws->phase < ZSTD_cwksp_alloc_buffers &&
  257. phase >= ZSTD_cwksp_alloc_buffers) {
  258. ws->tableValidEnd = ws->objectEnd;
  259. }
  260. /* Going from allocating buffers to allocating aligneds/tables */
  261. if (ws->phase < ZSTD_cwksp_alloc_aligned &&
  262. phase >= ZSTD_cwksp_alloc_aligned) {
  263. { /* Align the start of the "aligned" to 64 bytes. Use [1, 64] bytes. */
  264. size_t const bytesToAlign =
  265. ZSTD_CWKSP_ALIGNMENT_BYTES - ZSTD_cwksp_bytes_to_align_ptr(ws->allocStart, ZSTD_CWKSP_ALIGNMENT_BYTES);
  266. DEBUGLOG(5, "reserving aligned alignment addtl space: %zu", bytesToAlign);
  267. ZSTD_STATIC_ASSERT((ZSTD_CWKSP_ALIGNMENT_BYTES & (ZSTD_CWKSP_ALIGNMENT_BYTES - 1)) == 0); /* power of 2 */
  268. RETURN_ERROR_IF(!ZSTD_cwksp_reserve_internal_buffer_space(ws, bytesToAlign),
  269. memory_allocation, "aligned phase - alignment initial allocation failed!");
  270. }
  271. { /* Align the start of the tables to 64 bytes. Use [0, 63] bytes */
  272. void* const alloc = ws->objectEnd;
  273. size_t const bytesToAlign = ZSTD_cwksp_bytes_to_align_ptr(alloc, ZSTD_CWKSP_ALIGNMENT_BYTES);
  274. void* const end = (BYTE*)alloc + bytesToAlign;
  275. DEBUGLOG(5, "reserving table alignment addtl space: %zu", bytesToAlign);
  276. RETURN_ERROR_IF(end > ws->workspaceEnd, memory_allocation,
  277. "table phase - alignment initial allocation failed!");
  278. ws->objectEnd = end;
  279. ws->tableEnd = end;
  280. ws->tableValidEnd = end;
  281. }
  282. }
  283. ws->phase = phase;
  284. ZSTD_cwksp_assert_internal_consistency(ws);
  285. }
  286. return 0;
  287. }
  288. /**
  289. * Returns whether this object/buffer/etc was allocated in this workspace.
  290. */
  291. MEM_STATIC int ZSTD_cwksp_owns_buffer(const ZSTD_cwksp* ws, const void* ptr) {
  292. return (ptr != NULL) && (ws->workspace <= ptr) && (ptr <= ws->workspaceEnd);
  293. }
  294. /**
  295. * Internal function. Do not use directly.
  296. */
  297. MEM_STATIC void* ZSTD_cwksp_reserve_internal(
  298. ZSTD_cwksp* ws, size_t bytes, ZSTD_cwksp_alloc_phase_e phase) {
  299. void* alloc;
  300. if (ZSTD_isError(ZSTD_cwksp_internal_advance_phase(ws, phase)) || bytes == 0) {
  301. return NULL;
  302. }
  303. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  304. /* over-reserve space */
  305. bytes += 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  306. #endif
  307. alloc = ZSTD_cwksp_reserve_internal_buffer_space(ws, bytes);
  308. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  309. /* Move alloc so there's ZSTD_CWKSP_ASAN_REDZONE_SIZE unused space on
  310. * either size. */
  311. if (alloc) {
  312. alloc = (BYTE *)alloc + ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  313. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  314. __asan_unpoison_memory_region(alloc, bytes);
  315. }
  316. }
  317. #endif
  318. return alloc;
  319. }
  320. /**
  321. * Reserves and returns unaligned memory.
  322. */
  323. MEM_STATIC BYTE* ZSTD_cwksp_reserve_buffer(ZSTD_cwksp* ws, size_t bytes) {
  324. return (BYTE*)ZSTD_cwksp_reserve_internal(ws, bytes, ZSTD_cwksp_alloc_buffers);
  325. }
  326. /**
  327. * Reserves and returns memory sized on and aligned on ZSTD_CWKSP_ALIGNMENT_BYTES (64 bytes).
  328. */
  329. MEM_STATIC void* ZSTD_cwksp_reserve_aligned(ZSTD_cwksp* ws, size_t bytes) {
  330. void* ptr = ZSTD_cwksp_reserve_internal(ws, ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES),
  331. ZSTD_cwksp_alloc_aligned);
  332. assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
  333. return ptr;
  334. }
  335. /**
  336. * Aligned on 64 bytes. These buffers have the special property that
  337. * their values remain constrained, allowing us to re-use them without
  338. * memset()-ing them.
  339. */
  340. MEM_STATIC void* ZSTD_cwksp_reserve_table(ZSTD_cwksp* ws, size_t bytes) {
  341. const ZSTD_cwksp_alloc_phase_e phase = ZSTD_cwksp_alloc_aligned;
  342. void* alloc;
  343. void* end;
  344. void* top;
  345. if (ZSTD_isError(ZSTD_cwksp_internal_advance_phase(ws, phase))) {
  346. return NULL;
  347. }
  348. alloc = ws->tableEnd;
  349. end = (BYTE *)alloc + bytes;
  350. top = ws->allocStart;
  351. DEBUGLOG(5, "cwksp: reserving %p table %zd bytes, %zd bytes remaining",
  352. alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
  353. assert((bytes & (sizeof(U32)-1)) == 0);
  354. ZSTD_cwksp_assert_internal_consistency(ws);
  355. assert(end <= top);
  356. if (end > top) {
  357. DEBUGLOG(4, "cwksp: table alloc failed!");
  358. ws->allocFailed = 1;
  359. return NULL;
  360. }
  361. ws->tableEnd = end;
  362. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  363. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  364. __asan_unpoison_memory_region(alloc, bytes);
  365. }
  366. #endif
  367. assert((bytes & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0);
  368. assert(((size_t)alloc & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
  369. return alloc;
  370. }
  371. /**
  372. * Aligned on sizeof(void*).
  373. */
  374. MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes) {
  375. size_t roundedBytes = ZSTD_cwksp_align(bytes, sizeof(void*));
  376. void* alloc = ws->objectEnd;
  377. void* end = (BYTE*)alloc + roundedBytes;
  378. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  379. /* over-reserve space */
  380. end = (BYTE *)end + 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  381. #endif
  382. DEBUGLOG(5,
  383. "cwksp: reserving %p object %zd bytes (rounded to %zd), %zd bytes remaining",
  384. alloc, bytes, roundedBytes, ZSTD_cwksp_available_space(ws) - roundedBytes);
  385. assert(((size_t)alloc & (sizeof(void*)-1)) == 0);
  386. assert((bytes & (sizeof(void*)-1)) == 0);
  387. ZSTD_cwksp_assert_internal_consistency(ws);
  388. /* we must be in the first phase, no advance is possible */
  389. if (ws->phase != ZSTD_cwksp_alloc_objects || end > ws->workspaceEnd) {
  390. DEBUGLOG(4, "cwksp: object alloc failed!");
  391. ws->allocFailed = 1;
  392. return NULL;
  393. }
  394. ws->objectEnd = end;
  395. ws->tableEnd = end;
  396. ws->tableValidEnd = end;
  397. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  398. /* Move alloc so there's ZSTD_CWKSP_ASAN_REDZONE_SIZE unused space on
  399. * either size. */
  400. alloc = (BYTE *)alloc + ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  401. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  402. __asan_unpoison_memory_region(alloc, bytes);
  403. }
  404. #endif
  405. return alloc;
  406. }
  407. MEM_STATIC void ZSTD_cwksp_mark_tables_dirty(ZSTD_cwksp* ws) {
  408. DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_dirty");
  409. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  410. /* To validate that the table re-use logic is sound, and that we don't
  411. * access table space that we haven't cleaned, we re-"poison" the table
  412. * space every time we mark it dirty. */
  413. {
  414. size_t size = (BYTE*)ws->tableValidEnd - (BYTE*)ws->objectEnd;
  415. assert(__msan_test_shadow(ws->objectEnd, size) == -1);
  416. __msan_poison(ws->objectEnd, size);
  417. }
  418. #endif
  419. assert(ws->tableValidEnd >= ws->objectEnd);
  420. assert(ws->tableValidEnd <= ws->allocStart);
  421. ws->tableValidEnd = ws->objectEnd;
  422. ZSTD_cwksp_assert_internal_consistency(ws);
  423. }
  424. MEM_STATIC void ZSTD_cwksp_mark_tables_clean(ZSTD_cwksp* ws) {
  425. DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_clean");
  426. assert(ws->tableValidEnd >= ws->objectEnd);
  427. assert(ws->tableValidEnd <= ws->allocStart);
  428. if (ws->tableValidEnd < ws->tableEnd) {
  429. ws->tableValidEnd = ws->tableEnd;
  430. }
  431. ZSTD_cwksp_assert_internal_consistency(ws);
  432. }
  433. /**
  434. * Zero the part of the allocated tables not already marked clean.
  435. */
  436. MEM_STATIC void ZSTD_cwksp_clean_tables(ZSTD_cwksp* ws) {
  437. DEBUGLOG(4, "cwksp: ZSTD_cwksp_clean_tables");
  438. assert(ws->tableValidEnd >= ws->objectEnd);
  439. assert(ws->tableValidEnd <= ws->allocStart);
  440. if (ws->tableValidEnd < ws->tableEnd) {
  441. ZSTD_memset(ws->tableValidEnd, 0, (BYTE*)ws->tableEnd - (BYTE*)ws->tableValidEnd);
  442. }
  443. ZSTD_cwksp_mark_tables_clean(ws);
  444. }
  445. /**
  446. * Invalidates table allocations.
  447. * All other allocations remain valid.
  448. */
  449. MEM_STATIC void ZSTD_cwksp_clear_tables(ZSTD_cwksp* ws) {
  450. DEBUGLOG(4, "cwksp: clearing tables!");
  451. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  452. /* We don't do this when the workspace is statically allocated, because
  453. * when that is the case, we have no capability to hook into the end of the
  454. * workspace's lifecycle to unpoison the memory.
  455. */
  456. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  457. size_t size = (BYTE*)ws->tableValidEnd - (BYTE*)ws->objectEnd;
  458. __asan_poison_memory_region(ws->objectEnd, size);
  459. }
  460. #endif
  461. ws->tableEnd = ws->objectEnd;
  462. ZSTD_cwksp_assert_internal_consistency(ws);
  463. }
  464. /**
  465. * Invalidates all buffer, aligned, and table allocations.
  466. * Object allocations remain valid.
  467. */
  468. MEM_STATIC void ZSTD_cwksp_clear(ZSTD_cwksp* ws) {
  469. DEBUGLOG(4, "cwksp: clearing!");
  470. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  471. /* To validate that the context re-use logic is sound, and that we don't
  472. * access stuff that this compression hasn't initialized, we re-"poison"
  473. * the workspace (or at least the non-static, non-table parts of it)
  474. * every time we start a new compression. */
  475. {
  476. size_t size = (BYTE*)ws->workspaceEnd - (BYTE*)ws->tableValidEnd;
  477. __msan_poison(ws->tableValidEnd, size);
  478. }
  479. #endif
  480. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  481. /* We don't do this when the workspace is statically allocated, because
  482. * when that is the case, we have no capability to hook into the end of the
  483. * workspace's lifecycle to unpoison the memory.
  484. */
  485. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  486. size_t size = (BYTE*)ws->workspaceEnd - (BYTE*)ws->objectEnd;
  487. __asan_poison_memory_region(ws->objectEnd, size);
  488. }
  489. #endif
  490. ws->tableEnd = ws->objectEnd;
  491. ws->allocStart = ws->workspaceEnd;
  492. ws->allocFailed = 0;
  493. if (ws->phase > ZSTD_cwksp_alloc_buffers) {
  494. ws->phase = ZSTD_cwksp_alloc_buffers;
  495. }
  496. ZSTD_cwksp_assert_internal_consistency(ws);
  497. }
  498. /**
  499. * The provided workspace takes ownership of the buffer [start, start+size).
  500. * Any existing values in the workspace are ignored (the previously managed
  501. * buffer, if present, must be separately freed).
  502. */
  503. MEM_STATIC void ZSTD_cwksp_init(ZSTD_cwksp* ws, void* start, size_t size, ZSTD_cwksp_static_alloc_e isStatic) {
  504. DEBUGLOG(4, "cwksp: init'ing workspace with %zd bytes", size);
  505. assert(((size_t)start & (sizeof(void*)-1)) == 0); /* ensure correct alignment */
  506. ws->workspace = start;
  507. ws->workspaceEnd = (BYTE*)start + size;
  508. ws->objectEnd = ws->workspace;
  509. ws->tableValidEnd = ws->objectEnd;
  510. ws->phase = ZSTD_cwksp_alloc_objects;
  511. ws->isStatic = isStatic;
  512. ZSTD_cwksp_clear(ws);
  513. ws->workspaceOversizedDuration = 0;
  514. ZSTD_cwksp_assert_internal_consistency(ws);
  515. }
  516. MEM_STATIC size_t ZSTD_cwksp_create(ZSTD_cwksp* ws, size_t size, ZSTD_customMem customMem) {
  517. void* workspace = ZSTD_customMalloc(size, customMem);
  518. DEBUGLOG(4, "cwksp: creating new workspace with %zd bytes", size);
  519. RETURN_ERROR_IF(workspace == NULL, memory_allocation, "NULL pointer!");
  520. ZSTD_cwksp_init(ws, workspace, size, ZSTD_cwksp_dynamic_alloc);
  521. return 0;
  522. }
  523. MEM_STATIC void ZSTD_cwksp_free(ZSTD_cwksp* ws, ZSTD_customMem customMem) {
  524. void *ptr = ws->workspace;
  525. DEBUGLOG(4, "cwksp: freeing workspace");
  526. ZSTD_memset(ws, 0, sizeof(ZSTD_cwksp));
  527. ZSTD_customFree(ptr, customMem);
  528. }
  529. /**
  530. * Moves the management of a workspace from one cwksp to another. The src cwksp
  531. * is left in an invalid state (src must be re-init()'ed before it's used again).
  532. */
  533. MEM_STATIC void ZSTD_cwksp_move(ZSTD_cwksp* dst, ZSTD_cwksp* src) {
  534. *dst = *src;
  535. ZSTD_memset(src, 0, sizeof(ZSTD_cwksp));
  536. }
  537. MEM_STATIC size_t ZSTD_cwksp_sizeof(const ZSTD_cwksp* ws) {
  538. return (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->workspace);
  539. }
  540. MEM_STATIC size_t ZSTD_cwksp_used(const ZSTD_cwksp* ws) {
  541. return (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->workspace)
  542. + (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->allocStart);
  543. }
  544. MEM_STATIC int ZSTD_cwksp_reserve_failed(const ZSTD_cwksp* ws) {
  545. return ws->allocFailed;
  546. }
  547. /*-*************************************
  548. * Functions Checking Free Space
  549. ***************************************/
  550. /* ZSTD_alignmentSpaceWithinBounds() :
  551. * Returns if the estimated space needed for a wksp is within an acceptable limit of the
  552. * actual amount of space used.
  553. */
  554. MEM_STATIC int ZSTD_cwksp_estimated_space_within_bounds(const ZSTD_cwksp* const ws,
  555. size_t const estimatedSpace, int resizedWorkspace) {
  556. if (resizedWorkspace) {
  557. /* Resized/newly allocated wksp should have exact bounds */
  558. return ZSTD_cwksp_used(ws) == estimatedSpace;
  559. } else {
  560. /* Due to alignment, when reusing a workspace, we can actually consume 63 fewer or more bytes
  561. * than estimatedSpace. See the comments in zstd_cwksp.h for details.
  562. */
  563. return (ZSTD_cwksp_used(ws) >= estimatedSpace - 63) && (ZSTD_cwksp_used(ws) <= estimatedSpace + 63);
  564. }
  565. }
  566. MEM_STATIC size_t ZSTD_cwksp_available_space(ZSTD_cwksp* ws) {
  567. return (size_t)((BYTE*)ws->allocStart - (BYTE*)ws->tableEnd);
  568. }
  569. MEM_STATIC int ZSTD_cwksp_check_available(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  570. return ZSTD_cwksp_available_space(ws) >= additionalNeededSpace;
  571. }
  572. MEM_STATIC int ZSTD_cwksp_check_too_large(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  573. return ZSTD_cwksp_check_available(
  574. ws, additionalNeededSpace * ZSTD_WORKSPACETOOLARGE_FACTOR);
  575. }
  576. MEM_STATIC int ZSTD_cwksp_check_wasteful(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  577. return ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)
  578. && ws->workspaceOversizedDuration > ZSTD_WORKSPACETOOLARGE_MAXDURATION;
  579. }
  580. MEM_STATIC void ZSTD_cwksp_bump_oversized_duration(
  581. ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  582. if (ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)) {
  583. ws->workspaceOversizedDuration++;
  584. } else {
  585. ws->workspaceOversizedDuration = 0;
  586. }
  587. }
  588. #if defined (__cplusplus)
  589. }
  590. #endif
  591. #endif /* ZSTD_CWKSP_H */