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