1 /* 2 * Copyright (c) 2016-present, 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 11 12 13 /* ************************************** 14 * Compiler Warnings 15 ****************************************/ 16 #ifdef _MSC_VER 17 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ 18 #endif 19 20 21 /*-************************************* 22 * Includes 23 ***************************************/ 24 #include "platform.h" /* Large Files support */ 25 #include "util.h" /* UTIL_getFileSize, UTIL_getTotalFileSize */ 26 #include <stdlib.h> /* malloc, free */ 27 #include <string.h> /* memset */ 28 #include <stdio.h> /* fprintf, fopen, ftello64 */ 29 #include <errno.h> /* errno */ 30 #include <assert.h> 31 32 #include "mem.h" /* read */ 33 #include "error_private.h" 34 #include "dibio.h" 35 36 37 /*-************************************* 38 * Constants 39 ***************************************/ 40 #define KB *(1 <<10) 41 #define MB *(1 <<20) 42 #define GB *(1U<<30) 43 44 #define SAMPLESIZE_MAX (128 KB) 45 #define MEMMULT 11 /* rough estimation : memory cost to analyze 1 byte of sample */ 46 #define COVER_MEMMULT 9 /* rough estimation : memory cost to analyze 1 byte of sample */ 47 #define FASTCOVER_MEMMULT 1 /* rough estimation : memory cost to analyze 1 byte of sample */ 48 static const size_t g_maxMemory = (sizeof(size_t) == 4) ? (2 GB - 64 MB) : ((size_t)(512 MB) << sizeof(size_t)); 49 50 #define NOISELENGTH 32 51 52 53 /*-************************************* 54 * Console display 55 ***************************************/ 56 #define DISPLAY(...) fprintf(stderr, __VA_ARGS__) 57 #define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); } 58 59 static const U64 g_refreshRate = SEC_TO_MICRO / 6; 60 static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER; 61 62 #define DISPLAYUPDATE(l, ...) { if (displayLevel>=l) { \ 63 if ((UTIL_clockSpanMicro(g_displayClock) > g_refreshRate) || (displayLevel>=4)) \ 64 { g_displayClock = UTIL_getTime(); DISPLAY(__VA_ARGS__); \ 65 if (displayLevel>=4) fflush(stderr); } } } 66 67 /*-************************************* 68 * Exceptions 69 ***************************************/ 70 #ifndef DEBUG 71 # define DEBUG 0 72 #endif 73 #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__); 74 #define EXM_THROW(error, ...) \ 75 { \ 76 DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \ 77 DISPLAY("Error %i : ", error); \ 78 DISPLAY(__VA_ARGS__); \ 79 DISPLAY("\n"); \ 80 exit(error); \ 81 } 82 83 84 /* ******************************************************** 85 * Helper functions 86 **********************************************************/ 87 #undef MIN 88 #define MIN(a,b) ((a) < (b) ? (a) : (b)) 89 90 91 /* ******************************************************** 92 * File related operations 93 **********************************************************/ 94 /** DiB_loadFiles() : 95 * load samples from files listed in fileNamesTable into buffer. 96 * works even if buffer is too small to load all samples. 97 * Also provides the size of each sample into sampleSizes table 98 * which must be sized correctly, using DiB_fileStats(). 99 * @return : nb of samples effectively loaded into `buffer` 100 * *bufferSizePtr is modified, it provides the amount data loaded within buffer. 101 * sampleSizes is filled with the size of each sample. 102 */ 103 static unsigned DiB_loadFiles(void* buffer, size_t* bufferSizePtr, 104 size_t* sampleSizes, unsigned sstSize, 105 const char** fileNamesTable, unsigned nbFiles, size_t targetChunkSize, 106 unsigned displayLevel) 107 { 108 char* const buff = (char*)buffer; 109 size_t pos = 0; 110 unsigned nbLoadedChunks = 0, fileIndex; 111 112 for (fileIndex=0; fileIndex<nbFiles; fileIndex++) { 113 const char* const fileName = fileNamesTable[fileIndex]; 114 unsigned long long const fs64 = UTIL_getFileSize(fileName); 115 unsigned long long remainingToLoad = (fs64 == UTIL_FILESIZE_UNKNOWN) ? 0 : fs64; 116 U32 const nbChunks = targetChunkSize ? (U32)((fs64 + (targetChunkSize-1)) / targetChunkSize) : 1; 117 U64 const chunkSize = targetChunkSize ? MIN(targetChunkSize, fs64) : fs64; 118 size_t const maxChunkSize = (size_t)MIN(chunkSize, SAMPLESIZE_MAX); 119 U32 cnb; 120 FILE* const f = fopen(fileName, "rb"); 121 if (f==NULL) EXM_THROW(10, "zstd: dictBuilder: %s %s ", fileName, strerror(errno)); 122 DISPLAYUPDATE(2, "Loading %s... \r", fileName); 123 for (cnb=0; cnb<nbChunks; cnb++) { 124 size_t const toLoad = (size_t)MIN(maxChunkSize, remainingToLoad); 125 if (toLoad > *bufferSizePtr-pos) break; 126 { size_t const readSize = fread(buff+pos, 1, toLoad, f); 127 if (readSize != toLoad) EXM_THROW(11, "Pb reading %s", fileName); 128 pos += readSize; 129 sampleSizes[nbLoadedChunks++] = toLoad; 130 remainingToLoad -= targetChunkSize; 131 if (nbLoadedChunks == sstSize) { /* no more space left in sampleSizes table */ 132 fileIndex = nbFiles; /* stop there */ 133 break; 134 } 135 if (toLoad < targetChunkSize) { 136 fseek(f, (long)(targetChunkSize - toLoad), SEEK_CUR); 137 } } } 138 fclose(f); 139 } 140 DISPLAYLEVEL(2, "\r%79s\r", ""); 141 *bufferSizePtr = pos; 142 DISPLAYLEVEL(4, "loaded : %u KB \n", (unsigned)(pos >> 10)) 143 return nbLoadedChunks; 144 } 145 146 #define DiB_rotl32(x,r) ((x << r) | (x >> (32 - r))) 147 static U32 DiB_rand(U32* src) 148 { 149 static const U32 prime1 = 2654435761U; 150 static const U32 prime2 = 2246822519U; 151 U32 rand32 = *src; 152 rand32 *= prime1; 153 rand32 ^= prime2; 154 rand32 = DiB_rotl32(rand32, 13); 155 *src = rand32; 156 return rand32 >> 5; 157 } 158 159 /* DiB_shuffle() : 160 * shuffle a table of file names in a semi-random way 161 * It improves dictionary quality by reducing "locality" impact, so if sample set is very large, 162 * it will load random elements from it, instead of just the first ones. */ 163 static void DiB_shuffle(const char** fileNamesTable, unsigned nbFiles) { 164 U32 seed = 0xFD2FB528; 165 unsigned i; 166 assert(nbFiles >= 1); 167 for (i = nbFiles - 1; i > 0; --i) { 168 unsigned const j = DiB_rand(&seed) % (i + 1); 169 const char* const tmp = fileNamesTable[j]; 170 fileNamesTable[j] = fileNamesTable[i]; 171 fileNamesTable[i] = tmp; 172 } 173 } 174 175 176 /*-******************************************************** 177 * Dictionary training functions 178 **********************************************************/ 179 static size_t DiB_findMaxMem(unsigned long long requiredMem) 180 { 181 size_t const step = 8 MB; 182 void* testmem = NULL; 183 184 requiredMem = (((requiredMem >> 23) + 1) << 23); 185 requiredMem += step; 186 if (requiredMem > g_maxMemory) requiredMem = g_maxMemory; 187 188 while (!testmem) { 189 testmem = malloc((size_t)requiredMem); 190 requiredMem -= step; 191 } 192 193 free(testmem); 194 return (size_t)requiredMem; 195 } 196 197 198 static void DiB_fillNoise(void* buffer, size_t length) 199 { 200 unsigned const prime1 = 2654435761U; 201 unsigned const prime2 = 2246822519U; 202 unsigned acc = prime1; 203 size_t p=0;; 204 205 for (p=0; p<length; p++) { 206 acc *= prime2; 207 ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21); 208 } 209 } 210 211 212 static void DiB_saveDict(const char* dictFileName, 213 const void* buff, size_t buffSize) 214 { 215 FILE* const f = fopen(dictFileName, "wb"); 216 if (f==NULL) EXM_THROW(3, "cannot open %s ", dictFileName); 217 218 { size_t const n = fwrite(buff, 1, buffSize, f); 219 if (n!=buffSize) EXM_THROW(4, "%s : write error", dictFileName) } 220 221 { size_t const n = (size_t)fclose(f); 222 if (n!=0) EXM_THROW(5, "%s : flush error", dictFileName) } 223 } 224 225 226 typedef struct { 227 U64 totalSizeToLoad; 228 unsigned oneSampleTooLarge; 229 unsigned nbSamples; 230 } fileStats; 231 232 /*! DiB_fileStats() : 233 * Given a list of files, and a chunkSize (0 == no chunk, whole files) 234 * provides the amount of data to be loaded and the resulting nb of samples. 235 * This is useful primarily for allocation purpose => sample buffer, and sample sizes table. 236 */ 237 static fileStats DiB_fileStats(const char** fileNamesTable, unsigned nbFiles, size_t chunkSize, unsigned displayLevel) 238 { 239 fileStats fs; 240 unsigned n; 241 memset(&fs, 0, sizeof(fs)); 242 for (n=0; n<nbFiles; n++) { 243 U64 const fileSize = UTIL_getFileSize(fileNamesTable[n]); 244 U64 const srcSize = (fileSize == UTIL_FILESIZE_UNKNOWN) ? 0 : fileSize; 245 U32 const nbSamples = (U32)(chunkSize ? (srcSize + (chunkSize-1)) / chunkSize : 1); 246 U64 const chunkToLoad = chunkSize ? MIN(chunkSize, srcSize) : srcSize; 247 size_t const cappedChunkSize = (size_t)MIN(chunkToLoad, SAMPLESIZE_MAX); 248 fs.totalSizeToLoad += cappedChunkSize * nbSamples; 249 fs.oneSampleTooLarge |= (chunkSize > 2*SAMPLESIZE_MAX); 250 fs.nbSamples += nbSamples; 251 } 252 DISPLAYLEVEL(4, "Preparing to load : %u KB \n", (unsigned)(fs.totalSizeToLoad >> 10)); 253 return fs; 254 } 255 256 257 /*! ZDICT_trainFromBuffer_unsafe_legacy() : 258 Strictly Internal use only !! 259 Same as ZDICT_trainFromBuffer_legacy(), but does not control `samplesBuffer`. 260 `samplesBuffer` must be followed by noisy guard band to avoid out-of-buffer reads. 261 @return : size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`) 262 or an error code. 263 */ 264 size_t ZDICT_trainFromBuffer_unsafe_legacy(void* dictBuffer, size_t dictBufferCapacity, 265 const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples, 266 ZDICT_legacy_params_t parameters); 267 268 269 int DiB_trainFromFiles(const char* dictFileName, unsigned maxDictSize, 270 const char** fileNamesTable, unsigned nbFiles, size_t chunkSize, 271 ZDICT_legacy_params_t* params, ZDICT_cover_params_t* coverParams, 272 ZDICT_fastCover_params_t* fastCoverParams, int optimize) 273 { 274 unsigned const displayLevel = params ? params->zParams.notificationLevel : 275 coverParams ? coverParams->zParams.notificationLevel : 276 fastCoverParams ? fastCoverParams->zParams.notificationLevel : 277 0; /* should never happen */ 278 void* const dictBuffer = malloc(maxDictSize); 279 fileStats const fs = DiB_fileStats(fileNamesTable, nbFiles, chunkSize, displayLevel); 280 size_t* const sampleSizes = (size_t*)malloc(fs.nbSamples * sizeof(size_t)); 281 size_t const memMult = params ? MEMMULT : 282 coverParams ? COVER_MEMMULT: 283 FASTCOVER_MEMMULT; 284 size_t const maxMem = DiB_findMaxMem(fs.totalSizeToLoad * memMult) / memMult; 285 size_t loadedSize = (size_t) MIN ((unsigned long long)maxMem, fs.totalSizeToLoad); 286 void* const srcBuffer = malloc(loadedSize+NOISELENGTH); 287 int result = 0; 288 289 /* Checks */ 290 if ((!sampleSizes) || (!srcBuffer) || (!dictBuffer)) 291 EXM_THROW(12, "not enough memory for DiB_trainFiles"); /* should not happen */ 292 if (fs.oneSampleTooLarge) { 293 DISPLAYLEVEL(2, "! Warning : some sample(s) are very large \n"); 294 DISPLAYLEVEL(2, "! Note that dictionary is only useful for small samples. \n"); 295 DISPLAYLEVEL(2, "! As a consequence, only the first %u bytes of each sample are loaded \n", SAMPLESIZE_MAX); 296 } 297 if (fs.nbSamples < 5) { 298 DISPLAYLEVEL(2, "! Warning : nb of samples too low for proper processing ! \n"); 299 DISPLAYLEVEL(2, "! Please provide _one file per sample_. \n"); 300 DISPLAYLEVEL(2, "! Alternatively, split files into fixed-size blocks representative of samples, with -B# \n"); 301 EXM_THROW(14, "nb of samples too low"); /* we now clearly forbid this case */ 302 } 303 if (fs.totalSizeToLoad < (unsigned long long)(8 * maxDictSize)) { 304 DISPLAYLEVEL(2, "! Warning : data size of samples too small for target dictionary size \n"); 305 DISPLAYLEVEL(2, "! Samples should be about 100x larger than target dictionary size \n"); 306 } 307 308 /* init */ 309 if (loadedSize < fs.totalSizeToLoad) 310 DISPLAYLEVEL(1, "Not enough memory; training on %u MB only...\n", (unsigned)(loadedSize >> 20)); 311 312 /* Load input buffer */ 313 DISPLAYLEVEL(3, "Shuffling input files\n"); 314 DiB_shuffle(fileNamesTable, nbFiles); 315 316 DiB_loadFiles(srcBuffer, &loadedSize, sampleSizes, fs.nbSamples, fileNamesTable, nbFiles, chunkSize, displayLevel); 317 318 { size_t dictSize; 319 if (params) { 320 DiB_fillNoise((char*)srcBuffer + loadedSize, NOISELENGTH); /* guard band, for end of buffer condition */ 321 dictSize = ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, maxDictSize, 322 srcBuffer, sampleSizes, fs.nbSamples, 323 *params); 324 } else if (coverParams) { 325 if (optimize) { 326 dictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, maxDictSize, 327 srcBuffer, sampleSizes, fs.nbSamples, 328 coverParams); 329 if (!ZDICT_isError(dictSize)) { 330 unsigned splitPercentage = (unsigned)(coverParams->splitPoint * 100); 331 DISPLAYLEVEL(2, "k=%u\nd=%u\nsteps=%u\nsplit=%u\n", coverParams->k, coverParams->d, 332 coverParams->steps, splitPercentage); 333 } 334 } else { 335 dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, maxDictSize, srcBuffer, 336 sampleSizes, fs.nbSamples, *coverParams); 337 } 338 } else { 339 assert(fastCoverParams != NULL); 340 if (optimize) { 341 dictSize = ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, maxDictSize, 342 srcBuffer, sampleSizes, fs.nbSamples, 343 fastCoverParams); 344 if (!ZDICT_isError(dictSize)) { 345 unsigned splitPercentage = (unsigned)(fastCoverParams->splitPoint * 100); 346 DISPLAYLEVEL(2, "k=%u\nd=%u\nf=%u\nsteps=%u\nsplit=%u\naccel=%u\n", fastCoverParams->k, 347 fastCoverParams->d, fastCoverParams->f, fastCoverParams->steps, splitPercentage, 348 fastCoverParams->accel); 349 } 350 } else { 351 dictSize = ZDICT_trainFromBuffer_fastCover(dictBuffer, maxDictSize, srcBuffer, 352 sampleSizes, fs.nbSamples, *fastCoverParams); 353 } 354 } 355 if (ZDICT_isError(dictSize)) { 356 DISPLAYLEVEL(1, "dictionary training failed : %s \n", ZDICT_getErrorName(dictSize)); /* should not happen */ 357 result = 1; 358 goto _cleanup; 359 } 360 /* save dict */ 361 DISPLAYLEVEL(2, "Save dictionary of size %u into file %s \n", (unsigned)dictSize, dictFileName); 362 DiB_saveDict(dictFileName, dictBuffer, dictSize); 363 } 364 365 /* clean up */ 366 _cleanup: 367 free(srcBuffer); 368 free(sampleSizes); 369 free(dictBuffer); 370 return result; 371 } 372