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