zstd_cwksp.h 24 KB

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