You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

zstd_cwksp.h 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  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 "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. /* We need to keep the redzone poisoned while unpoisoning the bytes that
  323. * are actually allocated. */
  324. __asan_unpoison_memory_region(alloc, bytes - 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE);
  325. }
  326. }
  327. #endif
  328. return alloc;
  329. }
  330. /**
  331. * Reserves and returns unaligned memory.
  332. */
  333. MEM_STATIC BYTE* ZSTD_cwksp_reserve_buffer(ZSTD_cwksp* ws, size_t bytes)
  334. {
  335. return (BYTE*)ZSTD_cwksp_reserve_internal(ws, bytes, ZSTD_cwksp_alloc_buffers);
  336. }
  337. /**
  338. * Reserves and returns memory sized on and aligned on ZSTD_CWKSP_ALIGNMENT_BYTES (64 bytes).
  339. */
  340. MEM_STATIC void* ZSTD_cwksp_reserve_aligned(ZSTD_cwksp* ws, size_t bytes)
  341. {
  342. void* ptr = ZSTD_cwksp_reserve_internal(ws, ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES),
  343. ZSTD_cwksp_alloc_aligned);
  344. assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
  345. return ptr;
  346. }
  347. /**
  348. * Aligned on 64 bytes. These buffers have the special property that
  349. * their values remain constrained, allowing us to re-use them without
  350. * memset()-ing them.
  351. */
  352. MEM_STATIC void* ZSTD_cwksp_reserve_table(ZSTD_cwksp* ws, size_t bytes)
  353. {
  354. const ZSTD_cwksp_alloc_phase_e phase = ZSTD_cwksp_alloc_aligned;
  355. void* alloc;
  356. void* end;
  357. void* top;
  358. if (ZSTD_isError(ZSTD_cwksp_internal_advance_phase(ws, phase))) {
  359. return NULL;
  360. }
  361. alloc = ws->tableEnd;
  362. end = (BYTE *)alloc + bytes;
  363. top = ws->allocStart;
  364. DEBUGLOG(5, "cwksp: reserving %p table %zd bytes, %zd bytes remaining",
  365. alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
  366. assert((bytes & (sizeof(U32)-1)) == 0);
  367. ZSTD_cwksp_assert_internal_consistency(ws);
  368. assert(end <= top);
  369. if (end > top) {
  370. DEBUGLOG(4, "cwksp: table alloc failed!");
  371. ws->allocFailed = 1;
  372. return NULL;
  373. }
  374. ws->tableEnd = end;
  375. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  376. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  377. __asan_unpoison_memory_region(alloc, bytes);
  378. }
  379. #endif
  380. assert((bytes & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0);
  381. assert(((size_t)alloc & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
  382. return alloc;
  383. }
  384. /**
  385. * Aligned on sizeof(void*).
  386. * Note : should happen only once, at workspace first initialization
  387. */
  388. MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes)
  389. {
  390. size_t const roundedBytes = ZSTD_cwksp_align(bytes, sizeof(void*));
  391. void* alloc = ws->objectEnd;
  392. void* end = (BYTE*)alloc + roundedBytes;
  393. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  394. /* over-reserve space */
  395. end = (BYTE *)end + 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  396. #endif
  397. DEBUGLOG(4,
  398. "cwksp: reserving %p object %zd bytes (rounded to %zd), %zd bytes remaining",
  399. alloc, bytes, roundedBytes, ZSTD_cwksp_available_space(ws) - roundedBytes);
  400. assert((size_t)alloc % ZSTD_ALIGNOF(void*) == 0);
  401. assert(bytes % ZSTD_ALIGNOF(void*) == 0);
  402. ZSTD_cwksp_assert_internal_consistency(ws);
  403. /* we must be in the first phase, no advance is possible */
  404. if (ws->phase != ZSTD_cwksp_alloc_objects || end > ws->workspaceEnd) {
  405. DEBUGLOG(3, "cwksp: object alloc failed!");
  406. ws->allocFailed = 1;
  407. return NULL;
  408. }
  409. ws->objectEnd = end;
  410. ws->tableEnd = end;
  411. ws->tableValidEnd = end;
  412. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  413. /* Move alloc so there's ZSTD_CWKSP_ASAN_REDZONE_SIZE unused space on
  414. * either size. */
  415. alloc = (BYTE*)alloc + ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  416. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  417. __asan_unpoison_memory_region(alloc, bytes);
  418. }
  419. #endif
  420. return alloc;
  421. }
  422. MEM_STATIC void ZSTD_cwksp_mark_tables_dirty(ZSTD_cwksp* ws)
  423. {
  424. DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_dirty");
  425. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  426. /* To validate that the table re-use logic is sound, and that we don't
  427. * access table space that we haven't cleaned, we re-"poison" the table
  428. * space every time we mark it dirty. */
  429. {
  430. size_t size = (BYTE*)ws->tableValidEnd - (BYTE*)ws->objectEnd;
  431. assert(__msan_test_shadow(ws->objectEnd, size) == -1);
  432. __msan_poison(ws->objectEnd, size);
  433. }
  434. #endif
  435. assert(ws->tableValidEnd >= ws->objectEnd);
  436. assert(ws->tableValidEnd <= ws->allocStart);
  437. ws->tableValidEnd = ws->objectEnd;
  438. ZSTD_cwksp_assert_internal_consistency(ws);
  439. }
  440. MEM_STATIC void ZSTD_cwksp_mark_tables_clean(ZSTD_cwksp* ws) {
  441. DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_clean");
  442. assert(ws->tableValidEnd >= ws->objectEnd);
  443. assert(ws->tableValidEnd <= ws->allocStart);
  444. if (ws->tableValidEnd < ws->tableEnd) {
  445. ws->tableValidEnd = ws->tableEnd;
  446. }
  447. ZSTD_cwksp_assert_internal_consistency(ws);
  448. }
  449. /**
  450. * Zero the part of the allocated tables not already marked clean.
  451. */
  452. MEM_STATIC void ZSTD_cwksp_clean_tables(ZSTD_cwksp* ws) {
  453. DEBUGLOG(4, "cwksp: ZSTD_cwksp_clean_tables");
  454. assert(ws->tableValidEnd >= ws->objectEnd);
  455. assert(ws->tableValidEnd <= ws->allocStart);
  456. if (ws->tableValidEnd < ws->tableEnd) {
  457. ZSTD_memset(ws->tableValidEnd, 0, (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->tableValidEnd));
  458. }
  459. ZSTD_cwksp_mark_tables_clean(ws);
  460. }
  461. /**
  462. * Invalidates table allocations.
  463. * All other allocations remain valid.
  464. */
  465. MEM_STATIC void ZSTD_cwksp_clear_tables(ZSTD_cwksp* ws) {
  466. DEBUGLOG(4, "cwksp: clearing tables!");
  467. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  468. /* We don't do this when the workspace is statically allocated, because
  469. * when that is the case, we have no capability to hook into the end of the
  470. * workspace's lifecycle to unpoison the memory.
  471. */
  472. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  473. size_t size = (BYTE*)ws->tableValidEnd - (BYTE*)ws->objectEnd;
  474. __asan_poison_memory_region(ws->objectEnd, size);
  475. }
  476. #endif
  477. ws->tableEnd = ws->objectEnd;
  478. ZSTD_cwksp_assert_internal_consistency(ws);
  479. }
  480. /**
  481. * Invalidates all buffer, aligned, and table allocations.
  482. * Object allocations remain valid.
  483. */
  484. MEM_STATIC void ZSTD_cwksp_clear(ZSTD_cwksp* ws) {
  485. DEBUGLOG(4, "cwksp: clearing!");
  486. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  487. /* To validate that the context re-use logic is sound, and that we don't
  488. * access stuff that this compression hasn't initialized, we re-"poison"
  489. * the workspace (or at least the non-static, non-table parts of it)
  490. * every time we start a new compression. */
  491. {
  492. size_t size = (BYTE*)ws->workspaceEnd - (BYTE*)ws->tableValidEnd;
  493. __msan_poison(ws->tableValidEnd, size);
  494. }
  495. #endif
  496. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  497. /* We don't do this when the workspace is statically allocated, because
  498. * when that is the case, we have no capability to hook into the end of the
  499. * workspace's lifecycle to unpoison the memory.
  500. */
  501. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  502. size_t size = (BYTE*)ws->workspaceEnd - (BYTE*)ws->objectEnd;
  503. __asan_poison_memory_region(ws->objectEnd, size);
  504. }
  505. #endif
  506. ws->tableEnd = ws->objectEnd;
  507. ws->allocStart = ws->workspaceEnd;
  508. ws->allocFailed = 0;
  509. if (ws->phase > ZSTD_cwksp_alloc_buffers) {
  510. ws->phase = ZSTD_cwksp_alloc_buffers;
  511. }
  512. ZSTD_cwksp_assert_internal_consistency(ws);
  513. }
  514. /**
  515. * The provided workspace takes ownership of the buffer [start, start+size).
  516. * Any existing values in the workspace are ignored (the previously managed
  517. * buffer, if present, must be separately freed).
  518. */
  519. MEM_STATIC void ZSTD_cwksp_init(ZSTD_cwksp* ws, void* start, size_t size, ZSTD_cwksp_static_alloc_e isStatic) {
  520. DEBUGLOG(4, "cwksp: init'ing workspace with %zd bytes", size);
  521. assert(((size_t)start & (sizeof(void*)-1)) == 0); /* ensure correct alignment */
  522. ws->workspace = start;
  523. ws->workspaceEnd = (BYTE*)start + size;
  524. ws->objectEnd = ws->workspace;
  525. ws->tableValidEnd = ws->objectEnd;
  526. ws->phase = ZSTD_cwksp_alloc_objects;
  527. ws->isStatic = isStatic;
  528. ZSTD_cwksp_clear(ws);
  529. ws->workspaceOversizedDuration = 0;
  530. ZSTD_cwksp_assert_internal_consistency(ws);
  531. }
  532. MEM_STATIC size_t ZSTD_cwksp_create(ZSTD_cwksp* ws, size_t size, ZSTD_customMem customMem) {
  533. void* workspace = ZSTD_customMalloc(size, customMem);
  534. DEBUGLOG(4, "cwksp: creating new workspace with %zd bytes", size);
  535. RETURN_ERROR_IF(workspace == NULL, memory_allocation, "NULL pointer!");
  536. ZSTD_cwksp_init(ws, workspace, size, ZSTD_cwksp_dynamic_alloc);
  537. return 0;
  538. }
  539. MEM_STATIC void ZSTD_cwksp_free(ZSTD_cwksp* ws, ZSTD_customMem customMem) {
  540. void *ptr = ws->workspace;
  541. DEBUGLOG(4, "cwksp: freeing workspace");
  542. ZSTD_memset(ws, 0, sizeof(ZSTD_cwksp));
  543. ZSTD_customFree(ptr, customMem);
  544. }
  545. /**
  546. * Moves the management of a workspace from one cwksp to another. The src cwksp
  547. * is left in an invalid state (src must be re-init()'ed before it's used again).
  548. */
  549. MEM_STATIC void ZSTD_cwksp_move(ZSTD_cwksp* dst, ZSTD_cwksp* src) {
  550. *dst = *src;
  551. ZSTD_memset(src, 0, sizeof(ZSTD_cwksp));
  552. }
  553. MEM_STATIC size_t ZSTD_cwksp_sizeof(const ZSTD_cwksp* ws) {
  554. return (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->workspace);
  555. }
  556. MEM_STATIC size_t ZSTD_cwksp_used(const ZSTD_cwksp* ws) {
  557. return (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->workspace)
  558. + (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->allocStart);
  559. }
  560. MEM_STATIC int ZSTD_cwksp_reserve_failed(const ZSTD_cwksp* ws) {
  561. return ws->allocFailed;
  562. }
  563. /*-*************************************
  564. * Functions Checking Free Space
  565. ***************************************/
  566. /* ZSTD_alignmentSpaceWithinBounds() :
  567. * Returns if the estimated space needed for a wksp is within an acceptable limit of the
  568. * actual amount of space used.
  569. */
  570. MEM_STATIC int ZSTD_cwksp_estimated_space_within_bounds(const ZSTD_cwksp* const ws,
  571. size_t const estimatedSpace, int resizedWorkspace) {
  572. if (resizedWorkspace) {
  573. /* Resized/newly allocated wksp should have exact bounds */
  574. return ZSTD_cwksp_used(ws) == estimatedSpace;
  575. } else {
  576. /* Due to alignment, when reusing a workspace, we can actually consume 63 fewer or more bytes
  577. * than estimatedSpace. See the comments in zstd_cwksp.h for details.
  578. */
  579. return (ZSTD_cwksp_used(ws) >= estimatedSpace - 63) && (ZSTD_cwksp_used(ws) <= estimatedSpace + 63);
  580. }
  581. }
  582. MEM_STATIC size_t ZSTD_cwksp_available_space(ZSTD_cwksp* ws) {
  583. return (size_t)((BYTE*)ws->allocStart - (BYTE*)ws->tableEnd);
  584. }
  585. MEM_STATIC int ZSTD_cwksp_check_available(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  586. return ZSTD_cwksp_available_space(ws) >= additionalNeededSpace;
  587. }
  588. MEM_STATIC int ZSTD_cwksp_check_too_large(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  589. return ZSTD_cwksp_check_available(
  590. ws, additionalNeededSpace * ZSTD_WORKSPACETOOLARGE_FACTOR);
  591. }
  592. MEM_STATIC int ZSTD_cwksp_check_wasteful(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  593. return ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)
  594. && ws->workspaceOversizedDuration > ZSTD_WORKSPACETOOLARGE_MAXDURATION;
  595. }
  596. MEM_STATIC void ZSTD_cwksp_bump_oversized_duration(
  597. ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  598. if (ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)) {
  599. ws->workspaceOversizedDuration++;
  600. } else {
  601. ws->workspaceOversizedDuration = 0;
  602. }
  603. }
  604. #if defined (__cplusplus)
  605. }
  606. #endif
  607. #endif /* ZSTD_CWKSP_H */