2
0

zstd_cwksp.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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 section.
  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,
  225. * which 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*
  230. ZSTD_cwksp_reserve_internal_buffer_space(ZSTD_cwksp* ws, size_t const bytes)
  231. {
  232. void* const alloc = (BYTE*)ws->allocStart - bytes;
  233. void* const bottom = ws->tableEnd;
  234. DEBUGLOG(5, "cwksp: reserving %p %zd bytes, %zd bytes remaining",
  235. alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
  236. ZSTD_cwksp_assert_internal_consistency(ws);
  237. assert(alloc >= bottom);
  238. if (alloc < bottom) {
  239. DEBUGLOG(4, "cwksp: alloc failed!");
  240. ws->allocFailed = 1;
  241. return NULL;
  242. }
  243. /* the area is reserved from the end of wksp.
  244. * If it overlaps with tableValidEnd, it voids guarantees on values' range */
  245. if (alloc < ws->tableValidEnd) {
  246. ws->tableValidEnd = alloc;
  247. }
  248. ws->allocStart = alloc;
  249. return alloc;
  250. }
  251. /**
  252. * Moves the cwksp to the next phase, and does any necessary allocations.
  253. * cwksp initialization must necessarily go through each phase in order.
  254. * Returns a 0 on success, or zstd error
  255. */
  256. MEM_STATIC size_t
  257. ZSTD_cwksp_internal_advance_phase(ZSTD_cwksp* ws, ZSTD_cwksp_alloc_phase_e phase)
  258. {
  259. assert(phase >= ws->phase);
  260. if (phase > ws->phase) {
  261. /* Going from allocating objects to allocating buffers */
  262. if (ws->phase < ZSTD_cwksp_alloc_buffers &&
  263. phase >= ZSTD_cwksp_alloc_buffers) {
  264. ws->tableValidEnd = ws->objectEnd;
  265. }
  266. /* Going from allocating buffers to allocating aligneds/tables */
  267. if (ws->phase < ZSTD_cwksp_alloc_aligned &&
  268. phase >= ZSTD_cwksp_alloc_aligned) {
  269. { /* Align the start of the "aligned" to 64 bytes. Use [1, 64] bytes. */
  270. size_t const bytesToAlign =
  271. ZSTD_CWKSP_ALIGNMENT_BYTES - ZSTD_cwksp_bytes_to_align_ptr(ws->allocStart, ZSTD_CWKSP_ALIGNMENT_BYTES);
  272. DEBUGLOG(5, "reserving aligned alignment addtl space: %zu", bytesToAlign);
  273. ZSTD_STATIC_ASSERT((ZSTD_CWKSP_ALIGNMENT_BYTES & (ZSTD_CWKSP_ALIGNMENT_BYTES - 1)) == 0); /* power of 2 */
  274. RETURN_ERROR_IF(!ZSTD_cwksp_reserve_internal_buffer_space(ws, bytesToAlign),
  275. memory_allocation, "aligned phase - alignment initial allocation failed!");
  276. }
  277. { /* Align the start of the tables to 64 bytes. Use [0, 63] bytes */
  278. void* const alloc = ws->objectEnd;
  279. size_t const bytesToAlign = ZSTD_cwksp_bytes_to_align_ptr(alloc, ZSTD_CWKSP_ALIGNMENT_BYTES);
  280. void* const objectEnd = (BYTE*)alloc + bytesToAlign;
  281. DEBUGLOG(5, "reserving table alignment addtl space: %zu", bytesToAlign);
  282. RETURN_ERROR_IF(objectEnd > ws->workspaceEnd, memory_allocation,
  283. "table phase - alignment initial allocation failed!");
  284. ws->objectEnd = objectEnd;
  285. ws->tableEnd = objectEnd; /* table area starts being empty */
  286. if (ws->tableValidEnd < ws->tableEnd) {
  287. ws->tableValidEnd = ws->tableEnd;
  288. } } }
  289. ws->phase = phase;
  290. ZSTD_cwksp_assert_internal_consistency(ws);
  291. }
  292. return 0;
  293. }
  294. /**
  295. * Returns whether this object/buffer/etc was allocated in this workspace.
  296. */
  297. MEM_STATIC int ZSTD_cwksp_owns_buffer(const ZSTD_cwksp* ws, const void* ptr)
  298. {
  299. return (ptr != NULL) && (ws->workspace <= ptr) && (ptr <= ws->workspaceEnd);
  300. }
  301. /**
  302. * Internal function. Do not use directly.
  303. */
  304. MEM_STATIC void*
  305. ZSTD_cwksp_reserve_internal(ZSTD_cwksp* ws, size_t bytes, ZSTD_cwksp_alloc_phase_e phase)
  306. {
  307. void* alloc;
  308. if (ZSTD_isError(ZSTD_cwksp_internal_advance_phase(ws, phase)) || bytes == 0) {
  309. return NULL;
  310. }
  311. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  312. /* over-reserve space */
  313. bytes += 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  314. #endif
  315. alloc = ZSTD_cwksp_reserve_internal_buffer_space(ws, bytes);
  316. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  317. /* Move alloc so there's ZSTD_CWKSP_ASAN_REDZONE_SIZE unused space on
  318. * either size. */
  319. if (alloc) {
  320. alloc = (BYTE *)alloc + ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  321. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  322. __asan_unpoison_memory_region(alloc, bytes);
  323. }
  324. }
  325. #endif
  326. return alloc;
  327. }
  328. /**
  329. * Reserves and returns unaligned memory.
  330. */
  331. MEM_STATIC BYTE* ZSTD_cwksp_reserve_buffer(ZSTD_cwksp* ws, size_t bytes)
  332. {
  333. return (BYTE*)ZSTD_cwksp_reserve_internal(ws, bytes, ZSTD_cwksp_alloc_buffers);
  334. }
  335. /**
  336. * Reserves and returns memory sized on and aligned on ZSTD_CWKSP_ALIGNMENT_BYTES (64 bytes).
  337. */
  338. MEM_STATIC void* ZSTD_cwksp_reserve_aligned(ZSTD_cwksp* ws, size_t bytes)
  339. {
  340. void* ptr = ZSTD_cwksp_reserve_internal(ws, ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES),
  341. ZSTD_cwksp_alloc_aligned);
  342. assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
  343. return ptr;
  344. }
  345. /**
  346. * Aligned on 64 bytes. These buffers have the special property that
  347. * their values remain constrained, allowing us to re-use them without
  348. * memset()-ing them.
  349. */
  350. MEM_STATIC void* ZSTD_cwksp_reserve_table(ZSTD_cwksp* ws, size_t bytes)
  351. {
  352. const ZSTD_cwksp_alloc_phase_e phase = ZSTD_cwksp_alloc_aligned;
  353. void* alloc;
  354. void* end;
  355. void* top;
  356. if (ZSTD_isError(ZSTD_cwksp_internal_advance_phase(ws, phase))) {
  357. return NULL;
  358. }
  359. alloc = ws->tableEnd;
  360. end = (BYTE *)alloc + bytes;
  361. top = ws->allocStart;
  362. DEBUGLOG(5, "cwksp: reserving %p table %zd bytes, %zd bytes remaining",
  363. alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
  364. assert((bytes & (sizeof(U32)-1)) == 0);
  365. ZSTD_cwksp_assert_internal_consistency(ws);
  366. assert(end <= top);
  367. if (end > top) {
  368. DEBUGLOG(4, "cwksp: table alloc failed!");
  369. ws->allocFailed = 1;
  370. return NULL;
  371. }
  372. ws->tableEnd = end;
  373. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  374. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  375. __asan_unpoison_memory_region(alloc, bytes);
  376. }
  377. #endif
  378. assert((bytes & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0);
  379. assert(((size_t)alloc & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
  380. return alloc;
  381. }
  382. /**
  383. * Aligned on sizeof(void*).
  384. * Note : should happen only once, at workspace first initialization
  385. */
  386. MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes)
  387. {
  388. size_t const roundedBytes = ZSTD_cwksp_align(bytes, sizeof(void*));
  389. void* alloc = ws->objectEnd;
  390. void* end = (BYTE*)alloc + roundedBytes;
  391. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  392. /* over-reserve space */
  393. end = (BYTE *)end + 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  394. #endif
  395. DEBUGLOG(4,
  396. "cwksp: reserving %p object %zd bytes (rounded to %zd), %zd bytes remaining",
  397. alloc, bytes, roundedBytes, ZSTD_cwksp_available_space(ws) - roundedBytes);
  398. assert((size_t)alloc % ZSTD_ALIGNOF(void*) == 0);
  399. assert(bytes % ZSTD_ALIGNOF(void*) == 0);
  400. ZSTD_cwksp_assert_internal_consistency(ws);
  401. /* we must be in the first phase, no advance is possible */
  402. if (ws->phase != ZSTD_cwksp_alloc_objects || end > ws->workspaceEnd) {
  403. DEBUGLOG(3, "cwksp: object alloc failed!");
  404. ws->allocFailed = 1;
  405. return NULL;
  406. }
  407. ws->objectEnd = end;
  408. ws->tableEnd = end;
  409. ws->tableValidEnd = end;
  410. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  411. /* Move alloc so there's ZSTD_CWKSP_ASAN_REDZONE_SIZE unused space on
  412. * either size. */
  413. alloc = (BYTE*)alloc + ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  414. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  415. __asan_unpoison_memory_region(alloc, bytes);
  416. }
  417. #endif
  418. return alloc;
  419. }
  420. MEM_STATIC void ZSTD_cwksp_mark_tables_dirty(ZSTD_cwksp* ws)
  421. {
  422. DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_dirty");
  423. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  424. /* To validate that the table re-use logic is sound, and that we don't
  425. * access table space that we haven't cleaned, we re-"poison" the table
  426. * space every time we mark it dirty. */
  427. {
  428. size_t size = (BYTE*)ws->tableValidEnd - (BYTE*)ws->objectEnd;
  429. assert(__msan_test_shadow(ws->objectEnd, size) == -1);
  430. __msan_poison(ws->objectEnd, size);
  431. }
  432. #endif
  433. assert(ws->tableValidEnd >= ws->objectEnd);
  434. assert(ws->tableValidEnd <= ws->allocStart);
  435. ws->tableValidEnd = ws->objectEnd;
  436. ZSTD_cwksp_assert_internal_consistency(ws);
  437. }
  438. MEM_STATIC void ZSTD_cwksp_mark_tables_clean(ZSTD_cwksp* ws) {
  439. DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_clean");
  440. assert(ws->tableValidEnd >= ws->objectEnd);
  441. assert(ws->tableValidEnd <= ws->allocStart);
  442. if (ws->tableValidEnd < ws->tableEnd) {
  443. ws->tableValidEnd = ws->tableEnd;
  444. }
  445. ZSTD_cwksp_assert_internal_consistency(ws);
  446. }
  447. /**
  448. * Zero the part of the allocated tables not already marked clean.
  449. */
  450. MEM_STATIC void ZSTD_cwksp_clean_tables(ZSTD_cwksp* ws) {
  451. DEBUGLOG(4, "cwksp: ZSTD_cwksp_clean_tables");
  452. assert(ws->tableValidEnd >= ws->objectEnd);
  453. assert(ws->tableValidEnd <= ws->allocStart);
  454. if (ws->tableValidEnd < ws->tableEnd) {
  455. ZSTD_memset(ws->tableValidEnd, 0, (BYTE*)ws->tableEnd - (BYTE*)ws->tableValidEnd);
  456. }
  457. ZSTD_cwksp_mark_tables_clean(ws);
  458. }
  459. /**
  460. * Invalidates table allocations.
  461. * All other allocations remain valid.
  462. */
  463. MEM_STATIC void ZSTD_cwksp_clear_tables(ZSTD_cwksp* ws) {
  464. DEBUGLOG(4, "cwksp: clearing tables!");
  465. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  466. /* We don't do this when the workspace is statically allocated, because
  467. * when that is the case, we have no capability to hook into the end of the
  468. * workspace's lifecycle to unpoison the memory.
  469. */
  470. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  471. size_t size = (BYTE*)ws->tableValidEnd - (BYTE*)ws->objectEnd;
  472. __asan_poison_memory_region(ws->objectEnd, size);
  473. }
  474. #endif
  475. ws->tableEnd = ws->objectEnd;
  476. ZSTD_cwksp_assert_internal_consistency(ws);
  477. }
  478. /**
  479. * Invalidates all buffer, aligned, and table allocations.
  480. * Object allocations remain valid.
  481. */
  482. MEM_STATIC void ZSTD_cwksp_clear(ZSTD_cwksp* ws) {
  483. DEBUGLOG(4, "cwksp: clearing!");
  484. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  485. /* To validate that the context re-use logic is sound, and that we don't
  486. * access stuff that this compression hasn't initialized, we re-"poison"
  487. * the workspace (or at least the non-static, non-table parts of it)
  488. * every time we start a new compression. */
  489. {
  490. size_t size = (BYTE*)ws->workspaceEnd - (BYTE*)ws->tableValidEnd;
  491. __msan_poison(ws->tableValidEnd, size);
  492. }
  493. #endif
  494. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  495. /* We don't do this when the workspace is statically allocated, because
  496. * when that is the case, we have no capability to hook into the end of the
  497. * workspace's lifecycle to unpoison the memory.
  498. */
  499. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  500. size_t size = (BYTE*)ws->workspaceEnd - (BYTE*)ws->objectEnd;
  501. __asan_poison_memory_region(ws->objectEnd, size);
  502. }
  503. #endif
  504. ws->tableEnd = ws->objectEnd;
  505. ws->allocStart = ws->workspaceEnd;
  506. ws->allocFailed = 0;
  507. if (ws->phase > ZSTD_cwksp_alloc_buffers) {
  508. ws->phase = ZSTD_cwksp_alloc_buffers;
  509. }
  510. ZSTD_cwksp_assert_internal_consistency(ws);
  511. }
  512. /**
  513. * The provided workspace takes ownership of the buffer [start, start+size).
  514. * Any existing values in the workspace are ignored (the previously managed
  515. * buffer, if present, must be separately freed).
  516. */
  517. MEM_STATIC void ZSTD_cwksp_init(ZSTD_cwksp* ws, void* start, size_t size, ZSTD_cwksp_static_alloc_e isStatic) {
  518. DEBUGLOG(4, "cwksp: init'ing workspace with %zd bytes", size);
  519. assert(((size_t)start & (sizeof(void*)-1)) == 0); /* ensure correct alignment */
  520. ws->workspace = start;
  521. ws->workspaceEnd = (BYTE*)start + size;
  522. ws->objectEnd = ws->workspace;
  523. ws->tableValidEnd = ws->objectEnd;
  524. ws->phase = ZSTD_cwksp_alloc_objects;
  525. ws->isStatic = isStatic;
  526. ZSTD_cwksp_clear(ws);
  527. ws->workspaceOversizedDuration = 0;
  528. ZSTD_cwksp_assert_internal_consistency(ws);
  529. }
  530. MEM_STATIC size_t ZSTD_cwksp_create(ZSTD_cwksp* ws, size_t size, ZSTD_customMem customMem) {
  531. void* workspace = ZSTD_customMalloc(size, customMem);
  532. DEBUGLOG(4, "cwksp: creating new workspace with %zd bytes", size);
  533. RETURN_ERROR_IF(workspace == NULL, memory_allocation, "NULL pointer!");
  534. ZSTD_cwksp_init(ws, workspace, size, ZSTD_cwksp_dynamic_alloc);
  535. return 0;
  536. }
  537. MEM_STATIC void ZSTD_cwksp_free(ZSTD_cwksp* ws, ZSTD_customMem customMem) {
  538. void *ptr = ws->workspace;
  539. DEBUGLOG(4, "cwksp: freeing workspace");
  540. ZSTD_memset(ws, 0, sizeof(ZSTD_cwksp));
  541. ZSTD_customFree(ptr, customMem);
  542. }
  543. /**
  544. * Moves the management of a workspace from one cwksp to another. The src cwksp
  545. * is left in an invalid state (src must be re-init()'ed before it's used again).
  546. */
  547. MEM_STATIC void ZSTD_cwksp_move(ZSTD_cwksp* dst, ZSTD_cwksp* src) {
  548. *dst = *src;
  549. ZSTD_memset(src, 0, sizeof(ZSTD_cwksp));
  550. }
  551. MEM_STATIC size_t ZSTD_cwksp_sizeof(const ZSTD_cwksp* ws) {
  552. return (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->workspace);
  553. }
  554. MEM_STATIC size_t ZSTD_cwksp_used(const ZSTD_cwksp* ws) {
  555. return (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->workspace)
  556. + (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->allocStart);
  557. }
  558. MEM_STATIC int ZSTD_cwksp_reserve_failed(const ZSTD_cwksp* ws) {
  559. return ws->allocFailed;
  560. }
  561. /*-*************************************
  562. * Functions Checking Free Space
  563. ***************************************/
  564. /* ZSTD_alignmentSpaceWithinBounds() :
  565. * Returns if the estimated space needed for a wksp is within an acceptable limit of the
  566. * actual amount of space used.
  567. */
  568. MEM_STATIC int ZSTD_cwksp_estimated_space_within_bounds(const ZSTD_cwksp* const ws,
  569. size_t const estimatedSpace, int resizedWorkspace) {
  570. if (resizedWorkspace) {
  571. /* Resized/newly allocated wksp should have exact bounds */
  572. return ZSTD_cwksp_used(ws) == estimatedSpace;
  573. } else {
  574. /* Due to alignment, when reusing a workspace, we can actually consume 63 fewer or more bytes
  575. * than estimatedSpace. See the comments in zstd_cwksp.h for details.
  576. */
  577. return (ZSTD_cwksp_used(ws) >= estimatedSpace - 63) && (ZSTD_cwksp_used(ws) <= estimatedSpace + 63);
  578. }
  579. }
  580. MEM_STATIC size_t ZSTD_cwksp_available_space(ZSTD_cwksp* ws) {
  581. return (size_t)((BYTE*)ws->allocStart - (BYTE*)ws->tableEnd);
  582. }
  583. MEM_STATIC int ZSTD_cwksp_check_available(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  584. return ZSTD_cwksp_available_space(ws) >= additionalNeededSpace;
  585. }
  586. MEM_STATIC int ZSTD_cwksp_check_too_large(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  587. return ZSTD_cwksp_check_available(
  588. ws, additionalNeededSpace * ZSTD_WORKSPACETOOLARGE_FACTOR);
  589. }
  590. MEM_STATIC int ZSTD_cwksp_check_wasteful(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  591. return ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)
  592. && ws->workspaceOversizedDuration > ZSTD_WORKSPACETOOLARGE_MAXDURATION;
  593. }
  594. MEM_STATIC void ZSTD_cwksp_bump_oversized_duration(
  595. ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  596. if (ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)) {
  597. ws->workspaceOversizedDuration++;
  598. } else {
  599. ws->workspaceOversizedDuration = 0;
  600. }
  601. }
  602. #if defined (__cplusplus)
  603. }
  604. #endif
  605. #endif /* ZSTD_CWKSP_H */