File: wrapper.c

package info (click to toggle)
genwqe-user 4.0.20-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,372 kB
  • sloc: ansic: 18,786; sh: 2,382; makefile: 420
file content (1574 lines) | stat: -rw-r--r-- 39,131 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
/*
 * Copyright 2015, 2016, International Business Machines
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <limits.h>
#include <pthread.h>

#include <zlib.h>		/* standard interface */
#include "libddcb.h"
#include "wrapper.h"

/*
 * Functionality to switch between hardware and software zlib
 * implementations. Enhanced by tracing functionality for debugging
 * and workload analysis. Hardware performs best with sufficiently
 * large input and output buffers.
 *
 * FIXME setDictionary code needs to be properly tested and reviewed.
 *       Most likely it is not working right and needs to be fixed too.
 *
 * The 1st implementation to fallback to SW if the input buffer for
 * inflate is too small was to delay the h_inflateInit until init was
 * called. This finally resulted in a solution where in inflateReset I
 * called inflateEnd, which was causing inflateInit in inflate. This
 * might call obsolete memory allocations and freeing. Therefore I
 * gave up this approach and try to do the inflateEnd and new
 * inflateInit only if the fallback occurs.
 */

/*
 * Select default setting for accelerated zlib. Older version used
 * software as default. Since the library is packaged as extra
 * libz.so, we assume that users of it like to use hardware as
 * default.
 */
#define CONFIG_INFLATE_IMPL	 (ZLIB_HW_IMPL | ZLIB_FLAG_OMIT_LAST_DICT)
#define CONFIG_DEFLATE_IMPL	 (ZLIB_HW_IMPL | ZLIB_FLAG_OMIT_LAST_DICT)

#ifndef DEF_WBITS
#  define DEF_WBITS MAX_WBITS
#endif
/* default windowBits for decompression. MAX_WBITS is for compression only */

#if MAX_MEM_LEVEL >= 8
#  define DEF_MEM_LEVEL 8
#else
#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
#endif
/* default memLevel */

#define ZLIB_MAXDICTLEN		 (32 * 1024)

/* Good values are something like 8KiB or 16KiB */
#define CONFIG_INFLATE_THRESHOLD (16 * 1024)  /* 0: disabled */

int zlib_trace = 0x0;		/* no trace by default */
FILE *zlib_log = NULL;		/* default is stderr, unless overwritten */
int zlib_accelerator = DDCB_TYPE_GENWQE;
int zlib_card = -1;		/* Using redundant now as default */

unsigned int zlib_inflate_impl  = (CONFIG_INFLATE_IMPL &  ZLIB_IMPL_MASK);
unsigned int zlib_deflate_impl  = (CONFIG_DEFLATE_IMPL &  ZLIB_IMPL_MASK);
unsigned int zlib_inflate_flags = (CONFIG_INFLATE_IMPL & ~ZLIB_IMPL_MASK);
unsigned int zlib_deflate_flags = (CONFIG_DEFLATE_IMPL & ~ZLIB_IMPL_MASK);

static unsigned int zlib_inflate_threshold = CONFIG_INFLATE_THRESHOLD;
pthread_mutex_t zlib_stats_mutex; /* mutex to protect global stats */
struct zlib_stats zlib_stats;	/* global statistics */

/**
 * wrapper internal_state, hw/sw have different view of what
 * internal_state is.
 *
 * NOTE: Since we change the way the software zlib code is invoked,
 * from statically linking a z_ prefixed version to a version which
 * tries to load the code va dlopen/dlsym, we have now situations,
 * where the software libz calls functions like
 * inflate/deflateReset(2). In those cases the strm->state pointer
 * does not point to our own struct _internal_state, but to the
 * software internal state. As temporary or even final circumvention
 * we add here MAGIC0 and MAGIC1 to figure out the difference. If the
 * magic numbers are not setup right, we call the software variant.
 */
#define MAGIC0 0x1122334455667788ull
#define MAGIC1 0xaabbccddeeff00aaull

struct _internal_state {
	uint64_t magic0;
	enum zlib_impl impl;	/* hardware or software implementation */
	void *priv_data;	/* state from level below */
	bool allow_switching;

	/* For delayed inflateInit2() we need to remember parameters */
	int level;
	int method;
	int windowBits;
	int memLevel;
	int strategy;
	const char *version;
	int stream_size;
	gz_headerp gzhead;
	uint64_t magic1;

	Bytef *dictionary;	/* backlevel support for sw zlib < 1.2.8 */
	uInt dictLength;
};

static int has_wrapper_state(z_streamp strm)
{
	struct _internal_state *w;

	if (strm == NULL)
		return 0;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return 0;

	return ((w->magic0 == MAGIC0) && (w->magic1 == MAGIC1));
}

void zlib_set_accelerator(const char *accel, int card_no)
{
	if (strncmp(accel, "CAPI", 4) == 0)
		zlib_accelerator = DDCB_TYPE_CAPI;
	else
		zlib_accelerator = DDCB_TYPE_GENWQE;

	zlib_card = card_no;
}

void zlib_set_inflate_impl(enum zlib_impl impl)
{
	zlib_inflate_impl = impl;
}

void zlib_set_deflate_impl(enum zlib_impl impl)
{
	zlib_deflate_impl = impl;
}

/**
 * str_to_num - Convert string into number and copy with endings like
 *              KiB for kilobyte
 *              MiB for megabyte
 *              GiB for gigabyte
 */
uint64_t str_to_num(char *str)
{
	char *s = str;
	uint64_t num = strtoull(s, &s, 0);

	if (*s == '\0')
		return num;

	if (strcmp(s, "KiB") == 0)
		num *= 1024;
	else if (strcmp(s, "MiB") == 0)
		num *= 1024 * 1024;
	else if (strcmp(s, "GiB") == 0)
		num *= 1024 * 1024 * 1024;
	else {
		num = ULLONG_MAX;
		errno = ERANGE;
	}

	return num;
}

/**
 * Pretty print libz return codes for tracing.
 */
const char *ret_to_str(int ret)
{
	switch (ret) {
	case Z_OK:	      return "Z_OK";
	case Z_STREAM_END:    return "Z_STREAM_END";
	case Z_NEED_DICT:     return "Z_NEED_DICT";
	case Z_ERRNO:	      return "Z_ERRNO";
	case Z_STREAM_ERROR:  return "Z_STREAM_ERROR";
	case Z_DATA_ERROR:    return "Z_DATA_ERROR";
	case Z_MEM_ERROR:     return "Z_MEM_ERROR";
	case Z_BUF_ERROR:     return "Z_BUF_ERROR";
	case Z_VERSION_ERROR: return "Z_BUF_ERROR";
	default:	      return "UNKNOWN";
	}
}

/**
 * Pretty print flush codes for tracing.
 */
const char *flush_to_str(int flush)
{
	switch (flush) {
	case Z_NO_FLUSH:      return "Z_NO_FLUSH";
	case Z_PARTIAL_FLUSH: return "Z_PARTIAL_FLUSH";
	case Z_SYNC_FLUSH:    return "Z_SYNC_FLUSH";
	case Z_FULL_FLUSH:    return "Z_FULL_FLUSH";
	case Z_FINISH:	      return "Z_FINISH";
	case Z_BLOCK:	      return "Z_BLOCK";
#if defined(Z_TREES)		/* older zlibs do not have this */
	case Z_TREES:	      return "Z_TREES";
#endif
	default:	      return "UNKNOWN";
	}
}

static void _init(void) __attribute__((constructor));

/**
 * FIXME With the new zlib load mechanism a new problem arose: How do
 * I prevent us from loading ourselves?
 */
static void _init(void)
{
	int rc;
	const char *trace, *inflate_impl, *deflate_impl, *method;
	const char *zlib_logfile = NULL;
	char *inflate_threshold;

	zlib_logfile = getenv("ZLIB_LOGFILE");
	if (zlib_logfile != NULL) {
		zlib_log = fopen(zlib_logfile, "a+");
		if (zlib_log == NULL)
			zlib_log = stderr;
	} else zlib_log = stderr;

	trace = getenv("ZLIB_TRACE");
	if (trace != NULL)
		zlib_trace = strtol(trace, (char **)NULL, 0);

	deflate_impl  = getenv("ZLIB_DEFLATE_IMPL");
	if (deflate_impl != NULL) {
		zlib_deflate_impl = strtol(deflate_impl, (char **)NULL, 0);
		zlib_deflate_flags = zlib_deflate_impl & ~ZLIB_IMPL_MASK;
		zlib_deflate_impl &= ZLIB_IMPL_MASK;
		if (zlib_deflate_impl >= ZLIB_MAX_IMPL)
			zlib_deflate_impl = ZLIB_SW_IMPL;
	}

	inflate_impl = getenv("ZLIB_INFLATE_IMPL");
	if (inflate_impl != NULL) {
		zlib_inflate_impl = strtol(inflate_impl, (char **)NULL, 0);
		zlib_inflate_flags = zlib_inflate_impl & ~ZLIB_IMPL_MASK;
		zlib_inflate_impl &= ZLIB_IMPL_MASK;
		if (zlib_inflate_impl >= ZLIB_MAX_IMPL)
			zlib_inflate_impl = ZLIB_SW_IMPL;
	}

	inflate_threshold = getenv("ZLIB_INFLATE_THRESHOLD");
	if (inflate_threshold != NULL)
		zlib_inflate_threshold = str_to_num(inflate_threshold);

	/*
	 * Do it similar like zOS did it, such that we can share
	 * test-cases and documentation. If _HZC_COMPRESSION_METHOD is
	 * matching the string "software" we enforce software
	 * operation.
	 */
	method = getenv("_HZC_COMPRESSION_METHOD");
	if ((method != NULL) && (strcmp(method, "software") == 0)) {
		zlib_inflate_impl = ZLIB_SW_IMPL;
		zlib_deflate_impl = ZLIB_SW_IMPL;
	}

	pr_trace("%s: BUILD=%s ZLIB_TRACE=%x ZLIB_INFLATE_IMPL=%d "
		 "ZLIB_DEFLATE_IMPL=%d ZLIB_INFLATE_THRESHOLD=%d\n",
		 __func__, GIT_VERSION, zlib_trace,
		 zlib_inflate_impl, zlib_deflate_impl, zlib_inflate_threshold);

	if (zlib_gather_statistics()) {
		rc = pthread_mutex_init(&zlib_stats_mutex, NULL);
		if (rc != 0)
			pr_err("initializing phtread_mutex failed!\n");
	}

	/* Software is done first such that zlibVersion already work */
	zedc_sw_init();
	zedc_hw_init();
}

static void __deflate_update_totals(z_streamp strm)
{
	unsigned int total_in_slot, total_out_slot;

	if (strm->total_in) {
		total_in_slot = strm->total_in / 4096;
		if (total_in_slot >= ZLIB_SIZE_SLOTS)
			total_in_slot = ZLIB_SIZE_SLOTS - 1;
		zlib_stats.deflate_total_in[total_in_slot]++;
	}
	if (strm->total_out) {
		total_out_slot = strm->total_out / 4096;
		if (total_out_slot >= ZLIB_SIZE_SLOTS)
			total_out_slot = ZLIB_SIZE_SLOTS - 1;
		zlib_stats.deflate_total_out[total_out_slot]++;
	}
}

static void __inflate_update_totals(z_streamp strm)
{
	unsigned int total_in_slot, total_out_slot;

	if (strm->total_in) {
		total_in_slot = strm->total_in / 4096;
		if (total_in_slot >= ZLIB_SIZE_SLOTS)
			total_in_slot = ZLIB_SIZE_SLOTS - 1;
		zlib_stats.inflate_total_in[total_in_slot]++;
	}

	if (strm->total_out) {
		total_out_slot = strm->total_out / 4096;
		if (total_out_slot >= ZLIB_SIZE_SLOTS)
			total_out_slot = ZLIB_SIZE_SLOTS - 1;
		zlib_stats.inflate_total_out[total_out_slot]++;
	}
}

/**
 * Some statistics we print always, others we just print if someone
 * actually called the function. Print out variable if it is not
 * 0. Use variable name as string for the description.
 */
#define __sss(s...)       #s
#define __stringify(s...) __sss(s)

#define pr_stat(s, var) do {						\
		if ((s)->var)						\
			pr_info("%s: %lu\n", __stringify(var), (s)->var); \
	} while (0)

/**
 * __print_stats(): When library is not used any longer, print out
 * statistics e.g. when trace flag is set. This function is not
 * locking stats_mutex.
 */
static void __print_stats(void)
{
	unsigned int i;
	struct zlib_stats *s = &zlib_stats;

	pthread_mutex_lock(&zlib_stats_mutex);
	pr_info("deflateInit: %ld\n", s->deflateInit);
	pr_info("deflate: %ld sw: %ld hw: %ld\n",
		s->deflate[ZLIB_SW_IMPL] + s->deflate[ZLIB_HW_IMPL],
		s->deflate[ZLIB_SW_IMPL], s->deflate[ZLIB_HW_IMPL]);

	for (i = 0; i < ARRAY_SIZE(s->deflate_avail_in); i++) {
		if (s->deflate_avail_in[i] == 0)
			continue;
		pr_info("  deflate_avail_in %4i KiB: %ld\n",
			(i + 1) * 4, s->deflate_avail_in[i]);
	}
	for (i = 0; i < ARRAY_SIZE(s->deflate_avail_out); i++) {
		if (s->deflate_avail_out[i] == 0)
			continue;
		pr_info("  deflate_avail_out %4i KiB: %ld\n",
			(i + 1) * 4, s->deflate_avail_out[i]);
	}
	for (i = 0; i < ARRAY_SIZE(s->deflate_total_in); i++) {
		if (s->deflate_total_in[i] == 0)
			continue;
		pr_info("  deflate_total_in %4i KiB: %ld\n",
			(i + 1) * 4, s->deflate_total_in[i]);
	}
	for (i = 0; i < ARRAY_SIZE(s->deflate_total_out); i++) {
		if (s->deflate_total_out[i] == 0)
			continue;
		pr_info("  deflate_total_out %4i KiB: %ld\n",
			(i + 1) * 4, s->deflate_total_out[i]);
	}

	pr_stat(s, deflateReset);
	pr_stat(s, deflateParams);
	pr_stat(s, deflateBound);
	pr_stat(s, deflateSetDictionary);
	pr_stat(s, deflateSetHeader);
	pr_stat(s, deflatePrime);
	pr_stat(s, deflateCopy);

	pr_info("deflateEnd: %ld\n", s->deflateEnd);
	pr_info("inflateInit: %ld\n", s->inflateInit);
	pr_info("inflate: %ld sw: %ld hw: %ld\n",
		s->inflate[ZLIB_SW_IMPL] + s->inflate[ZLIB_HW_IMPL],
		s->inflate[ZLIB_SW_IMPL], s->inflate[ZLIB_HW_IMPL]);

	for (i = 0; i < ARRAY_SIZE(s->inflate_avail_in); i++) {
		if (s->inflate_avail_in[i] == 0)
			continue;
		pr_info("  inflate_avail_in %4i KiB: %ld\n",
			(i + 1) * 4, s->inflate_avail_in[i]);
	}
	for (i = 0; i < ARRAY_SIZE(s->inflate_avail_out); i++) {
		if (s->inflate_avail_out[i] == 0)
			continue;
		pr_info("  inflate_avail_out %4i KiB: %ld\n",
			(i + 1) * 4, s->inflate_avail_out[i]);
	}
	for (i = 0; i < ARRAY_SIZE(s->inflate_total_in); i++) {
		if (s->inflate_total_in[i] == 0)
			continue;
		pr_info("  inflate_total_in %4i KiB: %ld\n",
			(i + 1) * 4, s->inflate_total_in[i]);
	}
	for (i = 0; i < ARRAY_SIZE(s->inflate_total_out); i++) {
		if (s->inflate_total_out[i] == 0)
			continue;
		pr_info("  inflate_total_out %4i KiB: %ld\n",
			(i + 1) * 4, s->inflate_total_out[i]);
	}

	pr_stat(s, inflateReset);
	pr_stat(s, inflateReset2);
	pr_stat(s, inflateSetDictionary);
	pr_stat(s, inflateGetDictionary);
	pr_stat(s, inflateGetHeader);
	pr_stat(s, inflateSync);
	pr_stat(s, inflatePrime);
	pr_stat(s, inflateCopy);

	pr_info("inflateEnd: %ld\n", s->inflateEnd);

	pr_stat(s, adler32);
	pr_stat(s, adler32_combine);
	pr_stat(s, crc32);
	pr_stat(s, crc32_combine);
	pr_stat(s, adler32_combine64);
	pr_stat(s, crc32_combine64);
	pr_stat(s, get_crc_table);

	pr_stat(s, gzopen64);
	pr_stat(s, gzopen);
	pr_stat(s, gzdopen);
	pr_stat(s, gzbuffer);
	pr_stat(s, gztell64);
	pr_stat(s, gztell);
	pr_stat(s, gzseek64);
	pr_stat(s, gzseek);
	pr_stat(s, gzwrite);
	pr_stat(s, gzread);
	pr_stat(s, gzclose);
	pr_stat(s, gzoffset64);
	pr_stat(s, gzoffset);
	pr_stat(s, gzrewind);
	pr_stat(s, gzputs);
	pr_stat(s, gzgets);
	pr_stat(s, gzputc);
	pr_stat(s, gzgetc);
	pr_stat(s, gzungetc);
	pr_stat(s, gzprintf);
	pr_stat(s, gzerror);
	pr_stat(s, gzeof);
	pr_stat(s, gzflush);

	pr_stat(s, compress);
	pr_stat(s, compress2);
	pr_stat(s, compressBound);
	pr_stat(s, uncompress);

	pthread_mutex_unlock(&zlib_stats_mutex);
}

/**
 * If there is no hardware available we retry automatically the
 * software version.
 */
static int __deflateInit2_(z_streamp strm, struct _internal_state *w)
{
	int rc = Z_OK;
	int retries = 0;

	/* drop to SW mode, HW does not support level 0 */
	if (w->level == Z_NO_COMPRESSION)
		w->impl = ZLIB_SW_IMPL;

	do {
		pr_trace("[%p] __deflateInit2_: w=%p level=%d method=%d "
			 "windowBits=%d memLevel=%d strategy=%d version=%s/%s "
			 "stream_size=%d impl=%d\n",
			 strm, w, w->level, w->method, w->windowBits,
			 w->memLevel, w->strategy, w->version,
			 zlibVersion(), w->stream_size, w->impl);

		rc = w->impl ? h_deflateInit2_(strm, w->level, w->method,
					       w->windowBits, w->memLevel,
					       w->strategy, w->version,
					       w->stream_size) :
			       z_deflateInit2_(strm, w->level, w->method,
					       w->windowBits, w->memLevel,
					       w->strategy, w->version,
					       w->stream_size);
		if (rc != Z_OK) {
			pr_trace("[%p] %s: fallback to software (rc=%d)\n",
				 strm, __func__, rc);
			w->impl = ZLIB_SW_IMPL;
			retries++;
		}
	} while ((retries < 2) && (rc != Z_OK));

	return rc;
}

/**
 * deflateInit2_() - Initialize deflate context. If the hardware
 * implementation fails for some reason the code tries the software
 * version.
 */
int deflateInit2_(z_streamp strm,
		  int level,
		  int method,
		  int windowBits,
		  int memLevel,
		  int strategy,
		  const char *version,
		  int stream_size)
{
	int rc = Z_OK;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	zlib_stats_inc(&zlib_stats.deflateInit);

	w = calloc(1, sizeof(*w));
	if (w == NULL)
		return Z_ERRNO;

	w->magic0 = MAGIC0;
	w->magic1 = MAGIC1;
	w->level = level;
	w->method = method;
	w->windowBits = windowBits;
	w->memLevel = memLevel;
	w->strategy = strategy;
	w->version = version;
	w->stream_size = stream_size;
	w->priv_data = NULL;
	w->impl = zlib_deflate_impl; /* try default first */

	rc = __deflateInit2_(strm, w);
	if (rc != Z_OK) {
		free(w);
	} else {
		w->priv_data = strm->state;	/* backup sublevel state */
		strm->state = (void *)w;
	}
	return rc;
}

int deflateInit_(z_streamp strm, int level, const char *version,
		 int stream_size)
{
	return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
			     Z_DEFAULT_STRATEGY, version, stream_size);
}

int deflateReset(z_streamp strm)
{
	int rc;
	struct _internal_state *w;

	if (!has_wrapper_state(strm))
		return z_deflateReset(strm);

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	pr_trace("[%p] deflateReset w=%p impl=%d\n", strm, w, w->impl);
	if (zlib_gather_statistics()) {
		pthread_mutex_lock(&zlib_stats_mutex);
		zlib_stats.deflateReset++;
		__deflate_update_totals(strm);
		pthread_mutex_unlock(&zlib_stats_mutex);
	}

	strm->state = w->priv_data;
	rc = w->impl ? h_deflateReset(strm) :
		       z_deflateReset(strm);

	strm->state = (void *)w;
	return rc;
}

int deflateSetDictionary(z_streamp strm,
			 const Bytef *dictionary,
			 uInt  dictLength)
{
	int rc;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	pr_trace("[%p] deflateSetDictionary: dictionary=%p dictLength=%d "
		 "adler32=%08llx\n", strm, dictionary, dictLength,
		 (long long)z_adler32(1, dictionary, dictLength));

	zlib_stats_inc(&zlib_stats.deflateSetDictionary);

	strm->state = w->priv_data;
	rc = w->impl ? h_deflateSetDictionary(strm, dictionary, dictLength) :
		       z_deflateSetDictionary(strm, dictionary, dictLength);
	
	pr_trace("[%p]    calculated adler32=%08x\n", strm,
		 (unsigned int)strm->adler);
	strm->state = (void *)w;

	return rc;
}

int deflateSetHeader(z_streamp strm, gz_headerp head)
{
	int rc;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	pr_trace("[%p] deflateSetHeader\n", strm);
	zlib_stats_inc(&zlib_stats.deflateSetHeader);

	strm->state = w->priv_data;
	rc = w->impl ? h_deflateSetHeader(strm, head) :
		       z_deflateSetHeader(strm, head);
	strm->state = (void *)w;

	return rc;
}

int deflatePrime(z_streamp strm, int bits, int value)
{
	int rc;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	zlib_stats_inc(&zlib_stats.deflatePrime);

	strm->state = w->priv_data;
	rc = w->impl ? Z_UNSUPPORTED :
		       z_deflatePrime(strm, bits, value);
	strm->state = (void *)w;

	return rc;
}

int deflateCopy(z_streamp dest, z_streamp source)
{
	int rc;
	struct _internal_state *w_source;
	struct _internal_state *w_dest;

	pr_trace("[%p] deflateCopy: dest=%p source=%p\n",
		 source, dest, source);

	if ((dest == NULL) || (source == NULL))
		return Z_STREAM_ERROR;

	memcpy(dest, source, sizeof(*dest));

	w_source = (struct _internal_state *)source->state;
	if (w_source == NULL)
		return Z_STREAM_ERROR;

	zlib_stats_inc(&zlib_stats.deflateCopy);

	w_dest = calloc(1, sizeof(*w_dest));
	if (w_dest == NULL)
		return Z_ERRNO;

	memcpy(w_dest, w_source, sizeof(*w_dest));
	source->state = w_source->priv_data;
	dest->state = NULL;	/* this needs to be created */

	rc = w_source->impl ? h_deflateCopy(dest, source):
			      z_deflateCopy(dest, source);
	if (rc != Z_OK) {
		pr_err("[%p] deflateCopy returned %d\n", source, rc);
		free(w_dest);
		w_dest = NULL;
		goto err_out;
	}

	w_dest->priv_data = dest->state;
	dest->state   = (void *)w_dest;

 err_out:
	source->state = (void *)w_source;
	return rc;
}

int deflate(z_streamp strm, int flush)
{
	int rc = 0;
	struct _internal_state *w;
	unsigned int avail_in_slot, avail_out_slot;

	if (0 == has_wrapper_state(strm)) {
		rc = z_deflate(strm, flush);
		return rc;
	}

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	if (zlib_gather_statistics()) {
		pthread_mutex_lock(&zlib_stats_mutex);
		avail_in_slot = strm->avail_in / 4096;
		if (avail_in_slot >= ZLIB_SIZE_SLOTS)
			avail_in_slot = ZLIB_SIZE_SLOTS - 1;
		zlib_stats.deflate_avail_in[avail_in_slot]++;

		avail_out_slot = strm->avail_out / 4096;
		if (avail_out_slot >= ZLIB_SIZE_SLOTS)
			avail_out_slot = ZLIB_SIZE_SLOTS - 1;
		zlib_stats.deflate_avail_out[avail_out_slot]++;
		zlib_stats.deflate[w->impl]++;
		pthread_mutex_unlock(&zlib_stats_mutex);
	}

	pr_trace("[%p] deflate:   flush=%s next_in=%p avail_in=%d "
		 "next_out=%p avail_out=%d total_out=%ld crc/adler=%08lx "
		 "impl=%d\n", strm, flush_to_str(flush), strm->next_in,
		 strm->avail_in, strm->next_out, strm->avail_out,
		 strm->total_out, strm->adler, w->impl);

	strm->state = w->priv_data;
	/* impl can only be ZLIB_HW_IMPL or ZLIB_SW_IMPL */
	switch (w->impl) {
	case ZLIB_HW_IMPL:
		rc = h_deflate(strm, flush);
		break;
	case ZLIB_SW_IMPL:
		rc = z_deflate(strm, flush);
		break;
	default:
		pr_trace("[%p] deflate: impl (%d) is not valid for me\n",
			 strm, w->impl);
		break;
	}
	strm->state = (void *)w;

	pr_trace("[%p]            flush=%s next_in=%p avail_in=%d "
		 "next_out=%p avail_out=%d total_out=%ld crc/adler=%08lx "
		 "rc=%s\n", strm, flush_to_str(flush), strm->next_in,
		 strm->avail_in, strm->next_out, strm->avail_out,
		 strm->total_out, strm->adler, ret_to_str(rc));

	return rc;
}

static int __deflateEnd(z_streamp strm, struct _internal_state *w)
{
	int rc;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	if (w == NULL)
		return Z_STREAM_ERROR;

	strm->state = w->priv_data;
	rc = w->impl ? h_deflateEnd(strm) :
		       z_deflateEnd(strm);
	strm->state = NULL;

	return rc;
}

uLong deflateBound(z_streamp strm, uLong sourceLen)
{
	int rc;
	struct _internal_state *w;

	if (strm == NULL) {
		return MAX(h_deflateBound(NULL, sourceLen),
			   z_deflateBound(NULL, sourceLen));
	}

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	zlib_stats_inc(&zlib_stats.deflateBound);

	strm->state = w->priv_data;
	rc = w->impl ? h_deflateBound(strm, sourceLen) :
		       z_deflateBound(strm, sourceLen);

	strm->state = (void *)w;
	return rc;
}

int deflateEnd(z_streamp strm)
{
	int rc;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	if (zlib_gather_statistics()) {
		pthread_mutex_lock(&zlib_stats_mutex);
		zlib_stats.deflateEnd++;
		__deflate_update_totals(strm);
		pthread_mutex_unlock(&zlib_stats_mutex);
	}

	rc = __deflateEnd(strm, w);

	pr_trace("[%p] deflateEnd w=%p rc=%d\n", strm, w, rc);
	free(w);

	return rc;
}

/**
 * HW283780 LIR 40774: java.lang.InternalError seen when NoCompression
 * is set in Hardware Mode on Linux P
 *
 * Once we are in HW compression mode the HW will always do the
 * same. There is not chance here, like it is in software to change
 * the level or strategy. We return Z_OK to keep the calling code
 * happy. If that code would start checking the resulting data, it
 * will see that the HW compression was not doing what it was supposed
 * to do e.g. do a sync and produce copy-blocks e.g. when level is set
 * to 0.
 */
int deflateParams(z_streamp strm, int level, int strategy)
{
	int rc = Z_OK;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	/* Let us adjust level and strategy */
	w->level = level;
	w->strategy = strategy;
	zlib_stats_inc(&zlib_stats.deflateParams);

	pr_trace("[%p] deflateParams level=%d strategy=%d impl=%d\n",
		 strm, level, strategy, w->impl);

	strm->state = w->priv_data;
	switch (w->impl) {
	case ZLIB_HW_IMPL:
		/*
                 * For the Z_NO_COMPRESSION case, implement fallback
                 * to software. This is for the case where w->level
                 * was have been setup by deflateParams().
		 */
		if ((strm->total_in != 0) || (w->level != Z_NO_COMPRESSION)) {
			strm->state = (void *)w;
			return Z_OK;
		}

		/* Redo initialization in software mode */
		pr_trace("[%p]   Z_NO_COMPRESSION total_in=%ld\n",
			 strm, strm->total_in);

		rc = __deflateEnd(strm, w);
		if (rc != Z_OK)
			goto err;

		strm->total_in = 0;
		strm->total_out = 0;

		rc = __deflateInit2_(strm, w);
		if (rc != Z_OK)
			goto err;

		w->priv_data = strm->state; /* backup sublevel state */
		break;
	case ZLIB_SW_IMPL:
		rc = z_deflateParams(strm, level, strategy);
		break;
	default:
		pr_err("[%p] deflateParams impl=%d invalid\n", strm, w->impl);
		break;
	}

 err:
	strm->state = (void *)w;
	return rc;
}

static int __inflateInit2_(z_streamp strm, struct _internal_state *w)
{
	int rc, retries;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	if (w == NULL)
		return Z_STREAM_ERROR;

	retries = 0;
	do {
		pr_trace("[%p] inflateInit2_: w=%p windowBits=%d "
			 "version=%s/%s stream_size=%d impl=%d\n",
			 strm, w, w->windowBits,
			 w->version, zlibVersion(), w->stream_size, w->impl);

		rc = w->impl ? h_inflateInit2_(strm, w->windowBits, w->version,
					       w->stream_size) :
			       z_inflateInit2_(strm, w->windowBits, w->version,
					       w->stream_size);
		if (Z_OK == rc)
			break;	/* OK, i Can exit now */

		pr_trace("[%p] %s: fallback to software (rc=%d)\n",
			 strm, __func__, rc);
		w->impl = ZLIB_SW_IMPL;
		w->allow_switching = false;

		retries++;
	} while (retries < 2);

	if (rc != Z_OK)
		goto err;

	w->priv_data = strm->state;		/* backup sublevel state */
 err:
	return rc;
}

int inflateInit2_(z_streamp strm, int  windowBits,
		  const char *version, int stream_size)
{
	int rc = Z_OK;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	strm->total_in = 0;
	strm->total_out = 0;
	zlib_stats_inc(&zlib_stats.inflateInit);

	w = calloc(1, sizeof(*w));
	if (w == NULL)
		return Z_MEM_ERROR;

	w->allow_switching = true;
	w->magic0 = MAGIC0;
	w->magic1 = MAGIC1;
	w->windowBits = windowBits;
	w->version = version;
	w->stream_size = stream_size;
	w->priv_data = NULL;
	w->impl = zlib_inflate_impl; /* try default first */
	w->dictLength = 0;

	if (!z_hasGetDictionary()) {
		w->dictionary = calloc(1, ZLIB_MAXDICTLEN);
		if (w->dictionary == NULL) {
			rc = Z_MEM_ERROR;
			goto free_w;
		}
	}

	rc = __inflateInit2_(strm, w);
	if (rc == Z_OK)
		strm->state = (void *)w;
	else
		goto free_dict;

	return rc;

 free_dict:
	if (w->dictionary) {
		free(w->dictionary);
		w->dictionary = NULL;
	}
 free_w:
	free(w);
	return rc;
}

int inflateInit_(z_streamp strm, const char *version, int stream_size)
{
	return inflateInit2_(strm, DEF_WBITS, version, stream_size);
}

int inflateReset(z_streamp strm)
{
	int rc;
	struct _internal_state *w;

	if (!has_wrapper_state(strm))
		return z_inflateReset(strm);

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	/*
	 * We need to count even though priv_data could still be
	 * NULL. Otherwise the statistics will not be right at the
	 * end.
	 */
	pr_trace("[%p] inflateReset\n", strm);
	if (zlib_gather_statistics()) {
		pthread_mutex_lock(&zlib_stats_mutex);
		zlib_stats.inflateReset++;
		__inflate_update_totals(strm);
		pthread_mutex_unlock(&zlib_stats_mutex);
	}

	w->allow_switching = true;
	w->gzhead = NULL;	/* clear gz header */
	w->dictLength = 0;	/* clear cached dictionary */

	strm->state = w->priv_data;
	rc = (w->impl) ? h_inflateReset(strm) :
			 z_inflateReset(strm);

	strm->total_in = 0;
	strm->total_out = 0;
	strm->state = (void *)w;

	return rc;
}

extern int inflateReset2(z_streamp strm, int windowBits);
int inflateReset2(z_streamp strm, int windowBits)
{

	int rc;
	struct _internal_state *w;

	if (!has_wrapper_state(strm))
		return z_inflateReset2(strm, windowBits);

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	/*
	 * We need to count even though priv_data could still be
	 * NULL. Otherwise the statistics will not be right at the
	 * end.
	 */
	pr_trace("[%p] inflateReset2 impl=%d\n", strm, w->impl);
	if (zlib_gather_statistics()) {
		pthread_mutex_lock(&zlib_stats_mutex);
		zlib_stats.inflateReset2++;
		__inflate_update_totals(strm);
		pthread_mutex_unlock(&zlib_stats_mutex);
	}

	w->allow_switching = true;
	w->dictLength = 0;	/* clear cached dictionary */

	strm->state = w->priv_data;
	rc = (w->impl) ? h_inflateReset2(strm, windowBits) :
			 z_inflateReset2(strm, windowBits);

	strm->total_in = 0;
	strm->total_out = 0;
	strm->state = (void *)w;

	return rc;
}

int inflateSetDictionary(z_streamp strm,
			 const Bytef *dictionary,
			 uInt  dictLength)
{
	int rc;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	zlib_stats_inc(&zlib_stats.inflateSetDictionary);

	strm->state = w->priv_data;
	if (w->impl)
		rc = h_inflateSetDictionary(strm, dictionary, dictLength);
	else {
		rc = z_inflateSetDictionary(strm, dictionary, dictLength);

		/* Update a private copy for the case we have not
		   inflateGetDict */
		if (!z_hasGetDictionary()) {
			memcpy(w->dictionary, dictionary,
			       MIN((uInt)ZLIB_MAXDICTLEN, dictLength));
			w->dictLength = dictLength;
		}
	}
	strm->state = (void *)w;

	pr_trace("[%p] inflateSetDictionary: dictionary=%p dictLength=%d "
		 "adler32=%08llx rc=%d\n", strm,
		 dictionary, dictLength,
		 (long long)z_adler32(1, dictionary, dictLength), rc);

	return rc;
}

/**
 * zlib older than 1.2.8 has no inflateGetDictionary. To get the
 * software/hardware switching working without this function we create
 * a copy of the dictionary. I a user has set it via
 * inflateSetDictionary, we have still a copy in this code which we
 * can use.
 */
extern int inflateGetDictionary(z_streamp strm, Bytef *dictionary,
				uInt *dictLength);
int inflateGetDictionary(z_streamp strm, Bytef *dictionary, uInt *dictLength)
{
	int rc = Z_OK;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	zlib_stats_inc(&zlib_stats.inflateGetDictionary);

	strm->state = w->priv_data;
	if (w->impl)
		rc = h_inflateGetDictionary(strm, dictionary, dictLength);
	else {
		if (z_hasGetDictionary())
			rc = z_inflateGetDictionary(strm, dictionary,
						    dictLength);
		else {
			memcpy(dictionary, w->dictionary, w->dictLength);
			if (dictLength)
				*dictLength = w->dictLength;
		}
	}
	strm->state = (void *)w;

	pr_trace("[%p] inflateGetDictionary: dictionary=%p &dictLength=%p "
		 "rc=%d\n", strm, dictionary, dictLength, rc);

	return rc;
}

int inflateGetHeader(z_streamp strm, gz_headerp head)
{
	int rc;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	pr_trace("[%p] inflateGetHeader: head=%p\n", strm, head);
	zlib_stats_inc(&zlib_stats.inflateGetHeader);

	w->gzhead = head;
	strm->state = w->priv_data;
	rc = w->impl ? h_inflateGetHeader(strm, head) :
		       z_inflateGetHeader(strm, head);
	strm->state = (void *)w;
	return rc;
}


int inflatePrime(z_streamp strm, int bits, int value)
{
	int rc;
	struct _internal_state *w = (struct _internal_state *)strm->state;

	if (w == NULL)
		return Z_STREAM_ERROR;

	zlib_stats_inc(&zlib_stats.inflatePrime);

	strm->state = w->priv_data;
	rc = w->impl ? Z_UNSUPPORTED :
		       z_inflatePrime(strm, bits, value);
	strm->state = (void *)w;

	return rc;
}

int inflateSync(z_streamp strm)
{
	int rc;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	zlib_stats_inc(&zlib_stats.inflateSync);

	strm->state = w->priv_data;
	rc = w->impl ? Z_UNSUPPORTED :
		       z_inflateSync(strm);
	strm->state = (void *)w;

	return rc;
}

static int __inflateEnd(z_streamp strm, struct _internal_state *w)
{
	int rc;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	if (w == NULL)
		return Z_STREAM_ERROR;

	strm->state = w->priv_data;
	rc = w->impl ? h_inflateEnd(strm) :
		       z_inflateEnd(strm);

	strm->state = NULL;
	return rc;
}

int inflateEnd(z_streamp strm)
{
	int rc = Z_OK;
	struct _internal_state *w;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	if (zlib_gather_statistics()) {
		pthread_mutex_lock(&zlib_stats_mutex);
		zlib_stats.inflateEnd++;
		__inflate_update_totals(strm);
		pthread_mutex_unlock(&zlib_stats_mutex);
	}

	rc = __inflateEnd(strm, w);

	if (w->dictionary) {
		free(w->dictionary);
		w->dictionary = NULL;
	}

	pr_trace("[%p] inflateEnd w=%p rc=%d\n", strm, w, rc);
	free(w);

	return rc;
}

int inflate(z_streamp strm, int flush)
{
	int rc = Z_OK;
	struct _internal_state *w;
	unsigned int avail_in_slot, avail_out_slot;
	uint8_t dictionary[ZLIB_MAXDICTLEN];
	unsigned int dictLength = 0;

	if (strm == NULL)
		return Z_STREAM_ERROR;

	w = (struct _internal_state *)strm->state;
	if (w == NULL)
		return Z_STREAM_ERROR;

	/*
	 * Special situation triggered by strange JAVA zlib use-case:
	 * If we do not have any data to decompress, return
	 * Z_BUF_ERROR instead of trying to decypher 0 bytes. The
	 * decision to use HW or SW is deferred until we see avail_in
	 * != 0 for the first time.
	 */
	if ((strm->total_in == 0) && (w->allow_switching)) {
		/* Special case where there is no data. This occurs
		   quite often in the JAVA use-case. */
		if (strm->avail_in == 0)
			return Z_BUF_ERROR;

		if ((strm->avail_in < zlib_inflate_threshold) &&
		    (w->impl == ZLIB_HW_IMPL)) {
			pr_trace("[%p] inflate: avail_in=%d smaller "
				 "%d switching to software mode!\n",
				 strm, strm->avail_in, zlib_inflate_threshold);

			rc = inflateGetDictionary(strm, dictionary,
						  &dictLength);
			if (rc != Z_OK)
				goto err;

			/* Free already allocated resources, but not w */
			rc = __inflateEnd(strm, w);
			if (rc != Z_OK)
				goto err;

			/* Enforce software here! */
			w->impl = ZLIB_SW_IMPL;

			/* Reinit but not w */
			rc = __inflateInit2_(strm, w);
			if (rc != Z_OK)
				goto err;

			strm->state = (void *)w;
			if (w->gzhead != NULL)
				inflateGetHeader(strm, w->gzhead);

			if (dictLength != 0) {
				rc = inflateSetDictionary(strm, dictionary,
							  dictLength);
				if (rc != Z_OK) {
					inflateEnd(strm);
					goto err;
				}
			}
		} else if ((strm->avail_in >= zlib_inflate_threshold) &&
			   (w->impl == ZLIB_SW_IMPL) &&
			   (zlib_inflate_impl == ZLIB_HW_IMPL)) {
			pr_trace("[%p] inflate: avail_in=%d bigger or equal "
				 "%d switching to hardware mode!\n",
				 strm, strm->avail_in, zlib_inflate_threshold);

			rc = inflateGetDictionary(strm, dictionary,
						  &dictLength);
			if (rc != Z_OK)
				goto err;

			/* Free already allocated resources, but not w */
			rc = __inflateEnd(strm, w);
			if (rc != Z_OK)
				goto err;

			/* Try hardware mode here! */
			w->impl = zlib_inflate_impl;

			/* Reinit but not w */
			rc = __inflateInit2_(strm, w);
			if (rc != Z_OK)
				goto err;

			strm->state = (void *)w;
			if (w->gzhead != NULL)
				inflateGetHeader(strm, w->gzhead);

			if (dictLength != 0) {
				rc = inflateSetDictionary(strm, dictionary,
							  dictLength);
				if (rc != Z_OK) {
					inflateEnd(strm);
					goto err;
				}
			}
		}
	}

	if (zlib_gather_statistics()) {
		pthread_mutex_lock(&zlib_stats_mutex);
		avail_in_slot = strm->avail_in / 4096;
		if (avail_in_slot >= ZLIB_SIZE_SLOTS)
			avail_in_slot = ZLIB_SIZE_SLOTS - 1;
		zlib_stats.inflate_avail_in[avail_in_slot]++;

		avail_out_slot = strm->avail_out / 4096;
		if (avail_out_slot >= ZLIB_SIZE_SLOTS)
			avail_out_slot = ZLIB_SIZE_SLOTS - 1;
		zlib_stats.inflate_avail_out[avail_out_slot]++;
		zlib_stats.inflate[w->impl]++;
		pthread_mutex_unlock(&zlib_stats_mutex);
	}

	pr_trace("[%p] inflate:   flush=%s next_in=%p avail_in=%d "
		 "next_out=%p avail_out=%d total_in=%ld total_out=%ld "
		 "crc/adler=%08lx\n",
		 strm, flush_to_str(flush), strm->next_in,
		 strm->avail_in, strm->next_out, strm->avail_out,
		 strm->total_in, strm->total_out, strm->adler);

	strm->state = w->priv_data;
	rc = w->impl ? h_inflate(strm, flush) :
		       z_inflate(strm, flush);

	/* stop switching after lowlevel inflate has been called */
	w->allow_switching = false;
	strm->state = (void *)w;

	pr_trace("[%p]            flush=%s next_in=%p avail_in=%d "
		 "next_out=%p avail_out=%d total_in=%ld total_out=%ld "
		 "crc/adler=%08lx rc=%s\n",
		 strm, flush_to_str(flush), strm->next_in,
		 strm->avail_in, strm->next_out, strm->avail_out,
		 strm->total_in, strm->total_out, strm->adler, ret_to_str(rc));

 err:
	return rc;
}

/* Implement the *Back() functions by using software only */

int inflateBack(z_streamp strm, in_func in, void *in_desc,
		out_func out, void *out_desc)
{
	return z_inflateBack(strm, in, in_desc, out, out_desc);
}

/**
 * FIXME Implement fallback if hw is not available.
 */
int inflateBackInit_(z_streamp strm, int windowBits, unsigned char *window,
		     const char *version, int stream_size)
{
	return z_inflateBackInit_(strm, windowBits, window, version,
				  stream_size);
}

int inflateBackEnd(z_streamp strm)
{
	return z_inflateBackEnd(strm);
}

const char *zlibVersion(void)
{
	return z_zlibVersion();
}

uLong zlibCompileFlags(void)
{
	return z_zlibCompileFlags();
}

uLong compressBound(uLong sourceLen)
{
	zlib_stats_inc(&zlib_stats.compressBound);
	return MAX(h_deflateBound(NULL, sourceLen),
			   z_deflateBound(NULL, sourceLen));
}

/*
 * adler32: Returns the value of the result of the z_ prefixed adler32 function
 *
 */
uLong adler32(uLong adler, const Bytef *buf, uInt len)
{
	zlib_stats_inc(&zlib_stats.adler32);
	pr_trace("adler32(len=%lld)\n", (long long)len);

	return z_adler32(adler, buf, len);
}

/*
 * adler32_combine: Returns the value of the result of the z_ prefixed
 * adler32_combine function
 *
 */
uLong adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
{
	zlib_stats_inc(&zlib_stats.adler32_combine);
	pr_trace("adler32_combine(len2=%lld)\n", (long long)len2);

	return z_adler32_combine(adler1, adler2, len2);
}

/*
 * crc32: Returns the value of the result of the z_ prefixed crc32 function
 *
 */
uLong crc32(uLong crc, const Bytef *buf, uInt len)
{
	zlib_stats_inc(&zlib_stats.crc32);
	pr_trace("crc32(len=%lld)\n", (long long)len);

	return z_crc32(crc, buf, len);
}

/*
 * crc32_combine: Returns the value of the result of the z_ prefixed
 * crc32_combine function
 *
 */
uLong crc32_combine(uLong crc1, uLong crc2, z_off_t len2)
{
	zlib_stats_inc(&zlib_stats.crc32_combine);
	pr_trace("crc32_combine(len2=%lld)\n", (long long)len2);

	return z_crc32_combine(crc1, crc2, len2);
}

const char *zError(int err)
{
	return z_zError(err);
}

static void _done(void) __attribute__((destructor));

static void _done(void)
{
	if (zlib_gather_statistics()) {
		__print_stats();
		pthread_mutex_destroy(&zlib_stats_mutex);
	}

	zedc_hw_done();
	zedc_sw_done();

	if (zlib_log != stderr)
		fclose(zlib_log);

	return;
}