mfplat: Read queue subscriber within the critical section.
[wine/zf.git] / dlls / ntdll / unix / system.c
blobd3e380b8c325ad8f0f9e97638196f70dee0e8ea8
1 /*
2 * System information APIs
4 * Copyright 1996-1998 Marcus Meissner
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #if 0
22 #pragma makedep unix
23 #endif
25 #include "config.h"
26 #include "wine/port.h"
28 #include <string.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <errno.h>
33 #ifdef HAVE_SYS_TIME_H
34 # include <sys/time.h>
35 #endif
36 #include <time.h>
37 #ifdef HAVE_SYS_PARAM_H
38 # include <sys/param.h>
39 #endif
40 #ifdef HAVE_SYS_SYSCTL_H
41 # include <sys/sysctl.h>
42 #endif
43 #ifdef HAVE_SYS_UTSNAME_H
44 # include <sys/utsname.h>
45 #endif
46 #ifdef HAVE_MACHINE_CPU_H
47 # include <machine/cpu.h>
48 #endif
49 #ifdef HAVE_SYS_RANDOM_H
50 # include <sys/random.h>
51 #endif
52 #ifdef HAVE_IOKIT_IOKITLIB_H
53 # include <CoreFoundation/CoreFoundation.h>
54 # include <IOKit/IOKitLib.h>
55 # include <IOKit/pwr_mgt/IOPM.h>
56 # include <IOKit/pwr_mgt/IOPMLib.h>
57 # include <IOKit/ps/IOPowerSources.h>
58 #endif
59 #ifdef __APPLE__
60 # include <mach/mach.h>
61 # include <mach/machine.h>
62 # include <mach/mach_init.h>
63 # include <mach/mach_host.h>
64 # include <mach/vm_map.h>
65 #endif
67 #define NONAMELESSUNION
68 #include "ntstatus.h"
69 #define WIN32_NO_STATUS
70 #include "windef.h"
71 #include "winternl.h"
72 #include "ddk/wdm.h"
73 #include "wine/asm.h"
74 #include "unix_private.h"
75 #include "wine/debug.h"
77 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
79 #include "pshpack1.h"
81 struct smbios_prologue
83 BYTE calling_method;
84 BYTE major_version;
85 BYTE minor_version;
86 BYTE revision;
87 DWORD length;
90 struct smbios_header
92 BYTE type;
93 BYTE length;
94 WORD handle;
97 struct smbios_bios
99 struct smbios_header hdr;
100 BYTE vendor;
101 BYTE version;
102 WORD start;
103 BYTE date;
104 BYTE size;
105 UINT64 characteristics;
106 BYTE characteristics_ext[2];
107 BYTE system_bios_major_release;
108 BYTE system_bios_minor_release;
109 BYTE ec_firmware_major_release;
110 BYTE ec_firmware_minor_release;
113 struct smbios_system
115 struct smbios_header hdr;
116 BYTE vendor;
117 BYTE product;
118 BYTE version;
119 BYTE serial;
120 BYTE uuid[16];
121 BYTE wake_up_type;
122 BYTE sku_number;
123 BYTE family;
126 struct smbios_board
128 struct smbios_header hdr;
129 BYTE vendor;
130 BYTE product;
131 BYTE version;
132 BYTE serial;
133 BYTE asset_tag;
134 BYTE feature_flags;
135 BYTE location;
136 WORD chassis_handle;
137 BYTE board_type;
138 BYTE num_contained_handles;
141 struct smbios_chassis
143 struct smbios_header hdr;
144 BYTE vendor;
145 BYTE type;
146 BYTE version;
147 BYTE serial;
148 BYTE asset_tag;
149 BYTE boot_state;
150 BYTE power_supply_state;
151 BYTE thermal_state;
152 BYTE security_status;
153 DWORD oem_defined;
154 BYTE height;
155 BYTE num_power_cords;
156 BYTE num_contained_elements;
157 BYTE contained_element_rec_length;
160 struct smbios_boot_info
162 struct smbios_header hdr;
163 BYTE reserved[6];
164 BYTE boot_status[10];
167 #include "poppack.h"
169 /* Firmware table providers */
170 #define ACPI 0x41435049
171 #define FIRM 0x4649524D
172 #define RSMB 0x52534D42
174 SYSTEM_CPU_INFORMATION cpu_info = { 0 };
176 /*******************************************************************************
177 * Architecture specific feature detection for CPUs
179 * This a set of mutually exclusive #if define()s each providing its own get_cpuinfo() to be called
180 * from init_cpu_info();
182 #if defined(__i386__) || defined(__x86_64__)
184 BOOL xstate_compaction_enabled = FALSE;
186 #define AUTH 0x68747541 /* "Auth" */
187 #define ENTI 0x69746e65 /* "enti" */
188 #define CAMD 0x444d4163 /* "cAMD" */
190 #define GENU 0x756e6547 /* "Genu" */
191 #define INEI 0x49656e69 /* "ineI" */
192 #define NTEL 0x6c65746e /* "ntel" */
194 static inline void do_cpuid(unsigned int ax, unsigned int cx, unsigned int *p)
196 __asm__ ("cpuid" : "=a"(p[0]), "=b" (p[1]), "=c"(p[2]), "=d"(p[3]) : "a"(ax), "c"(cx));
199 #ifdef __i386__
200 extern int have_cpuid(void);
201 __ASM_GLOBAL_FUNC( have_cpuid,
202 "pushfl\n\t"
203 "pushfl\n\t"
204 "movl (%esp),%ecx\n\t"
205 "xorl $0x00200000,(%esp)\n\t"
206 "popfl\n\t"
207 "pushfl\n\t"
208 "popl %eax\n\t"
209 "popfl\n\t"
210 "xorl %ecx,%eax\n\t"
211 "andl $0x00200000,%eax\n\t"
212 "ret" )
213 #else
214 static int have_cpuid(void)
216 return 1;
218 #endif
220 /* Detect if a SSE2 processor is capable of Denormals Are Zero (DAZ) mode.
222 * This function assumes you have already checked for SSE2/FXSAVE support. */
223 static inline BOOL have_sse_daz_mode(void)
225 #ifdef __i386__
226 /* Intel says we need a zeroed 16-byte aligned buffer */
227 char buffer[512 + 16];
228 XSAVE_FORMAT *state = (XSAVE_FORMAT *)(((ULONG_PTR)buffer + 15) & ~15);
229 memset(buffer, 0, sizeof(buffer));
231 __asm__ __volatile__( "fxsave %0" : "=m" (*state) : "m" (*state) );
233 return (state->MxCsr_Mask & (1 << 6)) >> 6;
234 #else /* all x86_64 processors include SSE2 with DAZ mode */
235 return TRUE;
236 #endif
239 static void get_cpuinfo( SYSTEM_CPU_INFORMATION *info )
241 unsigned int regs[4], regs2[4], regs3[4];
243 #if defined(__i386__)
244 info->Architecture = PROCESSOR_ARCHITECTURE_INTEL;
245 #elif defined(__x86_64__)
246 info->Architecture = PROCESSOR_ARCHITECTURE_AMD64;
247 #endif
249 /* We're at least a 386 */
250 info->FeatureSet = CPU_FEATURE_VME | CPU_FEATURE_X86 | CPU_FEATURE_PGE;
251 info->Level = 3;
253 if (!have_cpuid()) return;
255 do_cpuid( 0x00000000, 0, regs ); /* get standard cpuid level and vendor name */
256 if (regs[0]>=0x00000001) /* Check for supported cpuid version */
258 do_cpuid( 0x00000001, 0, regs2 ); /* get cpu features */
259 if (regs2[3] & (1 << 3 )) info->FeatureSet |= CPU_FEATURE_PSE;
260 if (regs2[3] & (1 << 4 )) info->FeatureSet |= CPU_FEATURE_TSC;
261 if (regs2[3] & (1 << 6 )) info->FeatureSet |= CPU_FEATURE_PAE;
262 if (regs2[3] & (1 << 8 )) info->FeatureSet |= CPU_FEATURE_CX8;
263 if (regs2[3] & (1 << 11)) info->FeatureSet |= CPU_FEATURE_SEP;
264 if (regs2[3] & (1 << 12)) info->FeatureSet |= CPU_FEATURE_MTRR;
265 if (regs2[3] & (1 << 15)) info->FeatureSet |= CPU_FEATURE_CMOV;
266 if (regs2[3] & (1 << 16)) info->FeatureSet |= CPU_FEATURE_PAT;
267 if (regs2[3] & (1 << 23)) info->FeatureSet |= CPU_FEATURE_MMX;
268 if (regs2[3] & (1 << 24)) info->FeatureSet |= CPU_FEATURE_FXSR;
269 if (regs2[3] & (1 << 25)) info->FeatureSet |= CPU_FEATURE_SSE;
270 if (regs2[3] & (1 << 26)) info->FeatureSet |= CPU_FEATURE_SSE2;
271 if (regs2[2] & (1 << 0 )) info->FeatureSet |= CPU_FEATURE_SSE3;
272 if (regs2[2] & (1 << 9 )) info->FeatureSet |= CPU_FEATURE_SSSE3;
273 if (regs2[2] & (1 << 13)) info->FeatureSet |= CPU_FEATURE_CX128;
274 if (regs2[2] & (1 << 19)) info->FeatureSet |= CPU_FEATURE_SSE41;
275 if (regs2[2] & (1 << 20)) info->FeatureSet |= CPU_FEATURE_SSE42;
276 if (regs2[2] & (1 << 27)) info->FeatureSet |= CPU_FEATURE_XSAVE;
277 if (regs2[2] & (1 << 28)) info->FeatureSet |= CPU_FEATURE_AVX;
278 if((regs2[3] & (1 << 26)) && (regs2[3] & (1 << 24)) && have_sse_daz_mode()) /* has SSE2 and FXSAVE/FXRSTOR */
279 info->FeatureSet |= CPU_FEATURE_DAZ;
281 if (regs[0] >= 0x00000007)
283 do_cpuid( 0x00000007, 0, regs3 ); /* get extended features */
284 if (regs3[1] & (1 << 5)) info->FeatureSet |= CPU_FEATURE_AVX2;
287 if (info->FeatureSet & CPU_FEATURE_XSAVE)
289 do_cpuid( 0x0000000d, 1, regs3 ); /* get XSAVE details */
290 if (regs3[0] & 2) xstate_compaction_enabled = TRUE;
293 if (regs[1] == AUTH && regs[3] == ENTI && regs[2] == CAMD)
295 info->Level = (regs2[0] >> 8) & 0xf; /* family */
296 if (info->Level == 0xf) /* AMD says to add the extended family to the family if family is 0xf */
297 info->Level += (regs2[0] >> 20) & 0xff;
299 /* repack model and stepping to make a "revision" */
300 info->Revision = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
301 info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8; /* model */
302 info->Revision |= regs2[0] & 0xf; /* stepping */
304 do_cpuid( 0x80000000, 0, regs ); /* get vendor cpuid level */
305 if (regs[0] >= 0x80000001)
307 do_cpuid( 0x80000001, 0, regs2 ); /* get vendor features */
308 if (regs2[2] & (1 << 2)) info->FeatureSet |= CPU_FEATURE_VIRT;
309 if (regs2[3] & (1 << 20)) info->FeatureSet |= CPU_FEATURE_NX;
310 if (regs2[3] & (1 << 27)) info->FeatureSet |= CPU_FEATURE_TSC;
311 if (regs2[3] & (1u << 31)) info->FeatureSet |= CPU_FEATURE_3DNOW;
314 else if (regs[1] == GENU && regs[3] == INEI && regs[2] == NTEL)
316 info->Level = ((regs2[0] >> 8) & 0xf) + ((regs2[0] >> 20) & 0xff); /* family + extended family */
317 if(info->Level == 15) info->Level = 6;
319 /* repack model and stepping to make a "revision" */
320 info->Revision = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
321 info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8; /* model */
322 info->Revision |= regs2[0] & 0xf; /* stepping */
324 if(regs2[2] & (1 << 5)) info->FeatureSet |= CPU_FEATURE_VIRT;
325 if(regs2[3] & (1 << 21)) info->FeatureSet |= CPU_FEATURE_DS;
327 do_cpuid( 0x80000000, 0, regs ); /* get vendor cpuid level */
328 if (regs[0] >= 0x80000001)
330 do_cpuid( 0x80000001, 0, regs2 ); /* get vendor features */
331 if (regs2[3] & (1 << 20)) info->FeatureSet |= CPU_FEATURE_NX;
332 if (regs2[3] & (1 << 27)) info->FeatureSet |= CPU_FEATURE_TSC;
335 else
337 info->Level = (regs2[0] >> 8) & 0xf; /* family */
339 /* repack model and stepping to make a "revision" */
340 info->Revision = ((regs2[0] >> 4 ) & 0xf) << 8; /* model */
341 info->Revision |= regs2[0] & 0xf; /* stepping */
346 #elif defined(__arm__)
348 static inline void get_cpuinfo( SYSTEM_CPU_INFORMATION *info )
350 #ifdef linux
351 char line[512];
352 char *s, *value;
353 FILE *f = fopen("/proc/cpuinfo", "r");
354 if (f)
356 while (fgets( line, sizeof(line), f ))
358 /* NOTE: the ':' is the only character we can rely on */
359 if (!(value = strchr(line,':'))) continue;
360 /* terminate the valuename */
361 s = value - 1;
362 while ((s >= line) && (*s == ' ' || *s == '\t')) s--;
363 s[1] = 0;
364 /* and strip leading spaces from value */
365 value += 1;
366 while (*value == ' ' || *value == '\t') value++;
367 if ((s = strchr( value,'\n' ))) *s = 0;
368 if (!strcmp( line, "CPU architecture" ))
370 info->Level = atoi(value);
371 continue;
373 if (!strcmp( line, "CPU revision" ))
375 info->Revision = atoi(value);
376 continue;
378 if (!strcmp( line, "Features" ))
380 if (strstr(value, "crc32")) info->FeatureSet |= CPU_FEATURE_ARM_V8_CRC32;
381 if (strstr(value, "aes")) info->FeatureSet |= CPU_FEATURE_ARM_V8_CRYPTO;
382 continue;
385 fclose( f );
387 #elif defined(__FreeBSD__)
388 size_t valsize;
389 char buf[8];
390 int value;
392 valsize = sizeof(buf);
393 if (!sysctlbyname("hw.machine_arch", &buf, &valsize, NULL, 0) && sscanf(buf, "armv%i", &value) == 1)
394 info->Level = value;
396 valsize = sizeof(value);
397 if (!sysctlbyname("hw.floatingpoint", &value, &valsize, NULL, 0))
398 info->FeatureSet |= CPU_FEATURE_ARM_VFP_32;
399 #else
400 FIXME("CPU Feature detection not implemented.\n");
401 #endif
402 info->Architecture = PROCESSOR_ARCHITECTURE_ARM;
405 #elif defined(__aarch64__)
407 static void get_cpuinfo( SYSTEM_CPU_INFORMATION *info )
409 #ifdef linux
410 char line[512];
411 char *s, *value;
412 FILE *f = fopen("/proc/cpuinfo", "r");
413 if (f)
415 while (fgets( line, sizeof(line), f ))
417 /* NOTE: the ':' is the only character we can rely on */
418 if (!(value = strchr(line,':'))) continue;
419 /* terminate the valuename */
420 s = value - 1;
421 while ((s >= line) && (*s == ' ' || *s == '\t')) s--;
422 s[1] = 0;
423 /* and strip leading spaces from value */
424 value += 1;
425 while (*value == ' ' || *value == '\t') value++;
426 if ((s = strchr( value,'\n' ))) *s = 0;
427 if (!strcmp( line, "CPU architecture" ))
429 info->Level = atoi(value);
430 continue;
432 if (!strcmp( line, "CPU revision" ))
434 info->Revision = atoi(value);
435 continue;
437 if (!strcmp( line, "Features" ))
439 if (strstr(value, "crc32")) info->FeatureSet |= CPU_FEATURE_ARM_V8_CRC32;
440 if (strstr(value, "aes")) info->FeatureSet |= CPU_FEATURE_ARM_V8_CRYPTO;
441 continue;
444 fclose( f );
446 #else
447 FIXME("CPU Feature detection not implemented.\n");
448 #endif
449 info->Level = max(info->Level, 8);
450 info->Architecture = PROCESSOR_ARCHITECTURE_ARM64;
453 #endif /* End architecture specific feature detection for CPUs */
455 /******************************************************************
456 * init_cpu_info
458 * inits a couple of places with CPU related information:
459 * - cpu_info in this file
460 * - Peb->NumberOfProcessors
461 * - SharedUserData->ProcessFeatures[] array
463 void init_cpu_info(void)
465 long num;
467 #ifdef _SC_NPROCESSORS_ONLN
468 num = sysconf(_SC_NPROCESSORS_ONLN);
469 if (num < 1)
471 num = 1;
472 WARN("Failed to detect the number of processors.\n");
474 #elif defined(CTL_HW) && defined(HW_NCPU)
475 int mib[2];
476 size_t len = sizeof(num);
477 mib[0] = CTL_HW;
478 mib[1] = HW_NCPU;
479 if (sysctl(mib, 2, &num, &len, NULL, 0) != 0)
481 num = 1;
482 WARN("Failed to detect the number of processors.\n");
484 #else
485 num = 1;
486 FIXME("Detecting the number of processors is not supported.\n");
487 #endif
488 NtCurrentTeb()->Peb->NumberOfProcessors = num;
489 get_cpuinfo( &cpu_info );
490 TRACE( "<- CPU arch %d, level %d, rev %d, features 0x%x\n",
491 cpu_info.Architecture, cpu_info.Level, cpu_info.Revision, cpu_info.FeatureSet );
494 static BOOL grow_logical_proc_buf( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata, DWORD *max_len )
496 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
498 *max_len *= 2;
499 if (!(new_data = realloc( *pdata, *max_len*sizeof(*new_data) ))) return FALSE;
500 *pdata = new_data;
501 return TRUE;
504 static BOOL grow_logical_proc_ex_buf( SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *max_len )
506 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *new_dataex;
507 DWORD new_len = *max_len * 2;
508 if (!(new_dataex = realloc( *pdataex, new_len * sizeof(*new_dataex) ))) return FALSE;
509 memset( new_dataex + *max_len, 0, (new_len - *max_len) * sizeof(*new_dataex) );
510 *pdataex = new_dataex;
511 *max_len = new_len;
512 return TRUE;
515 static DWORD log_proc_ex_size_plus(DWORD size)
517 /* add SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX.Relationship and .Size */
518 return sizeof(LOGICAL_PROCESSOR_RELATIONSHIP) + sizeof(DWORD) + size;
521 static DWORD count_bits(ULONG_PTR mask)
523 DWORD count = 0;
524 while (mask > 0)
526 if (mask & 1) ++count;
527 mask >>= 1;
529 return count;
532 /* Store package and core information for a logical processor. Parsing of processor
533 * data may happen in multiple passes; the 'id' parameter is then used to locate
534 * previously stored data. The type of data stored in 'id' depends on 'rel':
535 * - RelationProcessorPackage: package id ('CPU socket').
536 * - RelationProcessorCore: physical core number.
538 static BOOL logical_proc_info_add_by_id( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
539 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *len,
540 DWORD *pmax_len, LOGICAL_PROCESSOR_RELATIONSHIP rel,
541 DWORD id, ULONG_PTR mask )
543 if (pdata)
545 DWORD i;
547 for (i = 0; i < *len; i++)
549 if (rel == RelationProcessorPackage && (*pdata)[i].Relationship == rel && (*pdata)[i].u.Reserved[1] == id)
551 (*pdata)[i].ProcessorMask |= mask;
552 return TRUE;
554 else if (rel == RelationProcessorCore && (*pdata)[i].Relationship == rel && (*pdata)[i].u.Reserved[1] == id)
555 return TRUE;
558 while (*len == *pmax_len)
560 if (!grow_logical_proc_buf(pdata, pmax_len)) return FALSE;
563 (*pdata)[i].Relationship = rel;
564 (*pdata)[i].ProcessorMask = mask;
565 if (rel == RelationProcessorCore)
566 (*pdata)[i].u.ProcessorCore.Flags = count_bits(mask) > 1 ? LTP_PC_SMT : 0;
567 (*pdata)[i].u.Reserved[0] = 0;
568 (*pdata)[i].u.Reserved[1] = id;
569 *len = i+1;
571 else
573 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex;
574 DWORD ofs = 0;
576 while (ofs < *len)
578 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
579 if (rel == RelationProcessorPackage && dataex->Relationship == rel && dataex->u.Processor.Reserved[1] == id)
581 dataex->u.Processor.GroupMask[0].Mask |= mask;
582 return TRUE;
584 else if (rel == RelationProcessorCore && dataex->Relationship == rel && dataex->u.Processor.Reserved[1] == id)
586 return TRUE;
588 ofs += dataex->Size;
591 /* TODO: For now, just one group. If more than 64 processors, then we
592 * need another group. */
594 while (ofs + log_proc_ex_size_plus(sizeof(PROCESSOR_RELATIONSHIP)) > *pmax_len)
596 if (!grow_logical_proc_ex_buf(pdataex, pmax_len)) return FALSE;
599 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
601 dataex->Relationship = rel;
602 dataex->Size = log_proc_ex_size_plus(sizeof(PROCESSOR_RELATIONSHIP));
603 if (rel == RelationProcessorCore)
604 dataex->u.Processor.Flags = count_bits(mask) > 1 ? LTP_PC_SMT : 0;
605 else
606 dataex->u.Processor.Flags = 0;
607 dataex->u.Processor.EfficiencyClass = 0;
608 dataex->u.Processor.GroupCount = 1;
609 dataex->u.Processor.GroupMask[0].Mask = mask;
610 dataex->u.Processor.GroupMask[0].Group = 0;
611 /* mark for future lookup */
612 dataex->u.Processor.Reserved[0] = 0;
613 dataex->u.Processor.Reserved[1] = id;
615 *len += dataex->Size;
618 return TRUE;
621 static BOOL logical_proc_info_add_cache( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
622 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *len,
623 DWORD *pmax_len, ULONG_PTR mask, CACHE_DESCRIPTOR *cache )
625 if (pdata)
627 DWORD i;
629 for (i = 0; i < *len; i++)
631 if ((*pdata)[i].Relationship==RelationCache && (*pdata)[i].ProcessorMask==mask
632 && (*pdata)[i].u.Cache.Level==cache->Level && (*pdata)[i].u.Cache.Type==cache->Type)
633 return TRUE;
636 while (*len == *pmax_len)
637 if (!grow_logical_proc_buf(pdata, pmax_len)) return FALSE;
639 (*pdata)[i].Relationship = RelationCache;
640 (*pdata)[i].ProcessorMask = mask;
641 (*pdata)[i].u.Cache = *cache;
642 *len = i+1;
644 else
646 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex;
647 DWORD ofs;
649 for (ofs = 0; ofs < *len; )
651 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
652 if (dataex->Relationship == RelationCache && dataex->u.Cache.GroupMask.Mask == mask &&
653 dataex->u.Cache.Level == cache->Level && dataex->u.Cache.Type == cache->Type)
654 return TRUE;
655 ofs += dataex->Size;
658 while (ofs + log_proc_ex_size_plus(sizeof(CACHE_RELATIONSHIP)) > *pmax_len)
660 if (!grow_logical_proc_ex_buf(pdataex, pmax_len)) return FALSE;
663 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
665 dataex->Relationship = RelationCache;
666 dataex->Size = log_proc_ex_size_plus(sizeof(CACHE_RELATIONSHIP));
667 dataex->u.Cache.Level = cache->Level;
668 dataex->u.Cache.Associativity = cache->Associativity;
669 dataex->u.Cache.LineSize = cache->LineSize;
670 dataex->u.Cache.CacheSize = cache->Size;
671 dataex->u.Cache.Type = cache->Type;
672 dataex->u.Cache.GroupMask.Mask = mask;
673 dataex->u.Cache.GroupMask.Group = 0;
675 *len += dataex->Size;
678 return TRUE;
681 static BOOL logical_proc_info_add_numa_node( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
682 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *len,
683 DWORD *pmax_len, ULONG_PTR mask, DWORD node_id )
685 if (pdata)
687 while (*len == *pmax_len)
688 if (!grow_logical_proc_buf(pdata, pmax_len)) return FALSE;
690 (*pdata)[*len].Relationship = RelationNumaNode;
691 (*pdata)[*len].ProcessorMask = mask;
692 (*pdata)[*len].u.NumaNode.NodeNumber = node_id;
693 (*len)++;
695 else
697 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex;
699 while (*len + log_proc_ex_size_plus(sizeof(NUMA_NODE_RELATIONSHIP)) > *pmax_len)
701 if (!grow_logical_proc_ex_buf(pdataex, pmax_len)) return FALSE;
704 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + *len);
706 dataex->Relationship = RelationNumaNode;
707 dataex->Size = log_proc_ex_size_plus(sizeof(NUMA_NODE_RELATIONSHIP));
708 dataex->u.NumaNode.NodeNumber = node_id;
709 dataex->u.NumaNode.GroupMask.Mask = mask;
710 dataex->u.NumaNode.GroupMask.Group = 0;
712 *len += dataex->Size;
715 return TRUE;
718 static BOOL logical_proc_info_add_group( SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex,
719 DWORD *len, DWORD *pmax_len, DWORD num_cpus, ULONG_PTR mask )
721 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex;
723 while (*len + log_proc_ex_size_plus(sizeof(GROUP_RELATIONSHIP)) > *pmax_len)
724 if (!grow_logical_proc_ex_buf(pdataex, pmax_len)) return FALSE;
726 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + *len);
728 dataex->Relationship = RelationGroup;
729 dataex->Size = log_proc_ex_size_plus(sizeof(GROUP_RELATIONSHIP));
730 dataex->u.Group.MaximumGroupCount = 1;
731 dataex->u.Group.ActiveGroupCount = 1;
732 dataex->u.Group.GroupInfo[0].MaximumProcessorCount = num_cpus;
733 dataex->u.Group.GroupInfo[0].ActiveProcessorCount = num_cpus;
734 dataex->u.Group.GroupInfo[0].ActiveProcessorMask = mask;
736 *len += dataex->Size;
737 return TRUE;
740 #ifdef linux
742 /* Helper function for counting bitmap values as commonly used by the Linux kernel
743 * for storing CPU masks in sysfs. The format is comma separated lists of hex values
744 * each max 32-bit e.g. "00ff" or even "00,00000000,0000ffff".
746 * Example files include:
747 * - /sys/devices/system/cpu/cpu0/cache/index0/shared_cpu_map
748 * - /sys/devices/system/cpu/cpu0/topology/thread_siblings
750 static BOOL sysfs_parse_bitmap(const char *filename, ULONG_PTR *mask)
752 FILE *f;
753 DWORD r;
755 f = fopen(filename, "r");
756 if (!f) return FALSE;
758 while (!feof(f))
760 char op;
761 if (!fscanf(f, "%x%c ", &r, &op)) break;
762 *mask = (sizeof(ULONG_PTR)>sizeof(int) ? *mask << (8 * sizeof(DWORD)) : 0) + r;
764 fclose( f );
765 return TRUE;
768 /* Helper function for counting number of elements in interval lists as used by
769 * the Linux kernel. The format is comma separated list of intervals of which
770 * each interval has the format of "begin-end" where begin and end are decimal
771 * numbers. E.g. "0-7", "0-7,16-23"
773 * Example files include:
774 * - /sys/devices/system/cpu/online
775 * - /sys/devices/system/cpu/cpu0/cache/index0/shared_cpu_list
776 * - /sys/devices/system/cpu/cpu0/topology/thread_siblings_list.
778 static BOOL sysfs_count_list_elements(const char *filename, DWORD *result)
780 FILE *f;
782 f = fopen(filename, "r");
783 if (!f) return FALSE;
785 while (!feof(f))
787 char op;
788 DWORD beg, end;
790 if (!fscanf(f, "%u%c ", &beg, &op)) break;
791 if(op == '-')
792 fscanf(f, "%u%c ", &end, &op);
793 else
794 end = beg;
796 *result += end - beg + 1;
798 fclose( f );
799 return TRUE;
802 /* for 'data', max_len is the array count. for 'dataex', max_len is in bytes */
803 static NTSTATUS create_logical_proc_info( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data,
804 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **dataex,
805 DWORD *max_len, DWORD relation )
807 static const char core_info[] = "/sys/devices/system/cpu/cpu%u/topology/%s";
808 static const char cache_info[] = "/sys/devices/system/cpu/cpu%u/cache/index%u/%s";
809 static const char numa_info[] = "/sys/devices/system/node/node%u/cpumap";
811 FILE *fcpu_list, *fnuma_list, *f;
812 DWORD len = 0, beg, end, i, j, r, num_cpus = 0, max_cpus = 0;
813 char op, name[MAX_PATH];
814 ULONG_PTR all_cpus_mask = 0;
816 /* On systems with a large number of CPU cores (32 or 64 depending on 32-bit or 64-bit),
817 * we have issues parsing processor information:
818 * - ULONG_PTR masks as used in data structures can't hold all cores. Requires splitting
819 * data appropriately into "processor groups". We are hard coding 1.
820 * - Thread affinity code in wineserver and our CPU parsing code here work independently.
821 * So far the Windows mask applied directly to Linux, but process groups break that.
822 * (NUMA systems you may have multiple non-full groups.)
824 if(sysfs_count_list_elements("/sys/devices/system/cpu/present", &max_cpus) && max_cpus > MAXIMUM_PROCESSORS)
826 FIXME("Improve CPU info reporting: system supports %u logical cores, but only %u supported!\n",
827 max_cpus, MAXIMUM_PROCESSORS);
830 fcpu_list = fopen("/sys/devices/system/cpu/online", "r");
831 if (!fcpu_list) return STATUS_NOT_IMPLEMENTED;
833 while (!feof(fcpu_list))
835 if (!fscanf(fcpu_list, "%u%c ", &beg, &op)) break;
836 if (op == '-') fscanf(fcpu_list, "%u%c ", &end, &op);
837 else end = beg;
839 for(i = beg; i <= end; i++)
841 DWORD phys_core = 0;
842 ULONG_PTR thread_mask = 0;
844 if (i > 8*sizeof(ULONG_PTR))
846 FIXME("skipping logical processor %d\n", i);
847 continue;
850 if (relation == RelationAll || relation == RelationProcessorPackage)
852 sprintf(name, core_info, i, "physical_package_id");
853 f = fopen(name, "r");
854 if (f)
856 fscanf(f, "%u", &r);
857 fclose(f);
859 else r = 0;
860 if (!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorPackage, r, (ULONG_PTR)1 << i))
862 fclose(fcpu_list);
863 return STATUS_NO_MEMORY;
867 /* Sysfs enumerates logical cores (and not physical cores), but Windows enumerates
868 * by physical core. Upon enumerating a logical core in sysfs, we register a physical
869 * core and all its logical cores. In order to not report physical cores multiple
870 * times, we pass a unique physical core ID to logical_proc_info_add_by_id and let
871 * that call figure out any duplication.
872 * Obtain a unique physical core ID from the first element of thread_siblings_list.
873 * This list provides logical cores sharing the same physical core. The IDs are based
874 * on kernel cpu core numbering as opposed to a hardware core ID like provided through
875 * 'core_id', so are suitable as a unique ID.
877 if(relation == RelationAll || relation == RelationProcessorCore ||
878 relation == RelationNumaNode || relation == RelationGroup)
880 /* Mask of logical threads sharing same physical core in kernel core numbering. */
881 sprintf(name, core_info, i, "thread_siblings");
882 if(!sysfs_parse_bitmap(name, &thread_mask)) thread_mask = 1<<i;
884 /* Needed later for NumaNode and Group. */
885 all_cpus_mask |= thread_mask;
887 if (relation == RelationAll || relation == RelationProcessorCore)
889 sprintf(name, core_info, i, "thread_siblings_list");
890 f = fopen(name, "r");
891 if (f)
893 fscanf(f, "%d%c", &phys_core, &op);
894 fclose(f);
896 else phys_core = i;
898 if (!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorCore, phys_core, thread_mask))
900 fclose(fcpu_list);
901 return STATUS_NO_MEMORY;
906 if (relation == RelationAll || relation == RelationCache)
908 for(j = 0; j < 4; j++)
910 CACHE_DESCRIPTOR cache;
911 ULONG_PTR mask = 0;
913 sprintf(name, cache_info, i, j, "shared_cpu_map");
914 if(!sysfs_parse_bitmap(name, &mask)) continue;
916 sprintf(name, cache_info, i, j, "level");
917 f = fopen(name, "r");
918 if(!f) continue;
919 fscanf(f, "%u", &r);
920 fclose(f);
921 cache.Level = r;
923 sprintf(name, cache_info, i, j, "ways_of_associativity");
924 f = fopen(name, "r");
925 if(!f) continue;
926 fscanf(f, "%u", &r);
927 fclose(f);
928 cache.Associativity = r;
930 sprintf(name, cache_info, i, j, "coherency_line_size");
931 f = fopen(name, "r");
932 if(!f) continue;
933 fscanf(f, "%u", &r);
934 fclose(f);
935 cache.LineSize = r;
937 sprintf(name, cache_info, i, j, "size");
938 f = fopen(name, "r");
939 if(!f) continue;
940 fscanf(f, "%u%c", &r, &op);
941 fclose(f);
942 if(op != 'K')
943 WARN("unknown cache size %u%c\n", r, op);
944 cache.Size = (op=='K' ? r*1024 : r);
946 sprintf(name, cache_info, i, j, "type");
947 f = fopen(name, "r");
948 if(!f) continue;
949 fscanf(f, "%s", name);
950 fclose(f);
951 if (!memcmp(name, "Data", 5))
952 cache.Type = CacheData;
953 else if(!memcmp(name, "Instruction", 11))
954 cache.Type = CacheInstruction;
955 else
956 cache.Type = CacheUnified;
958 if (!logical_proc_info_add_cache(data, dataex, &len, max_len, mask, &cache))
960 fclose(fcpu_list);
961 return STATUS_NO_MEMORY;
967 fclose(fcpu_list);
969 num_cpus = count_bits(all_cpus_mask);
971 if(relation == RelationAll || relation == RelationNumaNode)
973 fnuma_list = fopen("/sys/devices/system/node/online", "r");
974 if (!fnuma_list)
976 if (!logical_proc_info_add_numa_node(data, dataex, &len, max_len, all_cpus_mask, 0))
977 return STATUS_NO_MEMORY;
979 else
981 while (!feof(fnuma_list))
983 if (!fscanf(fnuma_list, "%u%c ", &beg, &op))
984 break;
985 if (op == '-') fscanf(fnuma_list, "%u%c ", &end, &op);
986 else end = beg;
988 for (i = beg; i <= end; i++)
990 ULONG_PTR mask = 0;
992 sprintf(name, numa_info, i);
993 if (!sysfs_parse_bitmap( name, &mask )) continue;
995 if (!logical_proc_info_add_numa_node(data, dataex, &len, max_len, mask, i))
997 fclose(fnuma_list);
998 return STATUS_NO_MEMORY;
1002 fclose(fnuma_list);
1006 if(dataex && (relation == RelationAll || relation == RelationGroup))
1007 logical_proc_info_add_group(dataex, &len, max_len, num_cpus, all_cpus_mask);
1009 if(data)
1010 *max_len = len * sizeof(**data);
1011 else
1012 *max_len = len;
1014 return STATUS_SUCCESS;
1017 #elif defined(__APPLE__)
1019 /* for 'data', max_len is the array count. for 'dataex', max_len is in bytes */
1020 static NTSTATUS create_logical_proc_info( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data,
1021 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **dataex,
1022 DWORD *max_len, DWORD relation)
1024 DWORD pkgs_no, cores_no, lcpu_no, lcpu_per_core, cores_per_package, assoc, len = 0;
1025 DWORD cache_ctrs[10] = {0};
1026 ULONG_PTR all_cpus_mask = 0;
1027 CACHE_DESCRIPTOR cache[10];
1028 LONGLONG cache_size, cache_line_size, cache_sharing[10];
1029 size_t size;
1030 DWORD p,i,j,k;
1032 if (relation != RelationAll)
1033 FIXME("Relationship filtering not implemented: 0x%x\n", relation);
1035 lcpu_no = NtCurrentTeb()->Peb->NumberOfProcessors;
1037 size = sizeof(pkgs_no);
1038 if (sysctlbyname("hw.packages", &pkgs_no, &size, NULL, 0))
1039 pkgs_no = 1;
1041 size = sizeof(cores_no);
1042 if (sysctlbyname("hw.physicalcpu", &cores_no, &size, NULL, 0))
1043 cores_no = lcpu_no;
1045 TRACE("%u logical CPUs from %u physical cores across %u packages\n",
1046 lcpu_no, cores_no, pkgs_no);
1048 lcpu_per_core = lcpu_no / cores_no;
1049 cores_per_package = cores_no / pkgs_no;
1051 memset(cache, 0, sizeof(cache));
1052 cache[1].Level = 1;
1053 cache[1].Type = CacheInstruction;
1054 cache[1].Associativity = 8; /* reasonable default */
1055 cache[1].LineSize = 0x40; /* reasonable default */
1056 cache[2].Level = 1;
1057 cache[2].Type = CacheData;
1058 cache[2].Associativity = 8;
1059 cache[2].LineSize = 0x40;
1060 cache[3].Level = 2;
1061 cache[3].Type = CacheUnified;
1062 cache[3].Associativity = 8;
1063 cache[3].LineSize = 0x40;
1064 cache[4].Level = 3;
1065 cache[4].Type = CacheUnified;
1066 cache[4].Associativity = 12;
1067 cache[4].LineSize = 0x40;
1069 size = sizeof(cache_line_size);
1070 if (!sysctlbyname("hw.cachelinesize", &cache_line_size, &size, NULL, 0))
1072 for (i = 1; i < 5; i++) cache[i].LineSize = cache_line_size;
1075 /* TODO: set actual associativity for all caches */
1076 size = sizeof(assoc);
1077 if (!sysctlbyname("machdep.cpu.cache.L2_associativity", &assoc, &size, NULL, 0))
1078 cache[3].Associativity = assoc;
1080 size = sizeof(cache_size);
1081 if (!sysctlbyname("hw.l1icachesize", &cache_size, &size, NULL, 0))
1082 cache[1].Size = cache_size;
1083 size = sizeof(cache_size);
1084 if (!sysctlbyname("hw.l1dcachesize", &cache_size, &size, NULL, 0))
1085 cache[2].Size = cache_size;
1086 size = sizeof(cache_size);
1087 if (!sysctlbyname("hw.l2cachesize", &cache_size, &size, NULL, 0))
1088 cache[3].Size = cache_size;
1089 size = sizeof(cache_size);
1090 if (!sysctlbyname("hw.l3cachesize", &cache_size, &size, NULL, 0))
1091 cache[4].Size = cache_size;
1093 size = sizeof(cache_sharing);
1094 if (sysctlbyname("hw.cacheconfig", cache_sharing, &size, NULL, 0) < 0)
1096 cache_sharing[1] = lcpu_per_core;
1097 cache_sharing[2] = lcpu_per_core;
1098 cache_sharing[3] = lcpu_per_core;
1099 cache_sharing[4] = lcpu_no;
1101 else
1103 /* in cache[], indexes 1 and 2 are l1 caches */
1104 cache_sharing[4] = cache_sharing[3];
1105 cache_sharing[3] = cache_sharing[2];
1106 cache_sharing[2] = cache_sharing[1];
1109 for(p = 0; p < pkgs_no; ++p)
1111 for(j = 0; j < cores_per_package && p * cores_per_package + j < cores_no; ++j)
1113 ULONG_PTR mask = 0;
1114 DWORD phys_core;
1116 for(k = 0; k < lcpu_per_core; ++k) mask |= (ULONG_PTR)1 << (j * lcpu_per_core + k);
1118 all_cpus_mask |= mask;
1120 /* add to package */
1121 if(!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorPackage, p, mask))
1122 return STATUS_NO_MEMORY;
1124 /* add new core */
1125 phys_core = p * cores_per_package + j;
1126 if(!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorCore, phys_core, mask))
1127 return STATUS_NO_MEMORY;
1129 for(i = 1; i < 5; ++i)
1131 if(cache_ctrs[i] == 0 && cache[i].Size > 0)
1133 mask = 0;
1134 for(k = 0; k < cache_sharing[i]; ++k)
1135 mask |= (ULONG_PTR)1 << (j * lcpu_per_core + k);
1137 if(!logical_proc_info_add_cache(data, dataex, &len, max_len, mask, &cache[i]))
1138 return STATUS_NO_MEMORY;
1141 cache_ctrs[i] += lcpu_per_core;
1142 if(cache_ctrs[i] == cache_sharing[i]) cache_ctrs[i] = 0;
1147 /* OSX doesn't support NUMA, so just make one NUMA node for all CPUs */
1148 if(!logical_proc_info_add_numa_node(data, dataex, &len, max_len, all_cpus_mask, 0))
1149 return STATUS_NO_MEMORY;
1151 if(dataex) logical_proc_info_add_group(dataex, &len, max_len, lcpu_no, all_cpus_mask);
1153 if(data)
1154 *max_len = len * sizeof(**data);
1155 else
1156 *max_len = len;
1158 return STATUS_SUCCESS;
1161 #else
1163 static NTSTATUS create_logical_proc_info( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data,
1164 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **dataex,
1165 DWORD *max_len, DWORD relation )
1167 FIXME("stub\n");
1168 return STATUS_NOT_IMPLEMENTED;
1170 #endif
1172 static NTSTATUS create_cpuset_info(SYSTEM_CPU_SET_INFORMATION *info)
1174 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *proc_info;
1175 BYTE core_index, cache_index, max_cache_level;
1176 unsigned int i, j, count;
1177 BYTE *proc_info_buffer;
1178 DWORD cpu_info_size;
1179 ULONG64 cpu_mask;
1180 NTSTATUS status;
1182 count = NtCurrentTeb()->Peb->NumberOfProcessors;
1184 cpu_info_size = 3 * sizeof(*proc_info);
1185 if (!(proc_info_buffer = malloc(cpu_info_size)))
1186 return STATUS_NO_MEMORY;
1188 if ((status = create_logical_proc_info(NULL, (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **)&proc_info_buffer,
1189 &cpu_info_size, RelationAll)))
1191 free(proc_info_buffer);
1192 return status;
1195 max_cache_level = 0;
1196 proc_info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)proc_info_buffer;
1197 for (i = 0; (BYTE *)proc_info != proc_info_buffer + cpu_info_size; ++i)
1199 if (proc_info->Relationship == RelationCache)
1201 if (max_cache_level < proc_info->u.Cache.Level)
1202 max_cache_level = proc_info->u.Cache.Level;
1204 proc_info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)((BYTE *)proc_info + proc_info->Size);
1207 memset(info, 0, count * sizeof(*info));
1209 core_index = 0;
1210 cache_index = 0;
1211 proc_info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)proc_info_buffer;
1212 for (i = 0; i < count; ++i)
1214 info[i].Size = sizeof(*info);
1215 info[i].Type = CpuSetInformation;
1216 info[i].u.CpuSet.Id = 0x100 + i;
1217 info[i].u.CpuSet.LogicalProcessorIndex = i;
1220 for (i = 0; (BYTE *)proc_info != (BYTE *)proc_info_buffer + cpu_info_size; ++i)
1222 if (proc_info->Relationship == RelationProcessorCore)
1224 if (proc_info->u.Processor.GroupCount != 1)
1226 FIXME("Unsupported group count %u.\n", proc_info->u.Processor.GroupCount);
1227 continue;
1229 cpu_mask = proc_info->u.Processor.GroupMask[0].Mask;
1230 for (j = 0; j < count; ++j)
1231 if (((ULONG64)1 << j) & cpu_mask)
1233 info[j].u.CpuSet.CoreIndex = core_index;
1234 info[j].u.CpuSet.EfficiencyClass = proc_info->u.Processor.EfficiencyClass;
1236 ++core_index;
1238 else if (proc_info->Relationship == RelationCache)
1240 if (proc_info->u.Cache.Level == max_cache_level)
1242 cpu_mask = proc_info->u.Cache.GroupMask.Mask;
1243 for (j = 0; j < count; ++j)
1244 if (((ULONG64)1 << j) & cpu_mask)
1245 info[j].u.CpuSet.LastLevelCacheIndex = cache_index;
1247 ++cache_index;
1249 else if (proc_info->Relationship == RelationNumaNode)
1251 cpu_mask = proc_info->u.NumaNode.GroupMask.Mask;
1252 for (j = 0; j < count; ++j)
1253 if (((ULONG64)1 << j) & cpu_mask)
1254 info[j].u.CpuSet.NumaNodeIndex = proc_info->u.NumaNode.NodeNumber;
1256 proc_info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)((BYTE *)proc_info + proc_info->Size);
1259 free(proc_info_buffer);
1261 return STATUS_SUCCESS;
1264 #ifdef linux
1266 static void copy_smbios_string( char **buffer, char *s, size_t len )
1268 if (!len) return;
1269 memcpy(*buffer, s, len + 1);
1270 *buffer += len + 1;
1273 static size_t get_smbios_string( const char *path, char *str, size_t size )
1275 FILE *file;
1276 size_t len;
1278 if (!(file = fopen(path, "r"))) return 0;
1280 len = fread( str, 1, size - 1, file );
1281 fclose( file );
1283 if (len >= 1 && str[len - 1] == '\n') len--;
1284 str[len] = 0;
1285 return len;
1288 static void get_system_uuid( GUID *uuid )
1290 static const unsigned char hex[] =
1292 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x00 */
1293 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x10 */
1294 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x20 */
1295 0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0, /* 0x30 */
1296 0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0, /* 0x40 */
1297 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x50 */
1298 0,10,11,12,13,14,15 /* 0x60 */
1300 int fd;
1302 memset( uuid, 0xff, sizeof(*uuid) );
1303 if ((fd = open( "/var/lib/dbus/machine-id", O_RDONLY )) != -1)
1305 unsigned char buf[32], *p = buf;
1306 if (read( fd, buf, sizeof(buf) ) == sizeof(buf))
1308 uuid->Data1 = hex[p[6]] << 28 | hex[p[7]] << 24 | hex[p[4]] << 20 | hex[p[5]] << 16 |
1309 hex[p[2]] << 12 | hex[p[3]] << 8 | hex[p[0]] << 4 | hex[p[1]];
1311 uuid->Data2 = hex[p[10]] << 12 | hex[p[11]] << 8 | hex[p[8]] << 4 | hex[p[9]];
1312 uuid->Data3 = hex[p[14]] << 12 | hex[p[15]] << 8 | hex[p[12]] << 4 | hex[p[13]];
1314 uuid->Data4[0] = hex[p[16]] << 4 | hex[p[17]];
1315 uuid->Data4[1] = hex[p[18]] << 4 | hex[p[19]];
1316 uuid->Data4[2] = hex[p[20]] << 4 | hex[p[21]];
1317 uuid->Data4[3] = hex[p[22]] << 4 | hex[p[23]];
1318 uuid->Data4[4] = hex[p[24]] << 4 | hex[p[25]];
1319 uuid->Data4[5] = hex[p[26]] << 4 | hex[p[27]];
1320 uuid->Data4[6] = hex[p[28]] << 4 | hex[p[29]];
1321 uuid->Data4[7] = hex[p[30]] << 4 | hex[p[31]];
1323 close( fd );
1327 static NTSTATUS get_firmware_info( SYSTEM_FIRMWARE_TABLE_INFORMATION *sfti, ULONG available_len,
1328 ULONG *required_len )
1330 switch (sfti->ProviderSignature)
1332 case RSMB:
1334 char bios_vendor[128], bios_version[128], bios_date[128];
1335 size_t bios_vendor_len, bios_version_len, bios_date_len;
1336 char system_vendor[128], system_product[128], system_version[128], system_serial[128];
1337 size_t system_vendor_len, system_product_len, system_version_len, system_serial_len;
1338 char system_sku[128], system_family[128];
1339 size_t system_sku_len, system_family_len;
1340 char board_vendor[128], board_product[128], board_version[128], board_serial[128], board_asset_tag[128];
1341 size_t board_vendor_len, board_product_len, board_version_len, board_serial_len, board_asset_tag_len;
1342 char chassis_vendor[128], chassis_version[128], chassis_serial[128], chassis_asset_tag[128];
1343 char chassis_type[11] = "2"; /* unknown */
1344 size_t chassis_vendor_len, chassis_version_len, chassis_serial_len, chassis_asset_tag_len;
1345 char *buffer = (char*)sfti->TableBuffer;
1346 BYTE string_count;
1347 BYTE handle_count = 0;
1348 struct smbios_prologue *prologue;
1349 struct smbios_bios *bios;
1350 struct smbios_system *system;
1351 struct smbios_board *board;
1352 struct smbios_chassis *chassis;
1353 struct smbios_boot_info *boot_info;
1354 struct smbios_header *end_of_table;
1356 #define S(s) s, sizeof(s)
1357 bios_vendor_len = get_smbios_string("/sys/class/dmi/id/bios_vendor", S(bios_vendor));
1358 bios_version_len = get_smbios_string("/sys/class/dmi/id/bios_version", S(bios_version));
1359 bios_date_len = get_smbios_string("/sys/class/dmi/id/bios_date", S(bios_date));
1360 system_vendor_len = get_smbios_string("/sys/class/dmi/id/sys_vendor", S(system_vendor));
1361 system_product_len = get_smbios_string("/sys/class/dmi/id/product_name", S(system_product));
1362 system_version_len = get_smbios_string("/sys/class/dmi/id/product_version", S(system_version));
1363 system_serial_len = get_smbios_string("/sys/class/dmi/id/product_serial", S(system_serial));
1364 system_sku_len = get_smbios_string("/sys/class/dmi/id/product_sku", S(system_sku));
1365 system_family_len = get_smbios_string("/sys/class/dmi/id/product_family", S(system_family));
1366 board_vendor_len = get_smbios_string("/sys/class/dmi/id/board_vendor", S(board_vendor));
1367 board_product_len = get_smbios_string("/sys/class/dmi/id/board_name", S(board_product));
1368 board_version_len = get_smbios_string("/sys/class/dmi/id/board_version", S(board_version));
1369 board_serial_len = get_smbios_string("/sys/class/dmi/id/board_serial", S(board_serial));
1370 board_asset_tag_len = get_smbios_string("/sys/class/dmi/id/board_asset_tag", S(board_asset_tag));
1371 chassis_vendor_len = get_smbios_string("/sys/class/dmi/id/chassis_vendor", S(chassis_vendor));
1372 chassis_version_len = get_smbios_string("/sys/class/dmi/id/chassis_version", S(chassis_version));
1373 chassis_serial_len = get_smbios_string("/sys/class/dmi/id/chassis_serial", S(chassis_serial));
1374 chassis_asset_tag_len = get_smbios_string("/sys/class/dmi/id/chassis_tag", S(chassis_asset_tag));
1375 get_smbios_string("/sys/class/dmi/id/chassis_type", S(chassis_type));
1376 #undef S
1378 *required_len = sizeof(struct smbios_prologue);
1380 #define L(l) (l + (l ? 1 : 0))
1381 *required_len += sizeof(struct smbios_bios);
1382 *required_len += max(L(bios_vendor_len) + L(bios_version_len) + L(bios_date_len) + 1, 2);
1384 *required_len += sizeof(struct smbios_system);
1385 *required_len += max(L(system_vendor_len) + L(system_product_len) + L(system_version_len) +
1386 L(system_serial_len) + L(system_sku_len) + L(system_family_len) + 1, 2);
1388 *required_len += sizeof(struct smbios_board);
1389 *required_len += max(L(board_vendor_len) + L(board_product_len) + L(board_version_len) +
1390 L(board_serial_len) + L(board_asset_tag_len) + 1, 2);
1392 *required_len += sizeof(struct smbios_chassis);
1393 *required_len += max(L(chassis_vendor_len) + L(chassis_version_len) + L(chassis_serial_len) +
1394 L(chassis_asset_tag_len) + 1, 2);
1396 *required_len += sizeof(struct smbios_boot_info);
1397 *required_len += 2;
1399 *required_len += sizeof(struct smbios_header);
1400 *required_len += 2;
1401 #undef L
1403 sfti->TableBufferLength = *required_len;
1405 *required_len += FIELD_OFFSET(SYSTEM_FIRMWARE_TABLE_INFORMATION, TableBuffer);
1407 if (available_len < *required_len)
1408 return STATUS_BUFFER_TOO_SMALL;
1410 prologue = (struct smbios_prologue*)buffer;
1411 prologue->calling_method = 0;
1412 prologue->major_version = 2;
1413 prologue->minor_version = 4;
1414 prologue->revision = 0;
1415 prologue->length = sfti->TableBufferLength - sizeof(struct smbios_prologue);
1416 buffer += sizeof(struct smbios_prologue);
1418 string_count = 0;
1419 bios = (struct smbios_bios*)buffer;
1420 bios->hdr.type = 0;
1421 bios->hdr.length = sizeof(struct smbios_bios);
1422 bios->hdr.handle = handle_count++;
1423 bios->vendor = bios_vendor_len ? ++string_count : 0;
1424 bios->version = bios_version_len ? ++string_count : 0;
1425 bios->start = 0;
1426 bios->date = bios_date_len ? ++string_count : 0;
1427 bios->size = 0;
1428 bios->characteristics = 0x4; /* not supported */
1429 bios->characteristics_ext[0] = 0;
1430 bios->characteristics_ext[1] = 0;
1431 bios->system_bios_major_release = 0xFF; /* not supported */
1432 bios->system_bios_minor_release = 0xFF; /* not supported */
1433 bios->ec_firmware_major_release = 0xFF; /* not supported */
1434 bios->ec_firmware_minor_release = 0xFF; /* not supported */
1435 buffer += sizeof(struct smbios_bios);
1437 copy_smbios_string(&buffer, bios_vendor, bios_vendor_len);
1438 copy_smbios_string(&buffer, bios_version, bios_version_len);
1439 copy_smbios_string(&buffer, bios_date, bios_date_len);
1440 if (!string_count) *buffer++ = 0;
1441 *buffer++ = 0;
1443 string_count = 0;
1444 system = (struct smbios_system*)buffer;
1445 system->hdr.type = 1;
1446 system->hdr.length = sizeof(struct smbios_system);
1447 system->hdr.handle = handle_count++;
1448 system->vendor = system_vendor_len ? ++string_count : 0;
1449 system->product = system_product_len ? ++string_count : 0;
1450 system->version = system_version_len ? ++string_count : 0;
1451 system->serial = system_serial_len ? ++string_count : 0;
1452 get_system_uuid( (GUID *)system->uuid );
1453 system->wake_up_type = 0x02; /* unknown */
1454 system->sku_number = system_sku_len ? ++string_count : 0;
1455 system->family = system_family_len ? ++string_count : 0;
1456 buffer += sizeof(struct smbios_system);
1458 copy_smbios_string(&buffer, system_vendor, system_vendor_len);
1459 copy_smbios_string(&buffer, system_product, system_product_len);
1460 copy_smbios_string(&buffer, system_version, system_version_len);
1461 copy_smbios_string(&buffer, system_serial, system_serial_len);
1462 copy_smbios_string(&buffer, system_sku, system_sku_len);
1463 copy_smbios_string(&buffer, system_family, system_family_len);
1464 if (!string_count) *buffer++ = 0;
1465 *buffer++ = 0;
1467 string_count = 0;
1468 chassis = (struct smbios_chassis*)buffer;
1469 chassis->hdr.type = 3;
1470 chassis->hdr.length = sizeof(struct smbios_chassis);
1471 chassis->hdr.handle = handle_count++;
1472 chassis->vendor = chassis_vendor_len ? ++string_count : 0;
1473 chassis->type = atoi(chassis_type);
1474 chassis->version = chassis_version_len ? ++string_count : 0;
1475 chassis->serial = chassis_serial_len ? ++string_count : 0;
1476 chassis->asset_tag = chassis_asset_tag_len ? ++string_count : 0;
1477 chassis->boot_state = 0x02; /* unknown */
1478 chassis->power_supply_state = 0x02; /* unknown */
1479 chassis->thermal_state = 0x02; /* unknown */
1480 chassis->security_status = 0x02; /* unknown */
1481 chassis->oem_defined = 0;
1482 chassis->height = 0; /* undefined */
1483 chassis->num_power_cords = 0; /* unspecified */
1484 chassis->num_contained_elements = 0;
1485 chassis->contained_element_rec_length = 3;
1486 buffer += sizeof(struct smbios_chassis);
1488 copy_smbios_string(&buffer, chassis_vendor, chassis_vendor_len);
1489 copy_smbios_string(&buffer, chassis_version, chassis_version_len);
1490 copy_smbios_string(&buffer, chassis_serial, chassis_serial_len);
1491 copy_smbios_string(&buffer, chassis_asset_tag, chassis_asset_tag_len);
1492 if (!string_count) *buffer++ = 0;
1493 *buffer++ = 0;
1495 string_count = 0;
1496 board = (struct smbios_board*)buffer;
1497 board->hdr.type = 2;
1498 board->hdr.length = sizeof(struct smbios_board);
1499 board->hdr.handle = handle_count++;
1500 board->vendor = board_vendor_len ? ++string_count : 0;
1501 board->product = board_product_len ? ++string_count : 0;
1502 board->version = board_version_len ? ++string_count : 0;
1503 board->serial = board_serial_len ? ++string_count : 0;
1504 board->asset_tag = board_asset_tag_len ? ++string_count : 0;
1505 board->feature_flags = 0x5; /* hosting board, removable */
1506 board->location = 0;
1507 board->chassis_handle = chassis->hdr.handle;
1508 board->board_type = 0xa; /* motherboard */
1509 board->num_contained_handles = 0;
1510 buffer += sizeof(struct smbios_board);
1512 copy_smbios_string(&buffer, board_vendor, board_vendor_len);
1513 copy_smbios_string(&buffer, board_product, board_product_len);
1514 copy_smbios_string(&buffer, board_version, board_version_len);
1515 copy_smbios_string(&buffer, board_serial, board_serial_len);
1516 copy_smbios_string(&buffer, board_asset_tag, board_asset_tag_len);
1517 if (!string_count) *buffer++ = 0;
1518 *buffer++ = 0;
1520 boot_info = (struct smbios_boot_info*)buffer;
1521 boot_info->hdr.type = 32;
1522 boot_info->hdr.length = sizeof(struct smbios_boot_info);
1523 boot_info->hdr.handle = handle_count++;
1524 memset(boot_info->reserved, 0, sizeof(boot_info->reserved));
1525 memset(boot_info->boot_status, 0, sizeof(boot_info->boot_status)); /* no errors detected */
1526 buffer += sizeof(struct smbios_boot_info);
1527 *buffer++ = 0;
1528 *buffer++ = 0;
1530 end_of_table = (struct smbios_header*)buffer;
1531 end_of_table->type = 127;
1532 end_of_table->length = sizeof(struct smbios_header);
1533 end_of_table->handle = handle_count++;
1534 buffer += sizeof(struct smbios_header);
1535 *buffer++ = 0;
1536 *buffer++ = 0;
1538 return STATUS_SUCCESS;
1540 default:
1541 FIXME("info_class SYSTEM_FIRMWARE_TABLE_INFORMATION provider %08x\n", sfti->ProviderSignature);
1542 return STATUS_NOT_IMPLEMENTED;
1546 #elif defined(__APPLE__)
1548 static NTSTATUS get_firmware_info( SYSTEM_FIRMWARE_TABLE_INFORMATION *sfti, ULONG available_len,
1549 ULONG *required_len )
1551 switch (sfti->ProviderSignature)
1553 case RSMB:
1555 io_service_t service;
1556 CFDataRef data;
1557 const UInt8 *ptr;
1558 CFIndex len;
1559 struct smbios_prologue *prologue;
1560 BYTE major_version = 2, minor_version = 0;
1562 if (!(service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleSMBIOS"))))
1564 WARN("can't find AppleSMBIOS service\n");
1565 return STATUS_NO_MEMORY;
1568 if (!(data = IORegistryEntryCreateCFProperty(service, CFSTR("SMBIOS-EPS"), kCFAllocatorDefault, 0)))
1570 WARN("can't find SMBIOS entry point\n");
1571 IOObjectRelease(service);
1572 return STATUS_NO_MEMORY;
1575 len = CFDataGetLength(data);
1576 ptr = CFDataGetBytePtr(data);
1577 if (len >= 8 && !memcmp(ptr, "_SM_", 4))
1579 major_version = ptr[6];
1580 minor_version = ptr[7];
1582 CFRelease(data);
1584 if (!(data = IORegistryEntryCreateCFProperty(service, CFSTR("SMBIOS"), kCFAllocatorDefault, 0)))
1586 WARN("can't find SMBIOS table\n");
1587 IOObjectRelease(service);
1588 return STATUS_NO_MEMORY;
1591 len = CFDataGetLength(data);
1592 ptr = CFDataGetBytePtr(data);
1593 sfti->TableBufferLength = sizeof(*prologue) + len;
1594 *required_len = sfti->TableBufferLength + FIELD_OFFSET(SYSTEM_FIRMWARE_TABLE_INFORMATION, TableBuffer);
1595 if (available_len < *required_len)
1597 CFRelease(data);
1598 IOObjectRelease(service);
1599 return STATUS_BUFFER_TOO_SMALL;
1602 prologue = (struct smbios_prologue *)sfti->TableBuffer;
1603 prologue->calling_method = 0;
1604 prologue->major_version = major_version;
1605 prologue->minor_version = minor_version;
1606 prologue->revision = 0;
1607 prologue->length = sfti->TableBufferLength - sizeof(*prologue);
1609 memcpy(sfti->TableBuffer + sizeof(*prologue), ptr, len);
1611 CFRelease(data);
1612 IOObjectRelease(service);
1613 return STATUS_SUCCESS;
1615 default:
1616 FIXME("info_class SYSTEM_FIRMWARE_TABLE_INFORMATION provider %08x\n", sfti->ProviderSignature);
1617 return STATUS_NOT_IMPLEMENTED;
1621 #else
1623 static NTSTATUS get_firmware_info( SYSTEM_FIRMWARE_TABLE_INFORMATION *sfti, ULONG available_len,
1624 ULONG *required_len )
1626 FIXME("info_class SYSTEM_FIRMWARE_TABLE_INFORMATION\n");
1627 sfti->TableBufferLength = 0;
1628 return STATUS_NOT_IMPLEMENTED;
1631 #endif
1633 static void get_performance_info( SYSTEM_PERFORMANCE_INFORMATION *info )
1635 unsigned long long totalram = 0, freeram = 0, totalswap = 0, freeswap = 0;
1636 FILE *fp;
1638 memset( info, 0, sizeof(*info) );
1640 if ((fp = fopen("/proc/uptime", "r")))
1642 double uptime, idle_time;
1644 fscanf(fp, "%lf %lf", &uptime, &idle_time);
1645 fclose(fp);
1646 info->IdleTime.QuadPart = 10000000 * idle_time;
1648 else
1650 static ULONGLONG idle;
1651 /* many programs expect IdleTime to change so fake change */
1652 info->IdleTime.QuadPart = ++idle;
1655 #ifdef linux
1656 if ((fp = fopen("/proc/meminfo", "r")))
1658 unsigned long long value;
1659 char line[64];
1661 while (fgets(line, sizeof(line), fp))
1663 if(sscanf(line, "MemTotal: %llu kB", &value) == 1)
1664 totalram += value * 1024;
1665 else if(sscanf(line, "MemFree: %llu kB", &value) == 1)
1666 freeram += value * 1024;
1667 else if(sscanf(line, "SwapTotal: %llu kB", &value) == 1)
1668 totalswap += value * 1024;
1669 else if(sscanf(line, "SwapFree: %llu kB", &value) == 1)
1670 freeswap += value * 1024;
1671 else if (sscanf(line, "Buffers: %llu", &value))
1672 freeram += value * 1024;
1673 else if (sscanf(line, "Cached: %llu", &value))
1674 freeram += value * 1024;
1676 fclose(fp);
1678 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || \
1679 defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
1681 #ifdef __APPLE__
1682 unsigned int val;
1683 #else
1684 unsigned long val;
1685 #endif
1686 int mib[2];
1687 size_t size_sys;
1689 mib[0] = CTL_HW;
1690 #ifdef HW_MEMSIZE
1692 uint64_t val64;
1693 mib[1] = HW_MEMSIZE;
1694 size_sys = sizeof(val64);
1695 if (!sysctl(mib, 2, &val64, &size_sys, NULL, 0) && size_sys == sizeof(val64)) totalram = val64;
1697 #endif
1699 #ifdef HAVE_MACH_MACH_H
1701 host_name_port_t host = mach_host_self();
1702 mach_msg_type_number_t count;
1703 #ifdef HOST_VM_INFO64_COUNT
1704 vm_statistics64_data_t vm_stat;
1706 count = HOST_VM_INFO64_COUNT;
1707 if (host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&vm_stat, &count) == KERN_SUCCESS)
1708 freeram = (vm_stat.free_count + vm_stat.inactive_count) * (ULONGLONG)page_size;
1709 #endif
1710 if (!totalram)
1712 host_basic_info_data_t info;
1713 count = HOST_BASIC_INFO_COUNT;
1714 if (host_info(host, HOST_BASIC_INFO, (host_info_t)&info, &count) == KERN_SUCCESS)
1715 totalram = info.max_mem;
1717 mach_port_deallocate(mach_task_self(), host);
1719 #endif
1721 if (!totalram)
1723 mib[1] = HW_PHYSMEM;
1724 size_sys = sizeof(val);
1725 if (!sysctl(mib, 2, &val, &size_sys, NULL, 0) && size_sys == sizeof(val)) totalram = val;
1727 if (!freeram)
1729 mib[1] = HW_USERMEM;
1730 size_sys = sizeof(val);
1731 if (!sysctl(mib, 2, &val, &size_sys, NULL, 0) && size_sys == sizeof(val)) freeram = val;
1733 #ifdef VM_SWAPUSAGE
1735 struct xsw_usage swap;
1736 mib[0] = CTL_VM;
1737 mib[1] = VM_SWAPUSAGE;
1738 size_sys = sizeof(swap);
1739 if (!sysctl(mib, 2, &swap, &size_sys, NULL, 0) && size_sys == sizeof(swap))
1741 totalswap = swap.xsu_total;
1742 freeswap = swap.xsu_avail;
1745 #endif
1747 #endif
1748 info->AvailablePages = freeram / page_size;
1749 info->TotalCommittedPages = (totalram + totalswap - freeram - freeswap) / page_size;
1750 info->TotalCommitLimit = (totalram + totalswap) / page_size;
1754 /* calculate the mday of dst change date, so that for instance Sun 5 Oct 2007
1755 * (last Sunday in October of 2007) becomes Sun Oct 28 2007
1757 * Note: year, day and month must be in unix format.
1759 static int weekday_to_mday(int year, int day, int mon, int day_of_week)
1761 struct tm date;
1762 time_t tmp;
1763 int wday, mday;
1765 /* find first day in the month matching week day of the date */
1766 memset(&date, 0, sizeof(date));
1767 date.tm_year = year;
1768 date.tm_mon = mon;
1769 date.tm_mday = -1;
1770 date.tm_wday = -1;
1773 date.tm_mday++;
1774 tmp = mktime(&date);
1775 } while (date.tm_wday != day_of_week || date.tm_mon != mon);
1777 mday = date.tm_mday;
1779 /* find number of week days in the month matching week day of the date */
1780 wday = 1; /* 1 - 1st, ...., 5 - last */
1781 while (wday < day)
1783 struct tm *tm;
1785 date.tm_mday += 7;
1786 tmp = mktime(&date);
1787 tm = localtime(&tmp);
1788 if (tm->tm_mon != mon)
1789 break;
1790 mday = tm->tm_mday;
1791 wday++;
1794 return mday;
1797 static BOOL match_tz_date( const RTL_SYSTEM_TIME *st, const RTL_SYSTEM_TIME *reg_st )
1799 WORD wDay;
1801 if (st->wMonth != reg_st->wMonth) return FALSE;
1802 if (!st->wMonth) return TRUE; /* no transition dates */
1803 wDay = reg_st->wDay;
1804 if (!reg_st->wYear) /* date in a day-of-week format */
1805 wDay = weekday_to_mday(st->wYear - 1900, reg_st->wDay, reg_st->wMonth - 1, reg_st->wDayOfWeek);
1807 return (st->wDay == wDay &&
1808 st->wHour == reg_st->wHour &&
1809 st->wMinute == reg_st->wMinute &&
1810 st->wSecond == reg_st->wSecond &&
1811 st->wMilliseconds == reg_st->wMilliseconds);
1814 static BOOL match_tz_info( const RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi,
1815 const RTL_DYNAMIC_TIME_ZONE_INFORMATION *reg_tzi )
1817 return (tzi->Bias == reg_tzi->Bias &&
1818 match_tz_date(&tzi->StandardDate, &reg_tzi->StandardDate) &&
1819 match_tz_date(&tzi->DaylightDate, &reg_tzi->DaylightDate));
1822 static BOOL match_past_tz_bias( time_t past_time, LONG past_bias )
1824 LONG bias;
1825 struct tm *tm;
1826 if (!past_time) return TRUE;
1828 tm = gmtime( &past_time );
1829 bias = (LONG)(mktime(tm) - past_time) / 60;
1830 return bias == past_bias;
1833 static BOOL match_tz_name( const char *tz_name, const RTL_DYNAMIC_TIME_ZONE_INFORMATION *reg_tzi )
1835 static const struct {
1836 WCHAR key_name[32];
1837 const char *short_name;
1838 time_t past_time;
1839 LONG past_bias;
1841 mapping[] =
1843 { {'N','o','r','t','h',' ','K','o','r','e','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',0 },
1844 "KST", 1451606400 /* 2016-01-01 00:00:00 UTC */, -510 },
1845 { {'K','o','r','e','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',0 },
1846 "KST", 1451606400 /* 2016-01-01 00:00:00 UTC */, -540 },
1847 { {'T','o','k','y','o',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',0 },
1848 "JST" },
1849 { {'Y','a','k','u','t','s','k',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',0 },
1850 "+09" }, /* YAKST was used until tzdata 2016f */
1852 unsigned int i;
1854 if (reg_tzi->DaylightDate.wMonth) return TRUE;
1855 for (i = 0; i < ARRAY_SIZE(mapping); i++)
1857 if (!wcscmp( mapping[i].key_name, reg_tzi->TimeZoneKeyName ))
1858 return !strcmp( mapping[i].short_name, tz_name )
1859 && match_past_tz_bias( mapping[i].past_time, mapping[i].past_bias );
1861 return TRUE;
1864 static BOOL reg_query_value( HKEY key, LPCWSTR name, DWORD type, void *data, DWORD count )
1866 char buf[256];
1867 UNICODE_STRING nameW;
1868 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buf;
1870 if (count > sizeof(buf) - sizeof(KEY_VALUE_PARTIAL_INFORMATION)) return FALSE;
1872 nameW.Buffer = (WCHAR *)name;
1873 nameW.Length = wcslen( name ) * sizeof(WCHAR);
1874 if (NtQueryValueKey( key, &nameW, KeyValuePartialInformation, buf, sizeof(buf), &count ))
1875 return FALSE;
1877 if (info->Type != type) return FALSE;
1878 memcpy( data, info->Data, info->DataLength );
1879 return TRUE;
1882 static void find_reg_tz_info(RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi, const char* tz_name, int year)
1884 static const WCHAR stdW[] = { 'S','t','d',0 };
1885 static const WCHAR dltW[] = { 'D','l','t',0 };
1886 static const WCHAR mui_stdW[] = { 'M','U','I','_','S','t','d',0 };
1887 static const WCHAR mui_dltW[] = { 'M','U','I','_','D','l','t',0 };
1888 static const WCHAR tziW[] = { 'T','Z','I',0 };
1889 static const WCHAR Time_ZonesW[] = { 'M','a','c','h','i','n','e','\\',
1890 'S','o','f','t','w','a','r','e','\\',
1891 'M','i','c','r','o','s','o','f','t','\\',
1892 'W','i','n','d','o','w','s',' ','N','T','\\',
1893 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
1894 'T','i','m','e',' ','Z','o','n','e','s',0 };
1895 static const WCHAR Dynamic_DstW[] = { 'D','y','n','a','m','i','c',' ','D','S','T',0 };
1896 RTL_DYNAMIC_TIME_ZONE_INFORMATION reg_tzi;
1897 HANDLE key, subkey, subkey_dyn = 0;
1898 ULONG idx, len;
1899 OBJECT_ATTRIBUTES attr;
1900 UNICODE_STRING nameW;
1901 WCHAR yearW[16];
1902 char buffer[128];
1903 KEY_BASIC_INFORMATION *info = (KEY_BASIC_INFORMATION *)buffer;
1905 sprintf( buffer, "%u", year );
1906 ascii_to_unicode( yearW, buffer, strlen(buffer) + 1 );
1907 init_unicode_string( &nameW, Time_ZonesW );
1908 InitializeObjectAttributes( &attr, &nameW, 0, 0, NULL );
1909 if (NtOpenKey( &key, KEY_READ, &attr )) return;
1911 idx = 0;
1912 while (!NtEnumerateKey( key, idx++, KeyBasicInformation, buffer, sizeof(buffer), &len ))
1914 struct tz_reg_data
1916 LONG bias;
1917 LONG std_bias;
1918 LONG dlt_bias;
1919 RTL_SYSTEM_TIME std_date;
1920 RTL_SYSTEM_TIME dlt_date;
1921 } tz_data;
1922 BOOL is_dynamic = FALSE;
1924 nameW.Buffer = info->Name;
1925 nameW.Length = info->NameLength;
1926 attr.RootDirectory = key;
1927 if (NtOpenKey( &subkey, KEY_READ, &attr )) continue;
1929 memset( &reg_tzi, 0, sizeof(reg_tzi) );
1930 memcpy(reg_tzi.TimeZoneKeyName, nameW.Buffer, nameW.Length);
1931 reg_tzi.TimeZoneKeyName[nameW.Length/sizeof(WCHAR)] = 0;
1933 if (!reg_query_value(subkey, mui_stdW, REG_SZ, reg_tzi.StandardName, sizeof(reg_tzi.StandardName)) &&
1934 !reg_query_value(subkey, stdW, REG_SZ, reg_tzi.StandardName, sizeof(reg_tzi.StandardName)))
1935 goto next;
1937 if (!reg_query_value(subkey, mui_dltW, REG_SZ, reg_tzi.DaylightName, sizeof(reg_tzi.DaylightName)) &&
1938 !reg_query_value(subkey, dltW, REG_SZ, reg_tzi.DaylightName, sizeof(reg_tzi.DaylightName)))
1939 goto next;
1941 /* Check for Dynamic DST entry first */
1942 nameW.Buffer = (WCHAR *)Dynamic_DstW;
1943 nameW.Length = sizeof(Dynamic_DstW) - sizeof(WCHAR);
1944 attr.RootDirectory = subkey;
1945 if (!NtOpenKey( &subkey_dyn, KEY_READ, &attr ))
1947 is_dynamic = reg_query_value( subkey_dyn, yearW, REG_BINARY, &tz_data, sizeof(tz_data) );
1948 NtClose( subkey_dyn );
1950 if (!is_dynamic && !reg_query_value( subkey, tziW, REG_BINARY, &tz_data, sizeof(tz_data) ))
1951 goto next;
1953 reg_tzi.Bias = tz_data.bias;
1954 reg_tzi.StandardBias = tz_data.std_bias;
1955 reg_tzi.DaylightBias = tz_data.dlt_bias;
1956 reg_tzi.StandardDate = tz_data.std_date;
1957 reg_tzi.DaylightDate = tz_data.dlt_date;
1959 TRACE("%s: bias %d\n", debugstr_us(&nameW), reg_tzi.Bias);
1960 TRACE("std (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
1961 reg_tzi.StandardDate.wDay, reg_tzi.StandardDate.wMonth,
1962 reg_tzi.StandardDate.wYear, reg_tzi.StandardDate.wDayOfWeek,
1963 reg_tzi.StandardDate.wHour, reg_tzi.StandardDate.wMinute,
1964 reg_tzi.StandardDate.wSecond, reg_tzi.StandardDate.wMilliseconds,
1965 reg_tzi.StandardBias);
1966 TRACE("dst (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
1967 reg_tzi.DaylightDate.wDay, reg_tzi.DaylightDate.wMonth,
1968 reg_tzi.DaylightDate.wYear, reg_tzi.DaylightDate.wDayOfWeek,
1969 reg_tzi.DaylightDate.wHour, reg_tzi.DaylightDate.wMinute,
1970 reg_tzi.DaylightDate.wSecond, reg_tzi.DaylightDate.wMilliseconds,
1971 reg_tzi.DaylightBias);
1973 if (match_tz_info( tzi, &reg_tzi ) && match_tz_name( tz_name, &reg_tzi ))
1975 *tzi = reg_tzi;
1976 NtClose( subkey );
1977 NtClose( key );
1978 return;
1980 next:
1981 NtClose( subkey );
1983 NtClose( key );
1985 if (idx == 1) return; /* registry info not initialized yet */
1987 FIXME("Can't find matching timezone information in the registry for "
1988 "%s, bias %d, std (d/m/y): %u/%02u/%04u, dlt (d/m/y): %u/%02u/%04u\n",
1989 tz_name, tzi->Bias,
1990 tzi->StandardDate.wDay, tzi->StandardDate.wMonth, tzi->StandardDate.wYear,
1991 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth, tzi->DaylightDate.wYear);
1994 static time_t find_dst_change(unsigned long min, unsigned long max, int *is_dst)
1996 time_t start;
1997 struct tm *tm;
1999 start = min;
2000 tm = localtime(&start);
2001 *is_dst = !tm->tm_isdst;
2002 TRACE("starting date isdst %d, %s", !*is_dst, ctime(&start));
2004 while (min <= max)
2006 time_t pos = (min + max) / 2;
2007 tm = localtime(&pos);
2009 if (tm->tm_isdst != *is_dst)
2010 min = pos + 1;
2011 else
2012 max = pos - 1;
2014 return min;
2017 static void get_timezone_info( RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi )
2019 static pthread_mutex_t tz_mutex = PTHREAD_MUTEX_INITIALIZER;
2020 static RTL_DYNAMIC_TIME_ZONE_INFORMATION cached_tzi;
2021 static int current_year = -1, current_bias = 65535;
2022 struct tm *tm;
2023 char tz_name[16];
2024 time_t year_start, year_end, tmp, dlt = 0, std = 0;
2025 int is_dst, bias;
2027 mutex_lock( &tz_mutex );
2029 year_start = time(NULL);
2030 tm = gmtime(&year_start);
2031 bias = (LONG)(mktime(tm) - year_start) / 60;
2033 tm = localtime(&year_start);
2034 if (current_year == tm->tm_year && current_bias == bias)
2036 *tzi = cached_tzi;
2037 mutex_unlock( &tz_mutex );
2038 return;
2041 memset(tzi, 0, sizeof(*tzi));
2042 if (!strftime(tz_name, sizeof(tz_name), "%Z", tm)) {
2043 /* not enough room or another error */
2044 tz_name[0] = '\0';
2047 TRACE("tz data will be valid through year %d, bias %d\n", tm->tm_year + 1900, bias);
2048 current_year = tm->tm_year;
2049 current_bias = bias;
2051 tzi->Bias = bias;
2053 tm->tm_isdst = 0;
2054 tm->tm_mday = 1;
2055 tm->tm_mon = tm->tm_hour = tm->tm_min = tm->tm_sec = tm->tm_wday = tm->tm_yday = 0;
2056 year_start = mktime(tm);
2057 TRACE("year_start: %s", ctime(&year_start));
2059 tm->tm_mday = tm->tm_wday = tm->tm_yday = 0;
2060 tm->tm_mon = 12;
2061 tm->tm_hour = 23;
2062 tm->tm_min = tm->tm_sec = 59;
2063 year_end = mktime(tm);
2064 TRACE("year_end: %s", ctime(&year_end));
2066 tmp = find_dst_change(year_start, year_end, &is_dst);
2067 if (is_dst)
2068 dlt = tmp;
2069 else
2070 std = tmp;
2072 tmp = find_dst_change(tmp, year_end, &is_dst);
2073 if (is_dst)
2074 dlt = tmp;
2075 else
2076 std = tmp;
2078 TRACE("std: %s", ctime(&std));
2079 TRACE("dlt: %s", ctime(&dlt));
2081 if (dlt == std || !dlt || !std)
2082 TRACE("there is no daylight saving rules in this time zone\n");
2083 else
2085 tmp = dlt - tzi->Bias * 60;
2086 tm = gmtime(&tmp);
2087 TRACE("dlt gmtime: %s", asctime(tm));
2089 tzi->DaylightBias = -60;
2090 tzi->DaylightDate.wYear = tm->tm_year + 1900;
2091 tzi->DaylightDate.wMonth = tm->tm_mon + 1;
2092 tzi->DaylightDate.wDayOfWeek = tm->tm_wday;
2093 tzi->DaylightDate.wDay = tm->tm_mday;
2094 tzi->DaylightDate.wHour = tm->tm_hour;
2095 tzi->DaylightDate.wMinute = tm->tm_min;
2096 tzi->DaylightDate.wSecond = tm->tm_sec;
2097 tzi->DaylightDate.wMilliseconds = 0;
2099 TRACE("daylight (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
2100 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth,
2101 tzi->DaylightDate.wYear, tzi->DaylightDate.wDayOfWeek,
2102 tzi->DaylightDate.wHour, tzi->DaylightDate.wMinute,
2103 tzi->DaylightDate.wSecond, tzi->DaylightDate.wMilliseconds,
2104 tzi->DaylightBias);
2106 tmp = std - tzi->Bias * 60 - tzi->DaylightBias * 60;
2107 tm = gmtime(&tmp);
2108 TRACE("std gmtime: %s", asctime(tm));
2110 tzi->StandardBias = 0;
2111 tzi->StandardDate.wYear = tm->tm_year + 1900;
2112 tzi->StandardDate.wMonth = tm->tm_mon + 1;
2113 tzi->StandardDate.wDayOfWeek = tm->tm_wday;
2114 tzi->StandardDate.wDay = tm->tm_mday;
2115 tzi->StandardDate.wHour = tm->tm_hour;
2116 tzi->StandardDate.wMinute = tm->tm_min;
2117 tzi->StandardDate.wSecond = tm->tm_sec;
2118 tzi->StandardDate.wMilliseconds = 0;
2120 TRACE("standard (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
2121 tzi->StandardDate.wDay, tzi->StandardDate.wMonth,
2122 tzi->StandardDate.wYear, tzi->StandardDate.wDayOfWeek,
2123 tzi->StandardDate.wHour, tzi->StandardDate.wMinute,
2124 tzi->StandardDate.wSecond, tzi->StandardDate.wMilliseconds,
2125 tzi->StandardBias);
2128 find_reg_tz_info(tzi, tz_name, current_year + 1900);
2129 cached_tzi = *tzi;
2130 mutex_unlock( &tz_mutex );
2134 static void read_dev_urandom( void *buf, ULONG len )
2136 int fd = open( "/dev/urandom", O_RDONLY );
2137 if (fd != -1)
2139 int ret;
2142 ret = read( fd, buf, len );
2144 while (ret == -1 && errno == EINTR);
2145 close( fd );
2147 else WARN( "can't open /dev/urandom\n" );
2150 /******************************************************************************
2151 * NtQuerySystemInformation (NTDLL.@)
2153 NTSTATUS WINAPI NtQuerySystemInformation( SYSTEM_INFORMATION_CLASS class,
2154 void *info, ULONG size, ULONG *ret_size )
2156 NTSTATUS ret = STATUS_SUCCESS;
2157 ULONG len = 0;
2159 TRACE( "(0x%08x,%p,0x%08x,%p)\n", class, info, size, ret_size );
2161 switch (class)
2163 case SystemBasicInformation:
2165 SYSTEM_BASIC_INFORMATION sbi;
2167 virtual_get_system_info( &sbi );
2168 len = sizeof(sbi);
2169 if (size == len)
2171 if (!info) ret = STATUS_ACCESS_VIOLATION;
2172 else memcpy( info, &sbi, len);
2174 else ret = STATUS_INFO_LENGTH_MISMATCH;
2175 break;
2178 case SystemCpuInformation:
2179 if (size >= (len = sizeof(cpu_info)))
2181 if (!info) ret = STATUS_ACCESS_VIOLATION;
2182 else memcpy(info, &cpu_info, len);
2184 else ret = STATUS_INFO_LENGTH_MISMATCH;
2185 break;
2187 case SystemPerformanceInformation:
2189 SYSTEM_PERFORMANCE_INFORMATION spi;
2190 static BOOL fixme_written = FALSE;
2192 get_performance_info( &spi );
2193 len = sizeof(spi);
2194 if (size >= len)
2196 if (!info) ret = STATUS_ACCESS_VIOLATION;
2197 else memcpy( info, &spi, len);
2199 else ret = STATUS_INFO_LENGTH_MISMATCH;
2200 if(!fixme_written) {
2201 FIXME("info_class SYSTEM_PERFORMANCE_INFORMATION\n");
2202 fixme_written = TRUE;
2204 break;
2207 case SystemTimeOfDayInformation:
2209 struct tm *tm;
2210 time_t now;
2211 SYSTEM_TIMEOFDAY_INFORMATION sti = {{{ 0 }}};
2213 sti.BootTime.QuadPart = server_start_time;
2214 now = time( NULL );
2215 tm = gmtime( &now );
2216 sti.TimeZoneBias.QuadPart = mktime( tm ) - now;
2217 tm = localtime( &now );
2218 if (tm->tm_isdst) sti.TimeZoneBias.QuadPart -= 3600;
2219 sti.TimeZoneBias.QuadPart *= TICKSPERSEC;
2220 NtQuerySystemTime( &sti.SystemTime );
2222 if (size <= sizeof(sti))
2224 len = size;
2225 if (!info) ret = STATUS_ACCESS_VIOLATION;
2226 else memcpy( info, &sti, size);
2228 else ret = STATUS_INFO_LENGTH_MISMATCH;
2229 break;
2232 case SystemProcessInformation:
2234 unsigned int process_count, i, j;
2235 char *buffer = NULL;
2236 unsigned int pos = 0;
2238 if (size && !(buffer = malloc( size )))
2240 ret = STATUS_NO_MEMORY;
2241 break;
2244 SERVER_START_REQ( list_processes )
2246 wine_server_set_reply( req, buffer, size );
2247 ret = wine_server_call( req );
2248 len = reply->info_size;
2249 process_count = reply->process_count;
2251 SERVER_END_REQ;
2253 if (ret)
2255 free( buffer );
2256 break;
2259 len = 0;
2261 for (i = 0; i < process_count; i++)
2263 SYSTEM_PROCESS_INFORMATION *nt_process = (SYSTEM_PROCESS_INFORMATION *)((char *)info + len);
2264 const struct process_info *server_process;
2265 const WCHAR *server_name, *file_part;
2266 ULONG proc_len;
2267 ULONG name_len = 0;
2269 pos = (pos + 7) & ~7;
2270 server_process = (const struct process_info *)(buffer + pos);
2271 pos += sizeof(*server_process);
2273 server_name = (const WCHAR *)(buffer + pos);
2274 file_part = server_name + (server_process->name_len / sizeof(WCHAR));
2275 pos += server_process->name_len;
2276 while (file_part > server_name && file_part[-1] != '\\')
2278 file_part--;
2279 name_len++;
2282 proc_len = sizeof(*nt_process) + server_process->thread_count * sizeof(SYSTEM_THREAD_INFORMATION)
2283 + (name_len + 1) * sizeof(WCHAR);
2284 len += proc_len;
2286 if (len <= size)
2288 memset(nt_process, 0, sizeof(*nt_process));
2289 if (i < process_count - 1)
2290 nt_process->NextEntryOffset = proc_len;
2291 nt_process->CreationTime.QuadPart = server_process->start_time;
2292 nt_process->dwThreadCount = server_process->thread_count;
2293 nt_process->dwBasePriority = server_process->priority;
2294 nt_process->UniqueProcessId = UlongToHandle(server_process->pid);
2295 nt_process->ParentProcessId = UlongToHandle(server_process->parent_pid);
2296 nt_process->HandleCount = server_process->handle_count;
2297 get_thread_times( server_process->unix_pid, -1, &nt_process->KernelTime, &nt_process->UserTime );
2298 fill_vm_counters( &nt_process->vmCounters, server_process->unix_pid );
2301 pos = (pos + 7) & ~7;
2302 for (j = 0; j < server_process->thread_count; j++)
2304 const struct thread_info *server_thread = (const struct thread_info *)(buffer + pos);
2306 if (len <= size)
2308 nt_process->ti[j].CreateTime.QuadPart = server_thread->start_time;
2309 nt_process->ti[j].ClientId.UniqueProcess = UlongToHandle(server_process->pid);
2310 nt_process->ti[j].ClientId.UniqueThread = UlongToHandle(server_thread->tid);
2311 nt_process->ti[j].dwCurrentPriority = server_thread->current_priority;
2312 nt_process->ti[j].dwBasePriority = server_thread->base_priority;
2313 get_thread_times( server_process->unix_pid, server_thread->unix_tid,
2314 &nt_process->ti[j].KernelTime, &nt_process->ti[j].UserTime );
2317 pos += sizeof(*server_thread);
2320 if (len <= size)
2322 nt_process->ProcessName.Buffer = (WCHAR *)&nt_process->ti[server_process->thread_count];
2323 nt_process->ProcessName.Length = name_len * sizeof(WCHAR);
2324 nt_process->ProcessName.MaximumLength = (name_len + 1) * sizeof(WCHAR);
2325 memcpy(nt_process->ProcessName.Buffer, file_part, name_len * sizeof(WCHAR));
2326 nt_process->ProcessName.Buffer[name_len] = 0;
2330 if (len > size) ret = STATUS_INFO_LENGTH_MISMATCH;
2331 free( buffer );
2332 break;
2335 case SystemProcessorPerformanceInformation:
2337 SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi = NULL;
2338 unsigned int cpus = 0;
2339 int out_cpus = size / sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION);
2341 if (out_cpus == 0)
2343 len = 0;
2344 ret = STATUS_INFO_LENGTH_MISMATCH;
2345 break;
2347 if (!(sppi = calloc( out_cpus, sizeof(*sppi) )))
2349 ret = STATUS_NO_MEMORY;
2350 break;
2352 else
2353 #ifdef __APPLE__
2355 processor_cpu_load_info_data_t *pinfo;
2356 mach_msg_type_number_t info_count;
2358 if (host_processor_info( mach_host_self (),
2359 PROCESSOR_CPU_LOAD_INFO,
2360 &cpus,
2361 (processor_info_array_t*)&pinfo,
2362 &info_count) == 0)
2364 int i;
2365 cpus = min(cpus,out_cpus);
2366 for (i = 0; i < cpus; i++)
2368 sppi[i].IdleTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_IDLE];
2369 sppi[i].KernelTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_SYSTEM];
2370 sppi[i].UserTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_USER];
2372 vm_deallocate (mach_task_self (), (vm_address_t) pinfo, info_count * sizeof(natural_t));
2375 #else
2377 FILE *cpuinfo = fopen("/proc/stat", "r");
2378 if (cpuinfo)
2380 unsigned long clk_tck = sysconf(_SC_CLK_TCK);
2381 unsigned long usr,nice,sys,idle,remainder[8];
2382 int i, count, id;
2383 char name[32];
2384 char line[255];
2386 /* first line is combined usage */
2387 while (fgets(line,255,cpuinfo))
2389 count = sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2390 name, &usr, &nice, &sys, &idle,
2391 &remainder[0], &remainder[1], &remainder[2], &remainder[3],
2392 &remainder[4], &remainder[5], &remainder[6], &remainder[7]);
2394 if (count < 5 || strncmp( name, "cpu", 3 )) break;
2395 for (i = 0; i + 5 < count; ++i) sys += remainder[i];
2396 sys += idle;
2397 usr += nice;
2398 id = atoi( name + 3 ) + 1;
2399 if (id > out_cpus) break;
2400 if (id > cpus) cpus = id;
2401 sppi[id-1].IdleTime.QuadPart = (ULONGLONG)idle * 10000000 / clk_tck;
2402 sppi[id-1].KernelTime.QuadPart = (ULONGLONG)sys * 10000000 / clk_tck;
2403 sppi[id-1].UserTime.QuadPart = (ULONGLONG)usr * 10000000 / clk_tck;
2405 fclose(cpuinfo);
2408 #endif
2409 if (cpus == 0)
2411 static int i = 1;
2412 unsigned int n;
2413 cpus = min(NtCurrentTeb()->Peb->NumberOfProcessors, out_cpus);
2414 FIXME("stub info_class SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION\n");
2415 /* many programs expect these values to change so fake change */
2416 for (n = 0; n < cpus; n++)
2418 sppi[n].KernelTime.QuadPart = 1 * i;
2419 sppi[n].UserTime.QuadPart = 2 * i;
2420 sppi[n].IdleTime.QuadPart = 3 * i;
2422 i++;
2425 len = sizeof(*sppi) * cpus;
2426 if (size >= len)
2428 if (!info) ret = STATUS_ACCESS_VIOLATION;
2429 else memcpy( info, sppi, len);
2431 else ret = STATUS_INFO_LENGTH_MISMATCH;
2433 free( sppi );
2434 break;
2437 case SystemModuleInformation:
2439 /* FIXME: return some fake info for now */
2440 static const char *fake_modules[] =
2442 "\\SystemRoot\\system32\\ntoskrnl.exe",
2443 "\\SystemRoot\\system32\\hal.dll",
2444 "\\SystemRoot\\system32\\drivers\\mountmgr.sys"
2447 ULONG i;
2448 SYSTEM_MODULE_INFORMATION *smi = info;
2450 len = offsetof( SYSTEM_MODULE_INFORMATION, Modules[ARRAY_SIZE(fake_modules)] );
2451 if (len <= size)
2453 memset( smi, 0, len );
2454 for (i = 0; i < ARRAY_SIZE(fake_modules); i++)
2456 SYSTEM_MODULE *sm = &smi->Modules[i];
2457 sm->ImageBaseAddress = (char *)0x10000000 + 0x200000 * i;
2458 sm->ImageSize = 0x200000;
2459 sm->LoadOrderIndex = i;
2460 sm->LoadCount = 1;
2461 strcpy( (char *)sm->Name, fake_modules[i] );
2462 sm->NameOffset = strrchr( fake_modules[i], '\\' ) - fake_modules[i] + 1;
2464 smi->ModulesCount = i;
2466 else ret = STATUS_INFO_LENGTH_MISMATCH;
2468 break;
2471 case SystemModuleInformationEx:
2473 /* FIXME: return some fake info for now */
2474 static const char *fake_modules[] =
2476 "\\SystemRoot\\system32\\ntoskrnl.exe",
2477 "\\SystemRoot\\system32\\hal.dll",
2478 "\\SystemRoot\\system32\\drivers\\mountmgr.sys"
2481 ULONG i;
2482 RTL_PROCESS_MODULE_INFORMATION_EX *module_info = info;
2484 len = sizeof(*module_info) * ARRAY_SIZE(fake_modules) + sizeof(module_info->NextOffset);
2485 if (len <= size)
2487 memset( info, 0, len );
2488 for (i = 0; i < ARRAY_SIZE(fake_modules); i++)
2490 SYSTEM_MODULE *sm = &module_info[i].BaseInfo;
2491 sm->ImageBaseAddress = (char *)0x10000000 + 0x200000 * i;
2492 sm->ImageSize = 0x200000;
2493 sm->LoadOrderIndex = i;
2494 sm->LoadCount = 1;
2495 strcpy( (char *)sm->Name, fake_modules[i] );
2496 sm->NameOffset = strrchr( fake_modules[i], '\\' ) - fake_modules[i] + 1;
2497 module_info[i].NextOffset = sizeof(*module_info);
2499 module_info[ARRAY_SIZE(fake_modules)].NextOffset = 0;
2501 else ret = STATUS_INFO_LENGTH_MISMATCH;
2503 break;
2506 case SystemHandleInformation:
2508 struct handle_info *handle_info;
2509 DWORD i, num_handles;
2511 if (size < sizeof(SYSTEM_HANDLE_INFORMATION))
2513 ret = STATUS_INFO_LENGTH_MISMATCH;
2514 break;
2517 if (!info)
2519 ret = STATUS_ACCESS_VIOLATION;
2520 break;
2523 num_handles = (size - FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION, Handle )) / sizeof(SYSTEM_HANDLE_ENTRY);
2524 if (!(handle_info = malloc( sizeof(*handle_info) * num_handles ))) return STATUS_NO_MEMORY;
2526 SERVER_START_REQ( get_system_handles )
2528 wine_server_set_reply( req, handle_info, sizeof(*handle_info) * num_handles );
2529 if (!(ret = wine_server_call( req )))
2531 SYSTEM_HANDLE_INFORMATION *shi = info;
2532 shi->Count = wine_server_reply_size( req ) / sizeof(*handle_info);
2533 len = FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION, Handle[shi->Count] );
2534 for (i = 0; i < shi->Count; i++)
2536 memset( &shi->Handle[i], 0, sizeof(shi->Handle[i]) );
2537 shi->Handle[i].OwnerPid = handle_info[i].owner;
2538 shi->Handle[i].HandleValue = handle_info[i].handle;
2539 shi->Handle[i].AccessMask = handle_info[i].access;
2540 shi->Handle[i].HandleFlags = handle_info[i].attributes;
2541 shi->Handle[i].ObjectType = handle_info[i].type;
2542 /* FIXME: Fill out ObjectPointer */
2545 else if (ret == STATUS_BUFFER_TOO_SMALL)
2547 len = FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION, Handle[reply->count] );
2548 ret = STATUS_INFO_LENGTH_MISMATCH;
2551 SERVER_END_REQ;
2553 free( handle_info );
2554 break;
2557 case SystemExtendedHandleInformation:
2559 struct handle_info *handle_info;
2560 DWORD i, num_handles;
2562 if (size < sizeof(SYSTEM_HANDLE_INFORMATION_EX))
2564 ret = STATUS_INFO_LENGTH_MISMATCH;
2565 break;
2568 if (!info)
2570 ret = STATUS_ACCESS_VIOLATION;
2571 break;
2574 num_handles = (size - FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION_EX, Handles ))
2575 / sizeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX);
2576 if (!(handle_info = malloc( sizeof(*handle_info) * num_handles ))) return STATUS_NO_MEMORY;
2578 SERVER_START_REQ( get_system_handles )
2580 wine_server_set_reply( req, handle_info, sizeof(*handle_info) * num_handles );
2581 if (!(ret = wine_server_call( req )))
2583 SYSTEM_HANDLE_INFORMATION_EX *shi = info;
2584 shi->NumberOfHandles = wine_server_reply_size( req ) / sizeof(*handle_info);
2585 len = FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION_EX, Handles[shi->NumberOfHandles] );
2586 for (i = 0; i < shi->NumberOfHandles; i++)
2588 memset( &shi->Handles[i], 0, sizeof(shi->Handles[i]) );
2589 shi->Handles[i].UniqueProcessId = handle_info[i].owner;
2590 shi->Handles[i].HandleValue = handle_info[i].handle;
2591 shi->Handles[i].GrantedAccess = handle_info[i].access;
2592 shi->Handles[i].HandleAttributes = handle_info[i].attributes;
2593 shi->Handles[i].ObjectTypeIndex = handle_info[i].type;
2594 /* FIXME: Fill out Object */
2597 else if (ret == STATUS_BUFFER_TOO_SMALL)
2599 len = FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION_EX, Handles[reply->count] );
2600 ret = STATUS_INFO_LENGTH_MISMATCH;
2603 SERVER_END_REQ;
2605 free( handle_info );
2606 break;
2609 case SystemFileCacheInformation:
2611 SYSTEM_CACHE_INFORMATION sci = { 0 };
2613 len = sizeof(sci);
2614 if (size >= len)
2616 if (!info) ret = STATUS_ACCESS_VIOLATION;
2617 else memcpy( info, &sci, len);
2619 else ret = STATUS_INFO_LENGTH_MISMATCH;
2620 FIXME("info_class SYSTEM_CACHE_INFORMATION\n");
2621 break;
2624 case SystemInterruptInformation:
2626 len = NtCurrentTeb()->Peb->NumberOfProcessors * sizeof(SYSTEM_INTERRUPT_INFORMATION);
2627 if (size >= len)
2629 if (!info) ret = STATUS_ACCESS_VIOLATION;
2630 else
2632 #ifdef HAVE_GETRANDOM
2633 int ret;
2636 ret = getrandom( info, len, 0 );
2638 while (ret == -1 && errno == EINTR);
2640 if (ret == -1 && errno == ENOSYS) read_dev_urandom( info, len );
2641 #else
2642 read_dev_urandom( info, len );
2643 #endif
2646 else ret = STATUS_INFO_LENGTH_MISMATCH;
2647 break;
2650 case SystemTimeAdjustmentInformation:
2652 SYSTEM_TIME_ADJUSTMENT_QUERY query = { 156250, 156250, TRUE };
2654 len = sizeof(query);
2655 if (size == len)
2657 if (!info) ret = STATUS_ACCESS_VIOLATION;
2658 else memcpy( info, &query, len );
2660 else ret = STATUS_INFO_LENGTH_MISMATCH;
2661 break;
2664 case SystemKernelDebuggerInformation:
2666 SYSTEM_KERNEL_DEBUGGER_INFORMATION skdi;
2668 skdi.DebuggerEnabled = FALSE;
2669 skdi.DebuggerNotPresent = TRUE;
2670 len = sizeof(skdi);
2671 if (size >= len)
2673 if (!info) ret = STATUS_ACCESS_VIOLATION;
2674 else memcpy( info, &skdi, len);
2676 else ret = STATUS_INFO_LENGTH_MISMATCH;
2677 break;
2680 case SystemRegistryQuotaInformation:
2682 /* Something to do with the size of the registry *
2683 * Since we don't have a size limitation, fake it *
2684 * This is almost certainly wrong. *
2685 * This sets each of the three words in the struct to 32 MB, *
2686 * which is enough to make the IE 5 installer happy. */
2687 SYSTEM_REGISTRY_QUOTA_INFORMATION srqi;
2689 srqi.RegistryQuotaAllowed = 0x2000000;
2690 srqi.RegistryQuotaUsed = 0x200000;
2691 srqi.Reserved1 = (void*)0x200000;
2692 len = sizeof(srqi);
2694 if (size >= len)
2696 if (!info) ret = STATUS_ACCESS_VIOLATION;
2697 else
2699 FIXME("SystemRegistryQuotaInformation: faking max registry size of 32 MB\n");
2700 memcpy( info, &srqi, len);
2703 else ret = STATUS_INFO_LENGTH_MISMATCH;
2704 break;
2707 case SystemCurrentTimeZoneInformation:
2709 RTL_DYNAMIC_TIME_ZONE_INFORMATION tz;
2711 get_timezone_info( &tz );
2712 len = sizeof(RTL_TIME_ZONE_INFORMATION);
2713 if (size >= len)
2715 if (!info) ret = STATUS_ACCESS_VIOLATION;
2716 else memcpy( info, &tz, len);
2718 else ret = STATUS_INFO_LENGTH_MISMATCH;
2719 break;
2722 case SystemLogicalProcessorInformation:
2724 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *buf;
2726 /* Each logical processor may use up to 7 entries in returned table:
2727 * core, numa node, package, L1i, L1d, L2, L3 */
2728 len = 7 * NtCurrentTeb()->Peb->NumberOfProcessors;
2729 buf = malloc( len * sizeof(*buf) );
2730 if (!buf)
2732 ret = STATUS_NO_MEMORY;
2733 break;
2735 ret = create_logical_proc_info(&buf, NULL, &len, RelationAll);
2736 if (!ret)
2738 if (size >= len)
2740 if (!info) ret = STATUS_ACCESS_VIOLATION;
2741 else memcpy( info, buf, len);
2743 else ret = STATUS_INFO_LENGTH_MISMATCH;
2745 free( buf );
2746 break;
2749 case SystemCpuSetInformation:
2750 return NtQuerySystemInformationEx(class, NULL, 0, info, size, ret_size);
2752 case SystemRecommendedSharedDataAlignment:
2754 len = sizeof(DWORD);
2755 if (size >= len)
2757 if (!info) ret = STATUS_ACCESS_VIOLATION;
2758 else
2760 #ifdef __arm__
2761 *((DWORD *)info) = 32;
2762 #else
2763 *((DWORD *)info) = 64;
2764 #endif
2767 else ret = STATUS_INFO_LENGTH_MISMATCH;
2768 break;
2771 case SystemFirmwareTableInformation:
2773 SYSTEM_FIRMWARE_TABLE_INFORMATION *sfti = info;
2774 len = FIELD_OFFSET(SYSTEM_FIRMWARE_TABLE_INFORMATION, TableBuffer);
2775 if (size < len)
2777 ret = STATUS_INFO_LENGTH_MISMATCH;
2778 break;
2781 switch (sfti->Action)
2783 case SystemFirmwareTable_Get:
2784 ret = get_firmware_info(sfti, size, &len);
2785 break;
2786 default:
2787 len = 0;
2788 ret = STATUS_NOT_IMPLEMENTED;
2789 FIXME("info_class SYSTEM_FIRMWARE_TABLE_INFORMATION action %d\n", sfti->Action);
2791 break;
2794 case SystemDynamicTimeZoneInformation:
2796 RTL_DYNAMIC_TIME_ZONE_INFORMATION tz;
2798 get_timezone_info( &tz );
2799 len = sizeof(tz);
2800 if (size >= len)
2802 if (!info) ret = STATUS_ACCESS_VIOLATION;
2803 else memcpy( info, &tz, len);
2805 else ret = STATUS_INFO_LENGTH_MISMATCH;
2806 break;
2809 case SystemExtendedProcessInformation:
2810 FIXME("SystemExtendedProcessInformation, size %u, info %p, stub!\n", size, info);
2811 memset( info, 0, size );
2812 ret = STATUS_SUCCESS;
2813 break;
2815 /* Wine extensions */
2817 case SystemWineVersionInformation:
2819 static const char version[] = PACKAGE_VERSION;
2820 extern const char wine_build[];
2821 struct utsname buf;
2823 uname( &buf );
2824 len = strlen(version) + strlen(wine_build) + strlen(buf.sysname) + strlen(buf.release) + 4;
2825 snprintf( info, size, "%s%c%s%c%s%c%s", version, 0, wine_build, 0, buf.sysname, 0, buf.release );
2826 if (size < len) ret = STATUS_INFO_LENGTH_MISMATCH;
2827 break;
2830 case SystemCodeIntegrityInformation:
2832 SYSTEM_CODEINTEGRITY_INFORMATION *integrity_info = info;
2834 FIXME("SystemCodeIntegrityInformation, size %u, info %p, stub!\n", size, info);
2836 len = sizeof(SYSTEM_CODEINTEGRITY_INFORMATION);
2838 if (size < len)
2839 integrity_info->CodeIntegrityOptions = CODEINTEGRITY_OPTION_ENABLED;
2840 else
2841 ret = STATUS_INFO_LENGTH_MISMATCH;
2842 break;
2845 default:
2846 FIXME( "(0x%08x,%p,0x%08x,%p) stub\n", class, info, size, ret_size );
2848 /* Several Information Classes are not implemented on Windows and return 2 different values
2849 * STATUS_NOT_IMPLEMENTED or STATUS_INVALID_INFO_CLASS
2850 * in 95% of the cases it's STATUS_INVALID_INFO_CLASS, so use this as the default
2852 ret = STATUS_INVALID_INFO_CLASS;
2855 if (ret_size) *ret_size = len;
2856 return ret;
2860 /******************************************************************************
2861 * NtQuerySystemInformationEx (NTDLL.@)
2863 NTSTATUS WINAPI NtQuerySystemInformationEx( SYSTEM_INFORMATION_CLASS class,
2864 void *query, ULONG query_len,
2865 void *info, ULONG size, ULONG *ret_size )
2867 ULONG len = 0;
2868 NTSTATUS ret = STATUS_NOT_IMPLEMENTED;
2870 TRACE( "(0x%08x,%p,%u,%p,%u,%p) stub\n", class, query, query_len, info, size, ret_size );
2872 switch (class)
2874 case SystemLogicalProcessorInformationEx:
2876 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buf;
2878 if (!query || query_len < sizeof(DWORD))
2880 ret = STATUS_INVALID_PARAMETER;
2881 break;
2884 len = 3 * sizeof(*buf);
2885 if (!(buf = malloc( len )))
2887 ret = STATUS_NO_MEMORY;
2888 break;
2890 ret = create_logical_proc_info(NULL, &buf, &len, *(DWORD *)query);
2891 if (!ret)
2893 if (size >= len)
2895 if (!info) ret = STATUS_ACCESS_VIOLATION;
2896 else memcpy(info, buf, len);
2898 else ret = STATUS_INFO_LENGTH_MISMATCH;
2900 free( buf );
2901 break;
2904 case SystemCpuSetInformation:
2906 unsigned int cpu_count = NtCurrentTeb()->Peb->NumberOfProcessors;
2907 PROCESS_BASIC_INFORMATION pbi;
2908 HANDLE process;
2910 if (!query || query_len < sizeof(HANDLE))
2911 return STATUS_INVALID_PARAMETER;
2913 process = *(HANDLE *)query;
2914 if (process && (ret = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL)))
2915 return ret;
2917 if (size < (len = cpu_count * sizeof(SYSTEM_CPU_SET_INFORMATION)))
2919 ret = STATUS_BUFFER_TOO_SMALL;
2920 break;
2922 if (!info)
2923 return STATUS_ACCESS_VIOLATION;
2925 if ((ret = create_cpuset_info(info)))
2926 return ret;
2927 break;
2929 default:
2930 FIXME( "(0x%08x,%p,%u,%p,%u,%p) stub\n", class, query, query_len, info, size, ret_size );
2931 break;
2933 if (ret_size) *ret_size = len;
2934 return ret;
2938 /******************************************************************************
2939 * NtSetSystemInformation (NTDLL.@)
2941 NTSTATUS WINAPI NtSetSystemInformation( SYSTEM_INFORMATION_CLASS class, void *info, ULONG length )
2943 FIXME( "(0x%08x,%p,0x%08x) stub\n", class, info, length );
2944 return STATUS_SUCCESS;
2948 /******************************************************************************
2949 * NtQuerySystemEnvironmentValue (NTDLL.@)
2951 NTSTATUS WINAPI NtQuerySystemEnvironmentValue( UNICODE_STRING *name, WCHAR *buffer, ULONG length,
2952 ULONG *retlen )
2954 FIXME( "(%s, %p, %u, %p), stub\n", debugstr_us(name), buffer, length, retlen );
2955 return STATUS_NOT_IMPLEMENTED;
2959 /******************************************************************************
2960 * NtQuerySystemEnvironmentValueEx (NTDLL.@)
2962 NTSTATUS WINAPI NtQuerySystemEnvironmentValueEx( UNICODE_STRING *name, GUID *vendor, void *buffer,
2963 ULONG *retlen, ULONG *attrib )
2965 FIXME( "(%s, %s, %p, %p, %p), stub\n", debugstr_us(name),
2966 debugstr_guid(vendor), buffer, retlen, attrib );
2967 return STATUS_NOT_IMPLEMENTED;
2971 /******************************************************************************
2972 * NtSystemDebugControl (NTDLL.@)
2974 NTSTATUS WINAPI NtSystemDebugControl( SYSDBG_COMMAND command, void *in_buff, ULONG in_len,
2975 void *out_buff, ULONG out_len, ULONG *retlen )
2977 FIXME( "(%d, %p, %d, %p, %d, %p), stub\n", command, in_buff, in_len, out_buff, out_len, retlen );
2978 return STATUS_NOT_IMPLEMENTED;
2982 /******************************************************************************
2983 * NtShutdownSystem (NTDLL.@)
2985 NTSTATUS WINAPI NtShutdownSystem( SHUTDOWN_ACTION action )
2987 FIXME( "%d\n", action );
2988 return STATUS_SUCCESS;
2992 #ifdef linux
2994 /* Fallback using /proc/cpuinfo for Linux systems without cpufreq. For
2995 * most distributions on recent enough hardware, this is only likely to
2996 * happen while running in virtualized environments such as QEMU. */
2997 static ULONG mhz_from_cpuinfo(void)
2999 char line[512];
3000 char *s, *value;
3001 double cmz = 0;
3002 FILE *f = fopen("/proc/cpuinfo", "r");
3003 if(f)
3005 while (fgets(line, sizeof(line), f) != NULL)
3007 if (!(value = strchr(line,':'))) continue;
3008 s = value - 1;
3009 while ((s >= line) && (*s == ' ' || *s == '\t')) s--;
3010 s[1] = 0;
3011 value++;
3012 if (!strcmp( line, "cpu MHz" ))
3014 sscanf(value, " %lf", &cmz);
3015 break;
3018 fclose( f );
3020 return cmz;
3023 static const char * get_sys_str(const char *path, char *s)
3025 FILE *f = fopen(path, "r");
3026 const char *ret = NULL;
3028 if (f)
3030 if (fgets(s, 16, f)) ret = s;
3031 fclose(f);
3033 return ret;
3036 static int get_sys_int(const char *path, int def)
3038 char s[16];
3039 return get_sys_str(path, s) ? atoi(s) : def;
3042 static NTSTATUS fill_battery_state( SYSTEM_BATTERY_STATE *bs )
3044 char s[16], path[64];
3045 unsigned int i = 0;
3046 LONG64 voltage; /* microvolts */
3048 bs->AcOnLine = get_sys_int("/sys/class/power_supply/AC/online", 1);
3050 for (;;)
3052 sprintf(path, "/sys/class/power_supply/BAT%u/status", i);
3053 if (!get_sys_str(path, s)) break;
3054 bs->Charging |= (strcmp(s, "Charging\n") == 0);
3055 bs->Discharging |= (strcmp(s, "Discharging\n") == 0);
3056 bs->BatteryPresent = TRUE;
3057 i++;
3060 if (bs->BatteryPresent)
3062 voltage = get_sys_int("/sys/class/power_supply/BAT0/voltage_now", 0);
3063 bs->MaxCapacity = get_sys_int("/sys/class/power_supply/BAT0/charge_full", 0) * voltage / 1e9;
3064 bs->RemainingCapacity = get_sys_int("/sys/class/power_supply/BAT0/charge_now", 0) * voltage / 1e9;
3065 bs->Rate = -get_sys_int("/sys/class/power_supply/BAT0/current_now", 0) * voltage / 1e9;
3066 if (!bs->Charging && (LONG)bs->Rate < 0)
3067 bs->EstimatedTime = 3600 * bs->RemainingCapacity / -(LONG)bs->Rate;
3068 else
3069 bs->EstimatedTime = ~0u;
3072 return STATUS_SUCCESS;
3075 #elif defined(HAVE_IOKIT_IOKITLIB_H)
3077 static NTSTATUS fill_battery_state( SYSTEM_BATTERY_STATE *bs )
3079 CFArrayRef batteries;
3080 CFDictionaryRef battery;
3081 CFNumberRef prop;
3082 uint32_t value, voltage;
3083 CFTimeInterval remain;
3085 if (IOPMCopyBatteryInfo( kIOMasterPortDefault, &batteries ) != kIOReturnSuccess)
3086 return STATUS_ACCESS_DENIED;
3088 if (CFArrayGetCount( batteries ) == 0)
3090 /* Just assume we're on AC with no battery. */
3091 bs->AcOnLine = TRUE;
3092 return STATUS_SUCCESS;
3094 /* Just use the first battery. */
3095 battery = CFArrayGetValueAtIndex( batteries, 0 );
3097 prop = CFDictionaryGetValue( battery, CFSTR(kIOBatteryFlagsKey) );
3098 CFNumberGetValue( prop, kCFNumberSInt32Type, &value );
3100 if (value & kIOBatteryInstalled)
3101 bs->BatteryPresent = TRUE;
3102 else
3103 /* Since we are executing code, we must have AC power. */
3104 bs->AcOnLine = TRUE;
3105 if (value & kIOBatteryChargerConnect)
3107 bs->AcOnLine = TRUE;
3108 if (value & kIOBatteryCharge)
3109 bs->Charging = TRUE;
3111 else
3112 bs->Discharging = TRUE;
3114 /* We'll need the voltage to be able to interpret the other values. */
3115 prop = CFDictionaryGetValue( battery, CFSTR(kIOBatteryVoltageKey) );
3116 CFNumberGetValue( prop, kCFNumberSInt32Type, &voltage );
3118 prop = CFDictionaryGetValue( battery, CFSTR(kIOBatteryCapacityKey) );
3119 CFNumberGetValue( prop, kCFNumberSInt32Type, &value );
3120 bs->MaxCapacity = value * voltage;
3121 /* Apple uses "estimated time < 10:00" and "22%" for these, but we'll follow
3122 * Windows for now (5% and 33%). */
3123 bs->DefaultAlert1 = bs->MaxCapacity / 20;
3124 bs->DefaultAlert2 = bs->MaxCapacity / 3;
3126 prop = CFDictionaryGetValue( battery, CFSTR(kIOBatteryCurrentChargeKey) );
3127 CFNumberGetValue( prop, kCFNumberSInt32Type, &value );
3128 bs->RemainingCapacity = value * voltage;
3130 prop = CFDictionaryGetValue( battery, CFSTR(kIOBatteryAmperageKey) );
3131 CFNumberGetValue( prop, kCFNumberSInt32Type, &value );
3132 bs->Rate = value * voltage;
3134 remain = IOPSGetTimeRemainingEstimate();
3135 if (remain != kIOPSTimeRemainingUnknown && remain != kIOPSTimeRemainingUnlimited)
3136 bs->EstimatedTime = (ULONG)remain;
3138 CFRelease( batteries );
3139 return STATUS_SUCCESS;
3142 #else
3144 static NTSTATUS fill_battery_state( SYSTEM_BATTERY_STATE *bs )
3146 FIXME("SystemBatteryState not implemented on this platform\n");
3147 return STATUS_NOT_IMPLEMENTED;
3150 #endif
3152 /******************************************************************************
3153 * NtPowerInformation (NTDLL.@)
3155 NTSTATUS WINAPI NtPowerInformation( POWER_INFORMATION_LEVEL level, void *input, ULONG in_size,
3156 void *output, ULONG out_size )
3158 TRACE( "(%d,%p,%d,%p,%d)\n", level, input, in_size, output, out_size );
3159 switch (level)
3161 case SystemPowerCapabilities:
3163 PSYSTEM_POWER_CAPABILITIES PowerCaps = output;
3164 FIXME("semi-stub: SystemPowerCapabilities\n");
3165 if (out_size < sizeof(SYSTEM_POWER_CAPABILITIES)) return STATUS_BUFFER_TOO_SMALL;
3166 /* FIXME: These values are based off a native XP desktop, should probably use APM/ACPI to get the 'real' values */
3167 PowerCaps->PowerButtonPresent = TRUE;
3168 PowerCaps->SleepButtonPresent = FALSE;
3169 PowerCaps->LidPresent = FALSE;
3170 PowerCaps->SystemS1 = TRUE;
3171 PowerCaps->SystemS2 = FALSE;
3172 PowerCaps->SystemS3 = FALSE;
3173 PowerCaps->SystemS4 = TRUE;
3174 PowerCaps->SystemS5 = TRUE;
3175 PowerCaps->HiberFilePresent = TRUE;
3176 PowerCaps->FullWake = TRUE;
3177 PowerCaps->VideoDimPresent = FALSE;
3178 PowerCaps->ApmPresent = FALSE;
3179 PowerCaps->UpsPresent = FALSE;
3180 PowerCaps->ThermalControl = FALSE;
3181 PowerCaps->ProcessorThrottle = FALSE;
3182 PowerCaps->ProcessorMinThrottle = 100;
3183 PowerCaps->ProcessorMaxThrottle = 100;
3184 PowerCaps->DiskSpinDown = TRUE;
3185 PowerCaps->SystemBatteriesPresent = FALSE;
3186 PowerCaps->BatteriesAreShortTerm = FALSE;
3187 PowerCaps->BatteryScale[0].Granularity = 0;
3188 PowerCaps->BatteryScale[0].Capacity = 0;
3189 PowerCaps->BatteryScale[1].Granularity = 0;
3190 PowerCaps->BatteryScale[1].Capacity = 0;
3191 PowerCaps->BatteryScale[2].Granularity = 0;
3192 PowerCaps->BatteryScale[2].Capacity = 0;
3193 PowerCaps->AcOnLineWake = PowerSystemUnspecified;
3194 PowerCaps->SoftLidWake = PowerSystemUnspecified;
3195 PowerCaps->RtcWake = PowerSystemSleeping1;
3196 PowerCaps->MinDeviceWakeState = PowerSystemUnspecified;
3197 PowerCaps->DefaultLowLatencyWake = PowerSystemUnspecified;
3198 return STATUS_SUCCESS;
3201 case SystemBatteryState:
3203 if (out_size < sizeof(SYSTEM_BATTERY_STATE)) return STATUS_BUFFER_TOO_SMALL;
3204 memset(output, 0, sizeof(SYSTEM_BATTERY_STATE));
3205 return fill_battery_state(output);
3208 case SystemExecutionState:
3210 ULONG *state = output;
3211 WARN("semi-stub: SystemExecutionState\n"); /* Needed for .NET Framework, but using a FIXME is really noisy. */
3212 if (input != NULL) return STATUS_INVALID_PARAMETER;
3213 /* FIXME: The actual state should be the value set by SetThreadExecutionState which is not currently implemented. */
3214 *state = ES_USER_PRESENT;
3215 return STATUS_SUCCESS;
3218 case ProcessorInformation:
3220 const int cannedMHz = 1000; /* We fake a 1GHz processor if we can't conjure up real values */
3221 PROCESSOR_POWER_INFORMATION* cpu_power = output;
3222 int i, out_cpus;
3224 if ((output == NULL) || (out_size == 0)) return STATUS_INVALID_PARAMETER;
3225 out_cpus = NtCurrentTeb()->Peb->NumberOfProcessors;
3226 if ((out_size / sizeof(PROCESSOR_POWER_INFORMATION)) < out_cpus) return STATUS_BUFFER_TOO_SMALL;
3227 #if defined(linux)
3229 char filename[128];
3230 FILE* f;
3232 for(i = 0; i < out_cpus; i++) {
3233 sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i);
3234 f = fopen(filename, "r");
3235 if (f && (fscanf(f, "%d", &cpu_power[i].MaxMhz) == 1)) {
3236 cpu_power[i].MaxMhz /= 1000;
3237 fclose(f);
3238 cpu_power[i].CurrentMhz = cpu_power[i].MaxMhz;
3240 else {
3241 if(i == 0) {
3242 cpu_power[0].CurrentMhz = mhz_from_cpuinfo();
3243 if(cpu_power[0].CurrentMhz == 0)
3244 cpu_power[0].CurrentMhz = cannedMHz;
3246 else
3247 cpu_power[i].CurrentMhz = cpu_power[0].CurrentMhz;
3248 cpu_power[i].MaxMhz = cpu_power[i].CurrentMhz;
3249 if(f) fclose(f);
3252 sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq", i);
3253 f = fopen(filename, "r");
3254 if(f && (fscanf(f, "%d", &cpu_power[i].MhzLimit) == 1)) {
3255 cpu_power[i].MhzLimit /= 1000;
3256 fclose(f);
3258 else
3260 cpu_power[i].MhzLimit = cpu_power[i].MaxMhz;
3261 if(f) fclose(f);
3264 cpu_power[i].Number = i;
3265 cpu_power[i].MaxIdleState = 0; /* FIXME */
3266 cpu_power[i].CurrentIdleState = 0; /* FIXME */
3269 #elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__DragonFly__)
3271 int num;
3272 size_t valSize = sizeof(num);
3273 if (sysctlbyname("hw.clockrate", &num, &valSize, NULL, 0))
3274 num = cannedMHz;
3275 for(i = 0; i < out_cpus; i++) {
3276 cpu_power[i].CurrentMhz = num;
3277 cpu_power[i].MaxMhz = num;
3278 cpu_power[i].MhzLimit = num;
3279 cpu_power[i].Number = i;
3280 cpu_power[i].MaxIdleState = 0; /* FIXME */
3281 cpu_power[i].CurrentIdleState = 0; /* FIXME */
3284 #elif defined (__APPLE__)
3286 size_t valSize;
3287 unsigned long long currentMhz;
3288 unsigned long long maxMhz;
3290 valSize = sizeof(currentMhz);
3291 if (!sysctlbyname("hw.cpufrequency", &currentMhz, &valSize, NULL, 0))
3292 currentMhz /= 1000000;
3293 else
3294 currentMhz = cannedMHz;
3296 valSize = sizeof(maxMhz);
3297 if (!sysctlbyname("hw.cpufrequency_max", &maxMhz, &valSize, NULL, 0))
3298 maxMhz /= 1000000;
3299 else
3300 maxMhz = currentMhz;
3302 for(i = 0; i < out_cpus; i++) {
3303 cpu_power[i].CurrentMhz = currentMhz;
3304 cpu_power[i].MaxMhz = maxMhz;
3305 cpu_power[i].MhzLimit = maxMhz;
3306 cpu_power[i].Number = i;
3307 cpu_power[i].MaxIdleState = 0; /* FIXME */
3308 cpu_power[i].CurrentIdleState = 0; /* FIXME */
3311 #else
3312 for(i = 0; i < out_cpus; i++) {
3313 cpu_power[i].CurrentMhz = cannedMHz;
3314 cpu_power[i].MaxMhz = cannedMHz;
3315 cpu_power[i].MhzLimit = cannedMHz;
3316 cpu_power[i].Number = i;
3317 cpu_power[i].MaxIdleState = 0; /* FIXME */
3318 cpu_power[i].CurrentIdleState = 0; /* FIXME */
3320 WARN("Unable to detect CPU MHz for this platform. Reporting %d MHz.\n", cannedMHz);
3321 #endif
3322 for(i = 0; i < out_cpus; i++) {
3323 TRACE("cpu_power[%d] = %u %u %u %u %u %u\n", i, cpu_power[i].Number,
3324 cpu_power[i].MaxMhz, cpu_power[i].CurrentMhz, cpu_power[i].MhzLimit,
3325 cpu_power[i].MaxIdleState, cpu_power[i].CurrentIdleState);
3327 return STATUS_SUCCESS;
3330 default:
3331 /* FIXME: Needed by .NET Framework */
3332 WARN( "Unimplemented NtPowerInformation action: %d\n", level );
3333 return STATUS_NOT_IMPLEMENTED;
3338 /******************************************************************************
3339 * NtLoadDriver (NTDLL.@)
3341 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *name )
3343 FIXME( "(%s), stub!\n", debugstr_us(name) );
3344 return STATUS_NOT_IMPLEMENTED;
3348 /******************************************************************************
3349 * NtUnloadDriver (NTDLL.@)
3351 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *name )
3353 FIXME( "(%s), stub!\n", debugstr_us(name) );
3354 return STATUS_NOT_IMPLEMENTED;
3358 /******************************************************************************
3359 * NtDisplayString (NTDLL.@)
3361 NTSTATUS WINAPI NtDisplayString( UNICODE_STRING *string )
3363 ERR( "%s\n", debugstr_us(string) );
3364 return STATUS_SUCCESS;
3368 /******************************************************************************
3369 * NtRaiseHardError (NTDLL.@)
3371 NTSTATUS WINAPI NtRaiseHardError( NTSTATUS status, ULONG count,
3372 UNICODE_STRING *params_mask, void **params,
3373 HARDERROR_RESPONSE_OPTION option, HARDERROR_RESPONSE *response )
3375 FIXME( "%08x stub\n", status );
3376 return STATUS_NOT_IMPLEMENTED;
3380 /******************************************************************************
3381 * NtInitiatePowerAction (NTDLL.@)
3383 NTSTATUS WINAPI NtInitiatePowerAction( POWER_ACTION action, SYSTEM_POWER_STATE state,
3384 ULONG flags, BOOLEAN async )
3386 FIXME( "(%d,%d,0x%08x,%d),stub\n", action, state, flags, async );
3387 return STATUS_NOT_IMPLEMENTED;
3391 /******************************************************************************
3392 * NtCreatePowerRequest (NTDLL.@)
3394 NTSTATUS WINAPI NtCreatePowerRequest( HANDLE *handle, COUNTED_REASON_CONTEXT *context )
3396 FIXME( "(%p, %p): stub\n", handle, context );
3397 return STATUS_NOT_IMPLEMENTED;
3401 /******************************************************************************
3402 * NtSetPowerRequest (NTDLL.@)
3404 NTSTATUS WINAPI NtSetPowerRequest( HANDLE handle, POWER_REQUEST_TYPE type )
3406 FIXME( "(%p, %u): stub\n", handle, type );
3407 return STATUS_NOT_IMPLEMENTED;
3411 /******************************************************************************
3412 * NtClearPowerRequest (NTDLL.@)
3414 NTSTATUS WINAPI NtClearPowerRequest( HANDLE handle, POWER_REQUEST_TYPE type )
3416 FIXME( "(%p, %u): stub\n", handle, type );
3417 return STATUS_NOT_IMPLEMENTED;
3421 /******************************************************************************
3422 * NtSetThreadExecutionState (NTDLL.@)
3424 NTSTATUS WINAPI NtSetThreadExecutionState( EXECUTION_STATE new_state, EXECUTION_STATE *old_state )
3426 static EXECUTION_STATE current = ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED | ES_USER_PRESENT;
3428 WARN( "(0x%x, %p): stub, harmless.\n", new_state, old_state );
3429 *old_state = current;
3430 if (!(current & ES_CONTINUOUS) || (new_state & ES_CONTINUOUS)) current = new_state;
3431 return STATUS_SUCCESS;