]> icculus.org git repositories - icculus/xz.git/blob - src/xz/hardware.c
Put the interesting parts of XZ Utils into the public domain.
[icculus/xz.git] / src / xz / hardware.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       hardware.c
4 /// \brief      Detection of available hardware resources
5 //
6 //  Author:     Lasse Collin
7 //
8 //  This file has been put into the public domain.
9 //  You can do whatever you want with this file.
10 //
11 ///////////////////////////////////////////////////////////////////////////////
12
13 #include "private.h"
14 #include "physmem.h"
15 #include "cpucores.h"
16
17
18 /// Maximum number of free *coder* threads. This can be set with
19 /// the --threads=NUM command line option.
20 static uint32_t threads_max;
21
22
23 /// Memory usage limit for encoding
24 static uint64_t memlimit_encoder;
25
26 /// Memory usage limit for decoding
27 static uint64_t memlimit_decoder;
28
29 /// Memory usage limit given on the command line or environment variable.
30 /// Zero indicates the default (memlimit_encoder or memlimit_decoder).
31 static uint64_t memlimit_custom = 0;
32
33
34 /// Get the number of CPU cores, and set opt_threads to default to that value.
35 /// User can then override this with --threads command line option.
36 static void
37 hardware_threadlimit_init(void)
38 {
39         threads_max = cpucores();
40         if (threads_max == 0)
41                 threads_max = 1;
42
43         return;
44 }
45
46
47 extern void
48 hardware_threadlimit_set(uint32_t threadlimit)
49 {
50         threads_max = threadlimit;
51         return;
52 }
53
54
55 extern uint32_t
56 hardware_threadlimit_get(void)
57 {
58         return threads_max;
59 }
60
61
62 static void
63 hardware_memlimit_init(void)
64 {
65         uint64_t mem = physmem();
66
67         // If we cannot determine the amount of RAM, assume 32 MiB. Maybe
68         // even that is too much on some systems. But on most systems it's
69         // far too little, and can be annoying.
70         if (mem == 0)
71                 mem = UINT64_C(32) * 1024 * 1024;
72
73         // Use at maximum of 90 % of RAM when encoding and 33 % when decoding.
74         memlimit_encoder = mem - mem / 10;
75         memlimit_decoder = mem / 3;
76
77         return;
78 }
79
80
81 extern void
82 hardware_memlimit_set(uint64_t memlimit)
83 {
84         memlimit_custom = memlimit;
85         return;
86 }
87
88
89 extern uint64_t
90 hardware_memlimit_encoder(void)
91 {
92         return memlimit_custom != 0 ? memlimit_custom : memlimit_encoder;
93 }
94
95
96 extern uint64_t
97 hardware_memlimit_decoder(void)
98 {
99         return memlimit_custom != 0 ? memlimit_custom : memlimit_decoder;
100 }
101
102
103 extern void
104 hardware_init(void)
105 {
106         hardware_memlimit_init();
107         hardware_threadlimit_init();
108         return;
109 }