ntdll: Fill the VM counters in NtQuerySystemInformation(SystemProcessInformation).
[wine.git] / dlls / ntdll / unix / system.c
blob33fb37ec33d046d204ade8e041b617fafc582bb5
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 #ifdef HAVE_SYS_TIME_H
33 # include <sys/time.h>
34 #endif
35 #include <time.h>
36 #ifdef HAVE_SYS_PARAM_H
37 # include <sys/param.h>
38 #endif
39 #ifdef HAVE_SYS_SYSCTL_H
40 # include <sys/sysctl.h>
41 #endif
42 #ifdef HAVE_MACHINE_CPU_H
43 # include <machine/cpu.h>
44 #endif
45 #ifdef HAVE_IOKIT_IOKITLIB_H
46 # include <CoreFoundation/CoreFoundation.h>
47 # include <IOKit/IOKitLib.h>
48 # include <IOKit/pwr_mgt/IOPM.h>
49 # include <IOKit/pwr_mgt/IOPMLib.h>
50 # include <IOKit/ps/IOPowerSources.h>
51 #endif
52 #ifdef __APPLE__
53 # include <mach/mach.h>
54 # include <mach/machine.h>
55 # include <mach/mach_init.h>
56 # include <mach/mach_host.h>
57 # include <mach/vm_map.h>
58 #endif
60 #define NONAMELESSUNION
61 #include "ntstatus.h"
62 #define WIN32_NO_STATUS
63 #include "windef.h"
64 #include "winternl.h"
65 #include "ddk/wdm.h"
66 #include "wine/asm.h"
67 #include "unix_private.h"
68 #include "wine/debug.h"
70 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
72 #include "pshpack1.h"
74 struct smbios_prologue
76 BYTE calling_method;
77 BYTE major_version;
78 BYTE minor_version;
79 BYTE revision;
80 DWORD length;
83 struct smbios_header
85 BYTE type;
86 BYTE length;
87 WORD handle;
90 struct smbios_bios
92 struct smbios_header hdr;
93 BYTE vendor;
94 BYTE version;
95 WORD start;
96 BYTE date;
97 BYTE size;
98 UINT64 characteristics;
99 BYTE characteristics_ext[2];
100 BYTE system_bios_major_release;
101 BYTE system_bios_minor_release;
102 BYTE ec_firmware_major_release;
103 BYTE ec_firmware_minor_release;
106 struct smbios_system
108 struct smbios_header hdr;
109 BYTE vendor;
110 BYTE product;
111 BYTE version;
112 BYTE serial;
113 BYTE uuid[16];
114 BYTE wake_up_type;
115 BYTE sku_number;
116 BYTE family;
119 struct smbios_board
121 struct smbios_header hdr;
122 BYTE vendor;
123 BYTE product;
124 BYTE version;
125 BYTE serial;
128 struct smbios_chassis
130 struct smbios_header hdr;
131 BYTE vendor;
132 BYTE type;
133 BYTE version;
134 BYTE serial;
135 BYTE asset_tag;
136 BYTE boot_state;
137 BYTE power_supply_state;
138 BYTE thermal_state;
139 BYTE security_status;
142 #include "poppack.h"
144 /* Firmware table providers */
145 #define ACPI 0x41435049
146 #define FIRM 0x4649524D
147 #define RSMB 0x52534D42
149 static SYSTEM_CPU_INFORMATION cpu_info;
151 /*******************************************************************************
152 * Architecture specific feature detection for CPUs
154 * This a set of mutually exclusive #if define()s each providing its own get_cpuinfo() to be called
155 * from init_cpu_info();
157 #if defined(__i386__) || defined(__x86_64__)
159 #define AUTH 0x68747541 /* "Auth" */
160 #define ENTI 0x69746e65 /* "enti" */
161 #define CAMD 0x444d4163 /* "cAMD" */
163 #define GENU 0x756e6547 /* "Genu" */
164 #define INEI 0x49656e69 /* "ineI" */
165 #define NTEL 0x6c65746e /* "ntel" */
167 extern void do_cpuid(unsigned int ax, unsigned int *p);
169 #ifdef __i386__
170 __ASM_GLOBAL_FUNC( do_cpuid,
171 "pushl %esi\n\t"
172 "pushl %ebx\n\t"
173 "movl 12(%esp),%eax\n\t"
174 "movl 16(%esp),%esi\n\t"
175 "cpuid\n\t"
176 "movl %eax,(%esi)\n\t"
177 "movl %ebx,4(%esi)\n\t"
178 "movl %ecx,8(%esi)\n\t"
179 "movl %edx,12(%esi)\n\t"
180 "popl %ebx\n\t"
181 "popl %esi\n\t"
182 "ret" )
183 #else
184 __ASM_GLOBAL_FUNC( do_cpuid,
185 "pushq %rbx\n\t"
186 "movl %edi,%eax\n\t"
187 "cpuid\n\t"
188 "movl %eax,(%rsi)\n\t"
189 "movl %ebx,4(%rsi)\n\t"
190 "movl %ecx,8(%rsi)\n\t"
191 "movl %edx,12(%rsi)\n\t"
192 "popq %rbx\n\t"
193 "ret" )
194 #endif
196 #ifdef __i386__
197 extern int have_cpuid(void);
198 __ASM_GLOBAL_FUNC( have_cpuid,
199 "pushfl\n\t"
200 "pushfl\n\t"
201 "movl (%esp),%ecx\n\t"
202 "xorl $0x00200000,(%esp)\n\t"
203 "popfl\n\t"
204 "pushfl\n\t"
205 "popl %eax\n\t"
206 "popfl\n\t"
207 "xorl %ecx,%eax\n\t"
208 "andl $0x00200000,%eax\n\t"
209 "ret" )
210 #else
211 static int have_cpuid(void)
213 return 1;
215 #endif
217 /* Detect if a SSE2 processor is capable of Denormals Are Zero (DAZ) mode.
219 * This function assumes you have already checked for SSE2/FXSAVE support. */
220 static inline BOOL have_sse_daz_mode(void)
222 #ifdef __i386__
223 typedef struct DECLSPEC_ALIGN(16) _M128A {
224 ULONGLONG Low;
225 LONGLONG High;
226 } M128A;
228 typedef struct _XMM_SAVE_AREA32 {
229 WORD ControlWord;
230 WORD StatusWord;
231 BYTE TagWord;
232 BYTE Reserved1;
233 WORD ErrorOpcode;
234 DWORD ErrorOffset;
235 WORD ErrorSelector;
236 WORD Reserved2;
237 DWORD DataOffset;
238 WORD DataSelector;
239 WORD Reserved3;
240 DWORD MxCsr;
241 DWORD MxCsr_Mask;
242 M128A FloatRegisters[8];
243 M128A XmmRegisters[16];
244 BYTE Reserved4[96];
245 } XMM_SAVE_AREA32;
247 /* Intel says we need a zeroed 16-byte aligned buffer */
248 char buffer[512 + 16];
249 XMM_SAVE_AREA32 *state = (XMM_SAVE_AREA32 *)(((ULONG_PTR)buffer + 15) & ~15);
250 memset(buffer, 0, sizeof(buffer));
252 __asm__ __volatile__( "fxsave %0" : "=m" (*state) : "m" (*state) );
254 return (state->MxCsr_Mask & (1 << 6)) >> 6;
255 #else /* all x86_64 processors include SSE2 with DAZ mode */
256 return TRUE;
257 #endif
260 static void get_cpuinfo( SYSTEM_CPU_INFORMATION *info )
262 unsigned int regs[4], regs2[4];
264 #if defined(__i386__)
265 info->Architecture = PROCESSOR_ARCHITECTURE_INTEL;
266 #elif defined(__x86_64__)
267 info->Architecture = PROCESSOR_ARCHITECTURE_AMD64;
268 #endif
270 /* We're at least a 386 */
271 info->FeatureSet = CPU_FEATURE_VME | CPU_FEATURE_X86 | CPU_FEATURE_PGE;
272 info->Level = 3;
274 if (!have_cpuid()) return;
276 do_cpuid( 0x00000000, regs ); /* get standard cpuid level and vendor name */
277 if (regs[0]>=0x00000001) /* Check for supported cpuid version */
279 do_cpuid( 0x00000001, regs2 ); /* get cpu features */
280 if (regs2[3] & (1 << 3 )) info->FeatureSet |= CPU_FEATURE_PSE;
281 if (regs2[3] & (1 << 4 )) info->FeatureSet |= CPU_FEATURE_TSC;
282 if (regs2[3] & (1 << 6 )) info->FeatureSet |= CPU_FEATURE_PAE;
283 if (regs2[3] & (1 << 8 )) info->FeatureSet |= CPU_FEATURE_CX8;
284 if (regs2[3] & (1 << 11)) info->FeatureSet |= CPU_FEATURE_SEP;
285 if (regs2[3] & (1 << 12)) info->FeatureSet |= CPU_FEATURE_MTRR;
286 if (regs2[3] & (1 << 15)) info->FeatureSet |= CPU_FEATURE_CMOV;
287 if (regs2[3] & (1 << 16)) info->FeatureSet |= CPU_FEATURE_PAT;
288 if (regs2[3] & (1 << 23)) info->FeatureSet |= CPU_FEATURE_MMX;
289 if (regs2[3] & (1 << 24)) info->FeatureSet |= CPU_FEATURE_FXSR;
290 if (regs2[3] & (1 << 25)) info->FeatureSet |= CPU_FEATURE_SSE;
291 if (regs2[3] & (1 << 26)) info->FeatureSet |= CPU_FEATURE_SSE2;
292 if (regs2[2] & (1 << 0 )) info->FeatureSet |= CPU_FEATURE_SSE3;
293 if (regs2[2] & (1 << 13)) info->FeatureSet |= CPU_FEATURE_CX128;
294 if (regs2[2] & (1 << 27)) info->FeatureSet |= CPU_FEATURE_XSAVE;
295 if((regs2[3] & (1 << 26)) && (regs2[3] & (1 << 24)) && have_sse_daz_mode()) /* has SSE2 and FXSAVE/FXRSTOR */
296 info->FeatureSet |= CPU_FEATURE_DAZ;
298 if (regs[1] == AUTH && regs[3] == ENTI && regs[2] == CAMD)
300 info->Level = (regs2[0] >> 8) & 0xf; /* family */
301 if (info->Level == 0xf) /* AMD says to add the extended family to the family if family is 0xf */
302 info->Level += (regs2[0] >> 20) & 0xff;
304 /* repack model and stepping to make a "revision" */
305 info->Revision = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
306 info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8; /* model */
307 info->Revision |= regs2[0] & 0xf; /* stepping */
309 do_cpuid( 0x80000000, regs ); /* get vendor cpuid level */
310 if (regs[0] >= 0x80000001)
312 do_cpuid( 0x80000001, regs2 ); /* get vendor features */
313 if (regs2[2] & (1 << 2)) info->FeatureSet |= CPU_FEATURE_VIRT;
314 if (regs2[3] & (1 << 20)) info->FeatureSet |= CPU_FEATURE_NX;
315 if (regs2[3] & (1 << 27)) info->FeatureSet |= CPU_FEATURE_TSC;
316 if (regs2[3] & (1u << 31)) info->FeatureSet |= CPU_FEATURE_3DNOW;
319 else if (regs[1] == GENU && regs[3] == INEI && regs[2] == NTEL)
321 info->Level = ((regs2[0] >> 8) & 0xf) + ((regs2[0] >> 20) & 0xff); /* family + extended family */
322 if(info->Level == 15) info->Level = 6;
324 /* repack model and stepping to make a "revision" */
325 info->Revision = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
326 info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8; /* model */
327 info->Revision |= regs2[0] & 0xf; /* stepping */
329 if(regs2[2] & (1 << 5)) info->FeatureSet |= CPU_FEATURE_VIRT;
330 if(regs2[3] & (1 << 21)) info->FeatureSet |= CPU_FEATURE_DS;
332 do_cpuid( 0x80000000, regs ); /* get vendor cpuid level */
333 if (regs[0] >= 0x80000001)
335 do_cpuid( 0x80000001, regs2 ); /* get vendor features */
336 if (regs2[3] & (1 << 20)) info->FeatureSet |= CPU_FEATURE_NX;
337 if (regs2[3] & (1 << 27)) info->FeatureSet |= CPU_FEATURE_TSC;
340 else
342 info->Level = (regs2[0] >> 8) & 0xf; /* family */
344 /* repack model and stepping to make a "revision" */
345 info->Revision = ((regs2[0] >> 4 ) & 0xf) << 8; /* model */
346 info->Revision |= regs2[0] & 0xf; /* stepping */
351 #elif defined(__arm__)
353 static inline void get_cpuinfo( SYSTEM_CPU_INFORMATION *info )
355 #ifdef linux
356 char line[512];
357 char *s, *value;
358 FILE *f = fopen("/proc/cpuinfo", "r");
359 if (f)
361 while (fgets( line, sizeof(line), f ))
363 /* NOTE: the ':' is the only character we can rely on */
364 if (!(value = strchr(line,':'))) continue;
365 /* terminate the valuename */
366 s = value - 1;
367 while ((s >= line) && (*s == ' ' || *s == '\t')) s--;
368 s[1] = 0;
369 /* and strip leading spaces from value */
370 value += 1;
371 while (*value == ' ' || *value == '\t') value++;
372 if ((s = strchr( value,'\n' ))) *s = 0;
373 if (!strcmp( line, "CPU architecture" ))
375 info->Level = atoi(value);
376 continue;
378 if (!strcmp( line, "CPU revision" ))
380 info->Revision = atoi(value);
381 continue;
383 if (!strcmp( line, "Features" ))
385 if (strstr(value, "crc32")) info->FeatureSet |= CPU_FEATURE_ARM_V8_CRC32;
386 if (strstr(value, "aes")) info->FeatureSet |= CPU_FEATURE_ARM_V8_CRYPTO;
387 continue;
390 fclose( f );
392 #elif defined(__FreeBSD__)
393 size_t valsize;
394 char buf[8];
395 int value;
397 valsize = sizeof(buf);
398 if (!sysctlbyname("hw.machine_arch", &buf, &valsize, NULL, 0) && sscanf(buf, "armv%i", &value) == 1)
399 info->Level = value;
401 valsize = sizeof(value);
402 if (!sysctlbyname("hw.floatingpoint", &value, &valsize, NULL, 0))
403 info->FeatureSet |= CPU_FEATURE_ARM_VFP_32;
404 #else
405 FIXME("CPU Feature detection not implemented.\n");
406 #endif
407 info->Architecture = PROCESSOR_ARCHITECTURE_ARM;
410 #elif defined(__aarch64__)
412 static void get_cpuinfo( SYSTEM_CPU_INFORMATION *info )
414 #ifdef linux
415 char line[512];
416 char *s, *value;
417 FILE *f = fopen("/proc/cpuinfo", "r");
418 if (f)
420 while (fgets( line, sizeof(line), f ))
422 /* NOTE: the ':' is the only character we can rely on */
423 if (!(value = strchr(line,':'))) continue;
424 /* terminate the valuename */
425 s = value - 1;
426 while ((s >= line) && (*s == ' ' || *s == '\t')) s--;
427 s[1] = 0;
428 /* and strip leading spaces from value */
429 value += 1;
430 while (*value == ' ' || *value == '\t') value++;
431 if ((s = strchr( value,'\n' ))) *s = 0;
432 if (!strcmp( line, "CPU architecture" ))
434 info->Level = atoi(value);
435 continue;
437 if (!strcmp( line, "CPU revision" ))
439 info->Revision = atoi(value);
440 continue;
442 if (!strcmp( line, "Features" ))
444 if (strstr(value, "crc32")) info->FeatureSet |= CPU_FEATURE_ARM_V8_CRC32;
445 if (strstr(value, "aes")) info->FeatureSet |= CPU_FEATURE_ARM_V8_CRYPTO;
446 continue;
449 fclose( f );
451 #else
452 FIXME("CPU Feature detection not implemented.\n");
453 #endif
454 info->Level = max(info->Level, 8);
455 info->Architecture = PROCESSOR_ARCHITECTURE_ARM64;
458 #endif /* End architecture specific feature detection for CPUs */
460 /******************************************************************
461 * init_cpu_info
463 * inits a couple of places with CPU related information:
464 * - cpu_info in this file
465 * - Peb->NumberOfProcessors
466 * - SharedUserData->ProcessFeatures[] array
468 void init_cpu_info(void)
470 long num;
472 #ifdef _SC_NPROCESSORS_ONLN
473 num = sysconf(_SC_NPROCESSORS_ONLN);
474 if (num < 1)
476 num = 1;
477 WARN("Failed to detect the number of processors.\n");
479 #elif defined(CTL_HW) && defined(HW_NCPU)
480 int mib[2];
481 size_t len = sizeof(num);
482 mib[0] = CTL_HW;
483 mib[1] = HW_NCPU;
484 if (sysctl(mib, 2, &num, &len, NULL, 0) != 0)
486 num = 1;
487 WARN("Failed to detect the number of processors.\n");
489 #else
490 num = 1;
491 FIXME("Detecting the number of processors is not supported.\n");
492 #endif
493 NtCurrentTeb()->Peb->NumberOfProcessors = num;
494 get_cpuinfo( &cpu_info );
495 TRACE( "<- CPU arch %d, level %d, rev %d, features 0x%x\n",
496 cpu_info.Architecture, cpu_info.Level, cpu_info.Revision, cpu_info.FeatureSet );
499 static BOOL grow_logical_proc_buf( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
500 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *max_len )
502 if (pdata)
504 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
506 *max_len *= 2;
507 new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *pdata, *max_len*sizeof(*new_data));
508 if (!new_data)
509 return FALSE;
511 *pdata = new_data;
513 else
515 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *new_dataex;
517 *max_len *= 2;
518 new_dataex = RtlReAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdataex, *max_len*sizeof(*new_dataex));
519 if (!new_dataex)
520 return FALSE;
522 *pdataex = new_dataex;
525 return TRUE;
528 static DWORD log_proc_ex_size_plus(DWORD size)
530 /* add SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX.Relationship and .Size */
531 return sizeof(LOGICAL_PROCESSOR_RELATIONSHIP) + sizeof(DWORD) + size;
534 static DWORD count_bits(ULONG_PTR mask)
536 DWORD count = 0;
537 while (mask > 0)
539 mask >>= 1;
540 count++;
542 return count;
545 /* Store package and core information for a logical processor. Parsing of processor
546 * data may happen in multiple passes; the 'id' parameter is then used to locate
547 * previously stored data. The type of data stored in 'id' depends on 'rel':
548 * - RelationProcessorPackage: package id ('CPU socket').
549 * - RelationProcessorCore: physical core number.
551 static BOOL logical_proc_info_add_by_id( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
552 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *len,
553 DWORD *pmax_len, LOGICAL_PROCESSOR_RELATIONSHIP rel,
554 DWORD id, ULONG_PTR mask )
556 if (pdata)
558 DWORD i;
560 for (i = 0; i < *len; i++)
562 if (rel == RelationProcessorPackage && (*pdata)[i].Relationship == rel && (*pdata)[i].u.Reserved[1] == id)
564 (*pdata)[i].ProcessorMask |= mask;
565 return TRUE;
567 else if (rel == RelationProcessorCore && (*pdata)[i].Relationship == rel && (*pdata)[i].u.Reserved[1] == id)
568 return TRUE;
571 while (*len == *pmax_len)
573 if (!grow_logical_proc_buf(pdata, NULL, pmax_len)) return FALSE;
576 (*pdata)[i].Relationship = rel;
577 (*pdata)[i].ProcessorMask = mask;
578 if (rel == RelationProcessorCore)
579 (*pdata)[i].u.ProcessorCore.Flags = count_bits(mask) > 1 ? LTP_PC_SMT : 0;
580 (*pdata)[i].u.Reserved[0] = 0;
581 (*pdata)[i].u.Reserved[1] = id;
582 *len = i+1;
584 else
586 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex;
587 DWORD ofs = 0;
589 while (ofs < *len)
591 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
592 if (rel == RelationProcessorPackage && dataex->Relationship == rel && dataex->u.Processor.Reserved[1] == id)
594 dataex->u.Processor.GroupMask[0].Mask |= mask;
595 return TRUE;
597 else if (rel == RelationProcessorCore && dataex->Relationship == rel && dataex->u.Processor.Reserved[1] == id)
599 return TRUE;
601 ofs += dataex->Size;
604 /* TODO: For now, just one group. If more than 64 processors, then we
605 * need another group. */
607 while (ofs + log_proc_ex_size_plus(sizeof(PROCESSOR_RELATIONSHIP)) > *pmax_len)
609 if (!grow_logical_proc_buf(NULL, pdataex, pmax_len)) return FALSE;
612 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
614 dataex->Relationship = rel;
615 dataex->Size = log_proc_ex_size_plus(sizeof(PROCESSOR_RELATIONSHIP));
616 if (rel == RelationProcessorCore)
617 dataex->u.Processor.Flags = count_bits(mask) > 1 ? LTP_PC_SMT : 0;
618 else
619 dataex->u.Processor.Flags = 0;
620 dataex->u.Processor.EfficiencyClass = 0;
621 dataex->u.Processor.GroupCount = 1;
622 dataex->u.Processor.GroupMask[0].Mask = mask;
623 dataex->u.Processor.GroupMask[0].Group = 0;
624 /* mark for future lookup */
625 dataex->u.Processor.Reserved[0] = 0;
626 dataex->u.Processor.Reserved[1] = id;
628 *len += dataex->Size;
631 return TRUE;
634 static BOOL logical_proc_info_add_cache( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
635 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *len,
636 DWORD *pmax_len, ULONG_PTR mask, CACHE_DESCRIPTOR *cache )
638 if (pdata)
640 DWORD i;
642 for (i = 0; i < *len; i++)
644 if ((*pdata)[i].Relationship==RelationCache && (*pdata)[i].ProcessorMask==mask
645 && (*pdata)[i].u.Cache.Level==cache->Level && (*pdata)[i].u.Cache.Type==cache->Type)
646 return TRUE;
649 while (*len == *pmax_len)
650 if (!grow_logical_proc_buf(pdata, NULL, pmax_len)) return FALSE;
652 (*pdata)[i].Relationship = RelationCache;
653 (*pdata)[i].ProcessorMask = mask;
654 (*pdata)[i].u.Cache = *cache;
655 *len = i+1;
657 else
659 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex;
660 DWORD ofs;
662 for (ofs = 0; ofs < *len; )
664 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
665 if (dataex->Relationship == RelationCache && dataex->u.Cache.GroupMask.Mask == mask &&
666 dataex->u.Cache.Level == cache->Level && dataex->u.Cache.Type == cache->Type)
667 return TRUE;
668 ofs += dataex->Size;
671 while (ofs + log_proc_ex_size_plus(sizeof(CACHE_RELATIONSHIP)) > *pmax_len)
673 if (!grow_logical_proc_buf(NULL, pdataex, pmax_len)) return FALSE;
676 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
678 dataex->Relationship = RelationCache;
679 dataex->Size = log_proc_ex_size_plus(sizeof(CACHE_RELATIONSHIP));
680 dataex->u.Cache.Level = cache->Level;
681 dataex->u.Cache.Associativity = cache->Associativity;
682 dataex->u.Cache.LineSize = cache->LineSize;
683 dataex->u.Cache.CacheSize = cache->Size;
684 dataex->u.Cache.Type = cache->Type;
685 dataex->u.Cache.GroupMask.Mask = mask;
686 dataex->u.Cache.GroupMask.Group = 0;
688 *len += dataex->Size;
691 return TRUE;
694 static BOOL logical_proc_info_add_numa_node( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
695 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *len,
696 DWORD *pmax_len, ULONG_PTR mask, DWORD node_id )
698 if (pdata)
700 while (*len == *pmax_len)
701 if (!grow_logical_proc_buf(pdata, NULL, pmax_len)) return FALSE;
703 (*pdata)[*len].Relationship = RelationNumaNode;
704 (*pdata)[*len].ProcessorMask = mask;
705 (*pdata)[*len].u.NumaNode.NodeNumber = node_id;
706 (*len)++;
708 else
710 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex;
712 while (*len + log_proc_ex_size_plus(sizeof(NUMA_NODE_RELATIONSHIP)) > *pmax_len)
714 if (!grow_logical_proc_buf(NULL, pdataex, pmax_len)) return FALSE;
717 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + *len);
719 dataex->Relationship = RelationNumaNode;
720 dataex->Size = log_proc_ex_size_plus(sizeof(NUMA_NODE_RELATIONSHIP));
721 dataex->u.NumaNode.NodeNumber = node_id;
722 dataex->u.NumaNode.GroupMask.Mask = mask;
723 dataex->u.NumaNode.GroupMask.Group = 0;
725 *len += dataex->Size;
728 return TRUE;
731 static BOOL logical_proc_info_add_group( SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex,
732 DWORD *len, DWORD *pmax_len, DWORD num_cpus, ULONG_PTR mask )
734 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex;
736 while (*len + log_proc_ex_size_plus(sizeof(GROUP_RELATIONSHIP)) > *pmax_len)
737 if (!grow_logical_proc_buf(NULL, pdataex, pmax_len)) return FALSE;
739 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + *len);
741 dataex->Relationship = RelationGroup;
742 dataex->Size = log_proc_ex_size_plus(sizeof(GROUP_RELATIONSHIP));
743 dataex->u.Group.MaximumGroupCount = 1;
744 dataex->u.Group.ActiveGroupCount = 1;
745 dataex->u.Group.GroupInfo[0].MaximumProcessorCount = num_cpus;
746 dataex->u.Group.GroupInfo[0].ActiveProcessorCount = num_cpus;
747 dataex->u.Group.GroupInfo[0].ActiveProcessorMask = mask;
749 *len += dataex->Size;
750 return TRUE;
753 #ifdef linux
755 /* Helper function for counting bitmap values as commonly used by the Linux kernel
756 * for storing CPU masks in sysfs. The format is comma separated lists of hex values
757 * each max 32-bit e.g. "00ff" or even "00,00000000,0000ffff".
759 * Example files include:
760 * - /sys/devices/system/cpu/cpu0/cache/index0/shared_cpu_map
761 * - /sys/devices/system/cpu/cpu0/topology/thread_siblings
763 static BOOL sysfs_parse_bitmap(const char *filename, ULONG_PTR *mask)
765 FILE *f;
766 DWORD r;
768 f = fopen(filename, "r");
769 if (!f) return FALSE;
771 while (!feof(f))
773 char op;
774 if (!fscanf(f, "%x%c ", &r, &op)) break;
775 *mask = (sizeof(ULONG_PTR)>sizeof(int) ? *mask << (8 * sizeof(DWORD)) : 0) + r;
777 fclose( f );
778 return TRUE;
781 /* Helper function for counting number of elements in interval lists as used by
782 * the Linux kernel. The format is comma separated list of intervals of which
783 * each interval has the format of "begin-end" where begin and end are decimal
784 * numbers. E.g. "0-7", "0-7,16-23"
786 * Example files include:
787 * - /sys/devices/system/cpu/online
788 * - /sys/devices/system/cpu/cpu0/cache/index0/shared_cpu_list
789 * - /sys/devices/system/cpu/cpu0/topology/thread_siblings_list.
791 static BOOL sysfs_count_list_elements(const char *filename, DWORD *result)
793 FILE *f;
795 f = fopen(filename, "r");
796 if (!f) return FALSE;
798 while (!feof(f))
800 char op;
801 DWORD beg, end;
803 if (!fscanf(f, "%u%c ", &beg, &op)) break;
804 if(op == '-')
805 fscanf(f, "%u%c ", &end, &op);
806 else
807 end = beg;
809 *result += end - beg + 1;
811 fclose( f );
812 return TRUE;
815 /* for 'data', max_len is the array count. for 'dataex', max_len is in bytes */
816 static NTSTATUS create_logical_proc_info( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data,
817 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **dataex,
818 DWORD *max_len, DWORD relation )
820 static const char core_info[] = "/sys/devices/system/cpu/cpu%u/topology/%s";
821 static const char cache_info[] = "/sys/devices/system/cpu/cpu%u/cache/index%u/%s";
822 static const char numa_info[] = "/sys/devices/system/node/node%u/cpumap";
824 FILE *fcpu_list, *fnuma_list, *f;
825 DWORD len = 0, beg, end, i, j, r, num_cpus = 0, max_cpus = 0;
826 char op, name[MAX_PATH];
827 ULONG_PTR all_cpus_mask = 0;
829 /* On systems with a large number of CPU cores (32 or 64 depending on 32-bit or 64-bit),
830 * we have issues parsing processor information:
831 * - ULONG_PTR masks as used in data structures can't hold all cores. Requires splitting
832 * data appropriately into "processor groups". We are hard coding 1.
833 * - Thread affinity code in wineserver and our CPU parsing code here work independently.
834 * So far the Windows mask applied directly to Linux, but process groups break that.
835 * (NUMA systems you may have multiple non-full groups.)
837 if(sysfs_count_list_elements("/sys/devices/system/cpu/present", &max_cpus) && max_cpus > MAXIMUM_PROCESSORS)
839 FIXME("Improve CPU info reporting: system supports %u logical cores, but only %u supported!\n",
840 max_cpus, MAXIMUM_PROCESSORS);
843 fcpu_list = fopen("/sys/devices/system/cpu/online", "r");
844 if (!fcpu_list) return STATUS_NOT_IMPLEMENTED;
846 while (!feof(fcpu_list))
848 if (!fscanf(fcpu_list, "%u%c ", &beg, &op)) break;
849 if (op == '-') fscanf(fcpu_list, "%u%c ", &end, &op);
850 else end = beg;
852 for(i = beg; i <= end; i++)
854 DWORD phys_core = 0;
855 ULONG_PTR thread_mask = 0;
857 if (i > 8*sizeof(ULONG_PTR))
859 FIXME("skipping logical processor %d\n", i);
860 continue;
863 if (relation == RelationAll || relation == RelationProcessorPackage)
865 sprintf(name, core_info, i, "physical_package_id");
866 f = fopen(name, "r");
867 if (f)
869 fscanf(f, "%u", &r);
870 fclose(f);
872 else r = 0;
873 if (!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorPackage, r, (ULONG_PTR)1 << i))
875 fclose(fcpu_list);
876 return STATUS_NO_MEMORY;
880 /* Sysfs enumerates logical cores (and not physical cores), but Windows enumerates
881 * by physical core. Upon enumerating a logical core in sysfs, we register a physical
882 * core and all its logical cores. In order to not report physical cores multiple
883 * times, we pass a unique physical core ID to logical_proc_info_add_by_id and let
884 * that call figure out any duplication.
885 * Obtain a unique physical core ID from the first element of thread_siblings_list.
886 * This list provides logical cores sharing the same physical core. The IDs are based
887 * on kernel cpu core numbering as opposed to a hardware core ID like provided through
888 * 'core_id', so are suitable as a unique ID.
890 if(relation == RelationAll || relation == RelationProcessorCore ||
891 relation == RelationNumaNode || relation == RelationGroup)
893 /* Mask of logical threads sharing same physical core in kernel core numbering. */
894 sprintf(name, core_info, i, "thread_siblings");
895 if(!sysfs_parse_bitmap(name, &thread_mask)) thread_mask = 1<<i;
897 /* Needed later for NumaNode and Group. */
898 all_cpus_mask |= thread_mask;
900 if (relation == RelationAll || relation == RelationProcessorCore)
902 sprintf(name, core_info, i, "thread_siblings_list");
903 f = fopen(name, "r");
904 if (f)
906 fscanf(f, "%d%c", &phys_core, &op);
907 fclose(f);
909 else phys_core = i;
911 if (!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorCore, phys_core, thread_mask))
913 fclose(fcpu_list);
914 return STATUS_NO_MEMORY;
919 if (relation == RelationAll || relation == RelationCache)
921 for(j = 0; j < 4; j++)
923 CACHE_DESCRIPTOR cache;
924 ULONG_PTR mask = 0;
926 sprintf(name, cache_info, i, j, "shared_cpu_map");
927 if(!sysfs_parse_bitmap(name, &mask)) continue;
929 sprintf(name, cache_info, i, j, "level");
930 f = fopen(name, "r");
931 if(!f) continue;
932 fscanf(f, "%u", &r);
933 fclose(f);
934 cache.Level = r;
936 sprintf(name, cache_info, i, j, "ways_of_associativity");
937 f = fopen(name, "r");
938 if(!f) continue;
939 fscanf(f, "%u", &r);
940 fclose(f);
941 cache.Associativity = r;
943 sprintf(name, cache_info, i, j, "coherency_line_size");
944 f = fopen(name, "r");
945 if(!f) continue;
946 fscanf(f, "%u", &r);
947 fclose(f);
948 cache.LineSize = r;
950 sprintf(name, cache_info, i, j, "size");
951 f = fopen(name, "r");
952 if(!f) continue;
953 fscanf(f, "%u%c", &r, &op);
954 fclose(f);
955 if(op != 'K')
956 WARN("unknown cache size %u%c\n", r, op);
957 cache.Size = (op=='K' ? r*1024 : r);
959 sprintf(name, cache_info, i, j, "type");
960 f = fopen(name, "r");
961 if(!f) continue;
962 fscanf(f, "%s", name);
963 fclose(f);
964 if (!memcmp(name, "Data", 5))
965 cache.Type = CacheData;
966 else if(!memcmp(name, "Instruction", 11))
967 cache.Type = CacheInstruction;
968 else
969 cache.Type = CacheUnified;
971 if (!logical_proc_info_add_cache(data, dataex, &len, max_len, mask, &cache))
973 fclose(fcpu_list);
974 return STATUS_NO_MEMORY;
980 fclose(fcpu_list);
982 num_cpus = count_bits(all_cpus_mask);
984 if(relation == RelationAll || relation == RelationNumaNode)
986 fnuma_list = fopen("/sys/devices/system/node/online", "r");
987 if (!fnuma_list)
989 if (!logical_proc_info_add_numa_node(data, dataex, &len, max_len, all_cpus_mask, 0))
990 return STATUS_NO_MEMORY;
992 else
994 while (!feof(fnuma_list))
996 if (!fscanf(fnuma_list, "%u%c ", &beg, &op))
997 break;
998 if (op == '-') fscanf(fnuma_list, "%u%c ", &end, &op);
999 else end = beg;
1001 for (i = beg; i <= end; i++)
1003 ULONG_PTR mask = 0;
1005 sprintf(name, numa_info, i);
1006 if (!sysfs_parse_bitmap( name, &mask )) continue;
1008 if (!logical_proc_info_add_numa_node(data, dataex, &len, max_len, mask, i))
1010 fclose(fnuma_list);
1011 return STATUS_NO_MEMORY;
1015 fclose(fnuma_list);
1019 if(dataex && (relation == RelationAll || relation == RelationGroup))
1020 logical_proc_info_add_group(dataex, &len, max_len, num_cpus, all_cpus_mask);
1022 if(data)
1023 *max_len = len * sizeof(**data);
1024 else
1025 *max_len = len;
1027 return STATUS_SUCCESS;
1030 #elif defined(__APPLE__)
1032 /* for 'data', max_len is the array count. for 'dataex', max_len is in bytes */
1033 static NTSTATUS create_logical_proc_info( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data,
1034 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **dataex,
1035 DWORD *max_len, DWORD relation)
1037 DWORD pkgs_no, cores_no, lcpu_no, lcpu_per_core, cores_per_package, assoc, len = 0;
1038 DWORD cache_ctrs[10] = {0};
1039 ULONG_PTR all_cpus_mask = 0;
1040 CACHE_DESCRIPTOR cache[10];
1041 LONGLONG cache_size, cache_line_size, cache_sharing[10];
1042 size_t size;
1043 DWORD p,i,j,k;
1045 if (relation != RelationAll)
1046 FIXME("Relationship filtering not implemented: 0x%x\n", relation);
1048 lcpu_no = NtCurrentTeb()->Peb->NumberOfProcessors;
1050 size = sizeof(pkgs_no);
1051 if (sysctlbyname("hw.packages", &pkgs_no, &size, NULL, 0))
1052 pkgs_no = 1;
1054 size = sizeof(cores_no);
1055 if (sysctlbyname("hw.physicalcpu", &cores_no, &size, NULL, 0))
1056 cores_no = lcpu_no;
1058 TRACE("%u logical CPUs from %u physical cores across %u packages\n",
1059 lcpu_no, cores_no, pkgs_no);
1061 lcpu_per_core = lcpu_no / cores_no;
1062 cores_per_package = cores_no / pkgs_no;
1064 memset(cache, 0, sizeof(cache));
1065 cache[1].Level = 1;
1066 cache[1].Type = CacheInstruction;
1067 cache[1].Associativity = 8; /* reasonable default */
1068 cache[1].LineSize = 0x40; /* reasonable default */
1069 cache[2].Level = 1;
1070 cache[2].Type = CacheData;
1071 cache[2].Associativity = 8;
1072 cache[2].LineSize = 0x40;
1073 cache[3].Level = 2;
1074 cache[3].Type = CacheUnified;
1075 cache[3].Associativity = 8;
1076 cache[3].LineSize = 0x40;
1077 cache[4].Level = 3;
1078 cache[4].Type = CacheUnified;
1079 cache[4].Associativity = 12;
1080 cache[4].LineSize = 0x40;
1082 size = sizeof(cache_line_size);
1083 if (!sysctlbyname("hw.cachelinesize", &cache_line_size, &size, NULL, 0))
1085 for (i = 1; i < 5; i++) cache[i].LineSize = cache_line_size;
1088 /* TODO: set actual associativity for all caches */
1089 size = sizeof(assoc);
1090 if (!sysctlbyname("machdep.cpu.cache.L2_associativity", &assoc, &size, NULL, 0))
1091 cache[3].Associativity = assoc;
1093 size = sizeof(cache_size);
1094 if (!sysctlbyname("hw.l1icachesize", &cache_size, &size, NULL, 0))
1095 cache[1].Size = cache_size;
1096 size = sizeof(cache_size);
1097 if (!sysctlbyname("hw.l1dcachesize", &cache_size, &size, NULL, 0))
1098 cache[2].Size = cache_size;
1099 size = sizeof(cache_size);
1100 if (!sysctlbyname("hw.l2cachesize", &cache_size, &size, NULL, 0))
1101 cache[3].Size = cache_size;
1102 size = sizeof(cache_size);
1103 if (!sysctlbyname("hw.l3cachesize", &cache_size, &size, NULL, 0))
1104 cache[4].Size = cache_size;
1106 size = sizeof(cache_sharing);
1107 if (sysctlbyname("hw.cacheconfig", cache_sharing, &size, NULL, 0) < 0)
1109 cache_sharing[1] = lcpu_per_core;
1110 cache_sharing[2] = lcpu_per_core;
1111 cache_sharing[3] = lcpu_per_core;
1112 cache_sharing[4] = lcpu_no;
1114 else
1116 /* in cache[], indexes 1 and 2 are l1 caches */
1117 cache_sharing[4] = cache_sharing[3];
1118 cache_sharing[3] = cache_sharing[2];
1119 cache_sharing[2] = cache_sharing[1];
1122 for(p = 0; p < pkgs_no; ++p)
1124 for(j = 0; j < cores_per_package && p * cores_per_package + j < cores_no; ++j)
1126 ULONG_PTR mask = 0;
1127 DWORD phys_core;
1129 for(k = 0; k < lcpu_per_core; ++k) mask |= (ULONG_PTR)1 << (j * lcpu_per_core + k);
1131 all_cpus_mask |= mask;
1133 /* add to package */
1134 if(!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorPackage, p, mask))
1135 return STATUS_NO_MEMORY;
1137 /* add new core */
1138 phys_core = p * cores_per_package + j;
1139 if(!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorCore, phys_core, mask))
1140 return STATUS_NO_MEMORY;
1142 for(i = 1; i < 5; ++i)
1144 if(cache_ctrs[i] == 0 && cache[i].Size > 0)
1146 mask = 0;
1147 for(k = 0; k < cache_sharing[i]; ++k)
1148 mask |= (ULONG_PTR)1 << (j * lcpu_per_core + k);
1150 if(!logical_proc_info_add_cache(data, dataex, &len, max_len, mask, &cache[i]))
1151 return STATUS_NO_MEMORY;
1154 cache_ctrs[i] += lcpu_per_core;
1155 if(cache_ctrs[i] == cache_sharing[i]) cache_ctrs[i] = 0;
1160 /* OSX doesn't support NUMA, so just make one NUMA node for all CPUs */
1161 if(!logical_proc_info_add_numa_node(data, dataex, &len, max_len, all_cpus_mask, 0))
1162 return STATUS_NO_MEMORY;
1164 if(dataex) logical_proc_info_add_group(dataex, &len, max_len, lcpu_no, all_cpus_mask);
1166 if(data)
1167 *max_len = len * sizeof(**data);
1168 else
1169 *max_len = len;
1171 return STATUS_SUCCESS;
1174 #else
1176 static NTSTATUS create_logical_proc_info( SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data,
1177 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **dataex,
1178 DWORD *max_len, DWORD relation )
1180 FIXME("stub\n");
1181 return STATUS_NOT_IMPLEMENTED;
1183 #endif
1185 #ifdef linux
1187 static void copy_smbios_string( char **buffer, char *s, size_t len )
1189 if (!len) return;
1190 memcpy(*buffer, s, len + 1);
1191 *buffer += len + 1;
1194 static size_t get_smbios_string( const char *path, char *str, size_t size )
1196 FILE *file;
1197 size_t len;
1199 if (!(file = fopen(path, "r"))) return 0;
1201 len = fread( str, 1, size - 1, file );
1202 fclose( file );
1204 if (len >= 1 && str[len - 1] == '\n') len--;
1205 str[len] = 0;
1206 return len;
1209 static void get_system_uuid( GUID *uuid )
1211 static const unsigned char hex[] =
1213 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x00 */
1214 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x10 */
1215 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x20 */
1216 0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0, /* 0x30 */
1217 0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0, /* 0x40 */
1218 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x50 */
1219 0,10,11,12,13,14,15 /* 0x60 */
1221 int fd;
1223 memset( uuid, 0xff, sizeof(*uuid) );
1224 if ((fd = open( "/var/lib/dbus/machine-id", O_RDONLY )) != -1)
1226 unsigned char buf[32], *p = buf;
1227 if (read( fd, buf, sizeof(buf) ) == sizeof(buf))
1229 uuid->Data1 = hex[p[6]] << 28 | hex[p[7]] << 24 | hex[p[4]] << 20 | hex[p[5]] << 16 |
1230 hex[p[2]] << 12 | hex[p[3]] << 8 | hex[p[0]] << 4 | hex[p[1]];
1232 uuid->Data2 = hex[p[10]] << 12 | hex[p[11]] << 8 | hex[p[8]] << 4 | hex[p[9]];
1233 uuid->Data3 = hex[p[14]] << 12 | hex[p[15]] << 8 | hex[p[12]] << 4 | hex[p[13]];
1235 uuid->Data4[0] = hex[p[16]] << 4 | hex[p[17]];
1236 uuid->Data4[1] = hex[p[18]] << 4 | hex[p[19]];
1237 uuid->Data4[2] = hex[p[20]] << 4 | hex[p[21]];
1238 uuid->Data4[3] = hex[p[22]] << 4 | hex[p[23]];
1239 uuid->Data4[4] = hex[p[24]] << 4 | hex[p[25]];
1240 uuid->Data4[5] = hex[p[26]] << 4 | hex[p[27]];
1241 uuid->Data4[6] = hex[p[28]] << 4 | hex[p[29]];
1242 uuid->Data4[7] = hex[p[30]] << 4 | hex[p[31]];
1244 close( fd );
1248 static NTSTATUS get_firmware_info( SYSTEM_FIRMWARE_TABLE_INFORMATION *sfti, ULONG available_len,
1249 ULONG *required_len )
1251 switch (sfti->ProviderSignature)
1253 case RSMB:
1255 char bios_vendor[128], bios_version[128], bios_date[128];
1256 size_t bios_vendor_len, bios_version_len, bios_date_len;
1257 char system_vendor[128], system_product[128], system_version[128], system_serial[128];
1258 size_t system_vendor_len, system_product_len, system_version_len, system_serial_len;
1259 char system_sku[128], system_family[128];
1260 size_t system_sku_len, system_family_len;
1261 char board_vendor[128], board_product[128], board_version[128], board_serial[128];
1262 size_t board_vendor_len, board_product_len, board_version_len, board_serial_len;
1263 char chassis_vendor[128], chassis_version[128], chassis_serial[128], chassis_asset_tag[128];
1264 char chassis_type[11] = "2"; /* unknown */
1265 size_t chassis_vendor_len, chassis_version_len, chassis_serial_len, chassis_asset_tag_len;
1266 char *buffer = (char*)sfti->TableBuffer;
1267 BYTE string_count;
1268 struct smbios_prologue *prologue;
1269 struct smbios_bios *bios;
1270 struct smbios_system *system;
1271 struct smbios_board *board;
1272 struct smbios_chassis *chassis;
1274 #define S(s) s, sizeof(s)
1275 bios_vendor_len = get_smbios_string("/sys/class/dmi/id/bios_vendor", S(bios_vendor));
1276 bios_version_len = get_smbios_string("/sys/class/dmi/id/bios_version", S(bios_version));
1277 bios_date_len = get_smbios_string("/sys/class/dmi/id/bios_date", S(bios_date));
1278 system_vendor_len = get_smbios_string("/sys/class/dmi/id/sys_vendor", S(system_vendor));
1279 system_product_len = get_smbios_string("/sys/class/dmi/id/product_name", S(system_product));
1280 system_version_len = get_smbios_string("/sys/class/dmi/id/product_version", S(system_version));
1281 system_serial_len = get_smbios_string("/sys/class/dmi/id/product_serial", S(system_serial));
1282 system_sku_len = get_smbios_string("/sys/class/dmi/id/product_sku", S(system_sku));
1283 system_family_len = get_smbios_string("/sys/class/dmi/id/product_family", S(system_family));
1284 board_vendor_len = get_smbios_string("/sys/class/dmi/id/board_vendor", S(board_vendor));
1285 board_product_len = get_smbios_string("/sys/class/dmi/id/board_name", S(board_product));
1286 board_version_len = get_smbios_string("/sys/class/dmi/id/board_version", S(board_version));
1287 board_serial_len = get_smbios_string("/sys/class/dmi/id/board_serial", S(board_serial));
1288 chassis_vendor_len = get_smbios_string("/sys/class/dmi/id/chassis_vendor", S(chassis_vendor));
1289 chassis_version_len = get_smbios_string("/sys/class/dmi/id/chassis_version", S(chassis_version));
1290 chassis_serial_len = get_smbios_string("/sys/class/dmi/id/chassis_serial", S(chassis_serial));
1291 chassis_asset_tag_len = get_smbios_string("/sys/class/dmi/id/chassis_tag", S(chassis_asset_tag));
1292 get_smbios_string("/sys/class/dmi/id/chassis_type", S(chassis_type));
1293 #undef S
1295 *required_len = sizeof(struct smbios_prologue);
1297 #define L(l) (l + (l ? 1 : 0))
1298 *required_len += sizeof(struct smbios_bios);
1299 *required_len += max(L(bios_vendor_len) + L(bios_version_len) + L(bios_date_len) + 1, 2);
1301 *required_len += sizeof(struct smbios_system);
1302 *required_len += max(L(system_vendor_len) + L(system_product_len) + L(system_version_len) +
1303 L(system_serial_len) + L(system_sku_len) + L(system_family_len) + 1, 2);
1305 *required_len += sizeof(struct smbios_board);
1306 *required_len += max(L(board_vendor_len) + L(board_product_len) + L(board_version_len) + L(board_serial_len) + 1, 2);
1308 *required_len += sizeof(struct smbios_chassis);
1309 *required_len += max(L(chassis_vendor_len) + L(chassis_version_len) + L(chassis_serial_len) +
1310 L(chassis_asset_tag_len) + 1, 2);
1311 #undef L
1313 sfti->TableBufferLength = *required_len;
1315 *required_len += FIELD_OFFSET(SYSTEM_FIRMWARE_TABLE_INFORMATION, TableBuffer);
1317 if (available_len < *required_len)
1318 return STATUS_BUFFER_TOO_SMALL;
1320 prologue = (struct smbios_prologue*)buffer;
1321 prologue->calling_method = 0;
1322 prologue->major_version = 2;
1323 prologue->minor_version = 4;
1324 prologue->revision = 0;
1325 prologue->length = sfti->TableBufferLength - sizeof(struct smbios_prologue);
1326 buffer += sizeof(struct smbios_prologue);
1328 string_count = 0;
1329 bios = (struct smbios_bios*)buffer;
1330 bios->hdr.type = 0;
1331 bios->hdr.length = sizeof(struct smbios_bios);
1332 bios->hdr.handle = 0;
1333 bios->vendor = bios_vendor_len ? ++string_count : 0;
1334 bios->version = bios_version_len ? ++string_count : 0;
1335 bios->start = 0;
1336 bios->date = bios_date_len ? ++string_count : 0;
1337 bios->size = 0;
1338 bios->characteristics = 0x4; /* not supported */
1339 bios->characteristics_ext[0] = 0;
1340 bios->characteristics_ext[1] = 0;
1341 bios->system_bios_major_release = 0xFF; /* not supported */
1342 bios->system_bios_minor_release = 0xFF; /* not supported */
1343 bios->ec_firmware_major_release = 0xFF; /* not supported */
1344 bios->ec_firmware_minor_release = 0xFF; /* not supported */
1345 buffer += sizeof(struct smbios_bios);
1347 copy_smbios_string(&buffer, bios_vendor, bios_vendor_len);
1348 copy_smbios_string(&buffer, bios_version, bios_version_len);
1349 copy_smbios_string(&buffer, bios_date, bios_date_len);
1350 if (!string_count) *buffer++ = 0;
1351 *buffer++ = 0;
1353 string_count = 0;
1354 system = (struct smbios_system*)buffer;
1355 system->hdr.type = 1;
1356 system->hdr.length = sizeof(struct smbios_system);
1357 system->hdr.handle = 0;
1358 system->vendor = system_vendor_len ? ++string_count : 0;
1359 system->product = system_product_len ? ++string_count : 0;
1360 system->version = system_version_len ? ++string_count : 0;
1361 system->serial = system_serial_len ? ++string_count : 0;
1362 get_system_uuid( (GUID *)system->uuid );
1363 system->wake_up_type = 0x02; /* unknown */
1364 system->sku_number = system_sku_len ? ++string_count : 0;
1365 system->family = system_family_len ? ++string_count : 0;
1366 buffer += sizeof(struct smbios_system);
1368 copy_smbios_string(&buffer, system_vendor, system_vendor_len);
1369 copy_smbios_string(&buffer, system_product, system_product_len);
1370 copy_smbios_string(&buffer, system_version, system_version_len);
1371 copy_smbios_string(&buffer, system_serial, system_serial_len);
1372 copy_smbios_string(&buffer, system_sku, system_sku_len);
1373 copy_smbios_string(&buffer, system_family, system_family_len);
1374 if (!string_count) *buffer++ = 0;
1375 *buffer++ = 0;
1377 string_count = 0;
1378 board = (struct smbios_board*)buffer;
1379 board->hdr.type = 2;
1380 board->hdr.length = sizeof(struct smbios_board);
1381 board->hdr.handle = 0;
1382 board->vendor = board_vendor_len ? ++string_count : 0;
1383 board->product = board_product_len ? ++string_count : 0;
1384 board->version = board_version_len ? ++string_count : 0;
1385 board->serial = board_serial_len ? ++string_count : 0;
1386 buffer += sizeof(struct smbios_board);
1388 copy_smbios_string(&buffer, board_vendor, board_vendor_len);
1389 copy_smbios_string(&buffer, board_product, board_product_len);
1390 copy_smbios_string(&buffer, board_version, board_version_len);
1391 copy_smbios_string(&buffer, board_serial, board_serial_len);
1392 if (!string_count) *buffer++ = 0;
1393 *buffer++ = 0;
1395 string_count = 0;
1396 chassis = (struct smbios_chassis*)buffer;
1397 chassis->hdr.type = 3;
1398 chassis->hdr.length = sizeof(struct smbios_chassis);
1399 chassis->hdr.handle = 0;
1400 chassis->vendor = chassis_vendor_len ? ++string_count : 0;
1401 chassis->type = atoi(chassis_type);
1402 chassis->version = chassis_version_len ? ++string_count : 0;
1403 chassis->serial = chassis_serial_len ? ++string_count : 0;
1404 chassis->asset_tag = chassis_asset_tag_len ? ++string_count : 0;
1405 chassis->boot_state = 0x02; /* unknown */
1406 chassis->power_supply_state = 0x02; /* unknown */
1407 chassis->thermal_state = 0x02; /* unknown */
1408 chassis->security_status = 0x02; /* unknown */
1409 buffer += sizeof(struct smbios_chassis);
1411 copy_smbios_string(&buffer, chassis_vendor, chassis_vendor_len);
1412 copy_smbios_string(&buffer, chassis_version, chassis_version_len);
1413 copy_smbios_string(&buffer, chassis_serial, chassis_serial_len);
1414 copy_smbios_string(&buffer, chassis_asset_tag, chassis_asset_tag_len);
1415 if (!string_count) *buffer++ = 0;
1416 *buffer++ = 0;
1418 return STATUS_SUCCESS;
1420 default:
1421 FIXME("info_class SYSTEM_FIRMWARE_TABLE_INFORMATION provider %08x\n", sfti->ProviderSignature);
1422 return STATUS_NOT_IMPLEMENTED;
1426 #elif defined(__APPLE__)
1428 static NTSTATUS get_firmware_info( SYSTEM_FIRMWARE_TABLE_INFORMATION *sfti, ULONG available_len,
1429 ULONG *required_len )
1431 switch (sfti->ProviderSignature)
1433 case RSMB:
1435 io_service_t service;
1436 CFDataRef data;
1437 const UInt8 *ptr;
1438 CFIndex len;
1439 struct smbios_prologue *prologue;
1440 BYTE major_version = 2, minor_version = 0;
1442 if (!(service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleSMBIOS"))))
1444 WARN("can't find AppleSMBIOS service\n");
1445 return STATUS_NO_MEMORY;
1448 if (!(data = IORegistryEntryCreateCFProperty(service, CFSTR("SMBIOS-EPS"), kCFAllocatorDefault, 0)))
1450 WARN("can't find SMBIOS entry point\n");
1451 IOObjectRelease(service);
1452 return STATUS_NO_MEMORY;
1455 len = CFDataGetLength(data);
1456 ptr = CFDataGetBytePtr(data);
1457 if (len >= 8 && !memcmp(ptr, "_SM_", 4))
1459 major_version = ptr[6];
1460 minor_version = ptr[7];
1462 CFRelease(data);
1464 if (!(data = IORegistryEntryCreateCFProperty(service, CFSTR("SMBIOS"), kCFAllocatorDefault, 0)))
1466 WARN("can't find SMBIOS table\n");
1467 IOObjectRelease(service);
1468 return STATUS_NO_MEMORY;
1471 len = CFDataGetLength(data);
1472 ptr = CFDataGetBytePtr(data);
1473 sfti->TableBufferLength = sizeof(*prologue) + len;
1474 *required_len = sfti->TableBufferLength + FIELD_OFFSET(SYSTEM_FIRMWARE_TABLE_INFORMATION, TableBuffer);
1475 if (available_len < *required_len)
1477 CFRelease(data);
1478 IOObjectRelease(service);
1479 return STATUS_BUFFER_TOO_SMALL;
1482 prologue = (struct smbios_prologue *)sfti->TableBuffer;
1483 prologue->calling_method = 0;
1484 prologue->major_version = major_version;
1485 prologue->minor_version = minor_version;
1486 prologue->revision = 0;
1487 prologue->length = sfti->TableBufferLength - sizeof(*prologue);
1489 memcpy(sfti->TableBuffer + sizeof(*prologue), ptr, len);
1491 CFRelease(data);
1492 IOObjectRelease(service);
1493 return STATUS_SUCCESS;
1495 default:
1496 FIXME("info_class SYSTEM_FIRMWARE_TABLE_INFORMATION provider %08x\n", sfti->ProviderSignature);
1497 return STATUS_NOT_IMPLEMENTED;
1501 #else
1503 static NTSTATUS get_firmware_info( SYSTEM_FIRMWARE_TABLE_INFORMATION *sfti, ULONG available_len,
1504 ULONG *required_len )
1506 FIXME("info_class SYSTEM_FIRMWARE_TABLE_INFORMATION\n");
1507 sfti->TableBufferLength = 0;
1508 return STATUS_NOT_IMPLEMENTED;
1511 #endif
1513 static void get_performance_info( SYSTEM_PERFORMANCE_INFORMATION *info )
1515 unsigned long long totalram = 0, freeram = 0, totalswap = 0, freeswap = 0;
1516 FILE *fp;
1518 memset( info, 0, sizeof(*info) );
1520 if ((fp = fopen("/proc/uptime", "r")))
1522 double uptime, idle_time;
1524 fscanf(fp, "%lf %lf", &uptime, &idle_time);
1525 fclose(fp);
1526 info->IdleTime.QuadPart = 10000000 * idle_time;
1528 else
1530 static ULONGLONG idle;
1531 /* many programs expect IdleTime to change so fake change */
1532 info->IdleTime.QuadPart = ++idle;
1535 #ifdef linux
1536 if ((fp = fopen("/proc/meminfo", "r")))
1538 unsigned long long value;
1539 char line[64];
1541 while (fgets(line, sizeof(line), fp))
1543 if(sscanf(line, "MemTotal: %llu kB", &value) == 1)
1544 totalram += value * 1024;
1545 else if(sscanf(line, "MemFree: %llu kB", &value) == 1)
1546 freeram += value * 1024;
1547 else if(sscanf(line, "SwapTotal: %llu kB", &value) == 1)
1548 totalswap += value * 1024;
1549 else if(sscanf(line, "SwapFree: %llu kB", &value) == 1)
1550 freeswap += value * 1024;
1551 else if (sscanf(line, "Buffers: %llu", &value))
1552 freeram += value * 1024;
1553 else if (sscanf(line, "Cached: %llu", &value))
1554 freeram += value * 1024;
1556 fclose(fp);
1558 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || \
1559 defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
1561 #ifdef __APPLE__
1562 unsigned int val;
1563 #else
1564 unsigned long val;
1565 #endif
1566 int mib[2];
1567 size_t size_sys;
1569 mib[0] = CTL_HW;
1570 #ifdef HW_MEMSIZE
1572 uint64_t val64;
1573 mib[1] = HW_MEMSIZE;
1574 size_sys = sizeof(val64);
1575 if (!sysctl(mib, 2, &val64, &size_sys, NULL, 0) && size_sys == sizeof(val64)) totalram = val64;
1577 #endif
1579 #ifdef HAVE_MACH_MACH_H
1581 host_name_port_t host = mach_host_self();
1582 mach_msg_type_number_t count;
1583 #ifdef HOST_VM_INFO64_COUNT
1584 vm_statistics64_data_t vm_stat;
1586 count = HOST_VM_INFO64_COUNT;
1587 if (host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&vm_stat, &count) == KERN_SUCCESS)
1588 freeram = (vm_stat.free_count + vm_stat.inactive_count) * (ULONGLONG)page_size;
1589 #endif
1590 if (!totalram)
1592 host_basic_info_data_t info;
1593 count = HOST_BASIC_INFO_COUNT;
1594 if (host_info(host, HOST_BASIC_INFO, (host_info_t)&info, &count) == KERN_SUCCESS)
1595 totalram = info.max_mem;
1597 mach_port_deallocate(mach_task_self(), host);
1599 #endif
1601 if (!totalram)
1603 mib[1] = HW_PHYSMEM;
1604 size_sys = sizeof(val);
1605 if (!sysctl(mib, 2, &val, &size_sys, NULL, 0) && size_sys == sizeof(val)) totalram = val;
1607 if (!freeram)
1609 mib[1] = HW_USERMEM;
1610 size_sys = sizeof(val);
1611 if (!sysctl(mib, 2, &val, &size_sys, NULL, 0) && size_sys == sizeof(val)) freeram = val;
1613 #ifdef VM_SWAPUSAGE
1615 struct xsw_usage swap;
1616 mib[0] = CTL_VM;
1617 mib[1] = VM_SWAPUSAGE;
1618 size_sys = sizeof(swap);
1619 if (!sysctl(mib, 2, &swap, &size_sys, NULL, 0) && size_sys == sizeof(swap))
1621 totalswap = swap.xsu_total;
1622 freeswap = swap.xsu_avail;
1625 #endif
1627 #endif
1628 info->AvailablePages = freeram / page_size;
1629 info->TotalCommittedPages = (totalram + totalswap - freeram - freeswap) / page_size;
1630 info->TotalCommitLimit = (totalram + totalswap) / page_size;
1634 /* calculate the mday of dst change date, so that for instance Sun 5 Oct 2007
1635 * (last Sunday in October of 2007) becomes Sun Oct 28 2007
1637 * Note: year, day and month must be in unix format.
1639 static int weekday_to_mday(int year, int day, int mon, int day_of_week)
1641 struct tm date;
1642 time_t tmp;
1643 int wday, mday;
1645 /* find first day in the month matching week day of the date */
1646 memset(&date, 0, sizeof(date));
1647 date.tm_year = year;
1648 date.tm_mon = mon;
1649 date.tm_mday = -1;
1650 date.tm_wday = -1;
1653 date.tm_mday++;
1654 tmp = mktime(&date);
1655 } while (date.tm_wday != day_of_week || date.tm_mon != mon);
1657 mday = date.tm_mday;
1659 /* find number of week days in the month matching week day of the date */
1660 wday = 1; /* 1 - 1st, ...., 5 - last */
1661 while (wday < day)
1663 struct tm *tm;
1665 date.tm_mday += 7;
1666 tmp = mktime(&date);
1667 tm = localtime(&tmp);
1668 if (tm->tm_mon != mon)
1669 break;
1670 mday = tm->tm_mday;
1671 wday++;
1674 return mday;
1677 static BOOL match_tz_date( const RTL_SYSTEM_TIME *st, const RTL_SYSTEM_TIME *reg_st )
1679 WORD wDay;
1681 if (st->wMonth != reg_st->wMonth) return FALSE;
1682 if (!st->wMonth) return TRUE; /* no transition dates */
1683 wDay = reg_st->wDay;
1684 if (!reg_st->wYear) /* date in a day-of-week format */
1685 wDay = weekday_to_mday(st->wYear - 1900, reg_st->wDay, reg_st->wMonth - 1, reg_st->wDayOfWeek);
1687 return (st->wDay == wDay &&
1688 st->wHour == reg_st->wHour &&
1689 st->wMinute == reg_st->wMinute &&
1690 st->wSecond == reg_st->wSecond &&
1691 st->wMilliseconds == reg_st->wMilliseconds);
1694 static BOOL match_tz_info( const RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi,
1695 const RTL_DYNAMIC_TIME_ZONE_INFORMATION *reg_tzi )
1697 return (tzi->Bias == reg_tzi->Bias &&
1698 match_tz_date(&tzi->StandardDate, &reg_tzi->StandardDate) &&
1699 match_tz_date(&tzi->DaylightDate, &reg_tzi->DaylightDate));
1702 static BOOL match_tz_name( const char *tz_name, const RTL_DYNAMIC_TIME_ZONE_INFORMATION *reg_tzi )
1704 static const struct { WCHAR key_name[32]; const char *short_name; } mapping[] =
1706 { {'K','o','r','e','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',0 },
1707 "KST" },
1708 { {'T','o','k','y','o',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',0 },
1709 "JST" },
1710 { {'Y','a','k','u','t','s','k',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',0 },
1711 "+09" }, /* YAKST was used until tzdata 2016f */
1713 unsigned int i;
1715 if (reg_tzi->DaylightDate.wMonth) return TRUE;
1716 for (i = 0; i < ARRAY_SIZE(mapping); i++)
1718 if (!wcscmp( mapping[i].key_name, reg_tzi->TimeZoneKeyName ))
1719 return !strcmp( mapping[i].short_name, tz_name );
1721 return TRUE;
1724 static BOOL reg_query_value( HKEY key, LPCWSTR name, DWORD type, void *data, DWORD count )
1726 char buf[256];
1727 UNICODE_STRING nameW;
1728 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buf;
1730 if (count > sizeof(buf) - sizeof(KEY_VALUE_PARTIAL_INFORMATION)) return FALSE;
1732 RtlInitUnicodeString( &nameW, name );
1733 if (NtQueryValueKey( key, &nameW, KeyValuePartialInformation, buf, sizeof(buf), &count ))
1734 return FALSE;
1736 if (info->Type != type) return FALSE;
1737 memcpy( data, info->Data, info->DataLength );
1738 return TRUE;
1741 static void find_reg_tz_info(RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi, const char* tz_name, int year)
1743 static const WCHAR stdW[] = { 'S','t','d',0 };
1744 static const WCHAR dltW[] = { 'D','l','t',0 };
1745 static const WCHAR mui_stdW[] = { 'M','U','I','_','S','t','d',0 };
1746 static const WCHAR mui_dltW[] = { 'M','U','I','_','D','l','t',0 };
1747 static const WCHAR tziW[] = { 'T','Z','I',0 };
1748 static const WCHAR Time_ZonesW[] = { 'M','a','c','h','i','n','e','\\',
1749 'S','o','f','t','w','a','r','e','\\',
1750 'M','i','c','r','o','s','o','f','t','\\',
1751 'W','i','n','d','o','w','s',' ','N','T','\\',
1752 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
1753 'T','i','m','e',' ','Z','o','n','e','s',0 };
1754 static const WCHAR Dynamic_DstW[] = { 'D','y','n','a','m','i','c',' ','D','S','T',0 };
1755 RTL_DYNAMIC_TIME_ZONE_INFORMATION reg_tzi;
1756 HANDLE key, subkey, subkey_dyn = 0;
1757 ULONG idx, len;
1758 OBJECT_ATTRIBUTES attr;
1759 UNICODE_STRING nameW, nameDynamicW;
1760 WCHAR yearW[16];
1761 char buffer[128];
1762 KEY_BASIC_INFORMATION *info = (KEY_BASIC_INFORMATION *)buffer;
1764 sprintf( buffer, "%u", year );
1765 ascii_to_unicode( yearW, buffer, strlen(buffer) + 1 );
1767 RtlInitUnicodeString( &nameW, Time_ZonesW );
1768 RtlInitUnicodeString( &nameDynamicW, Dynamic_DstW );
1770 InitializeObjectAttributes( &attr, &nameW, 0, 0, NULL );
1771 if (NtOpenKey( &key, KEY_READ, &attr )) return;
1773 idx = 0;
1774 while (!NtEnumerateKey( key, idx++, KeyBasicInformation, buffer, sizeof(buffer), &len ))
1776 struct tz_reg_data
1778 LONG bias;
1779 LONG std_bias;
1780 LONG dlt_bias;
1781 RTL_SYSTEM_TIME std_date;
1782 RTL_SYSTEM_TIME dlt_date;
1783 } tz_data;
1784 BOOL is_dynamic = FALSE;
1786 nameW.Buffer = info->Name;
1787 nameW.Length = info->NameLength;
1788 InitializeObjectAttributes( &attr, &nameW, 0, key, NULL );
1789 if (NtOpenKey( &subkey, KEY_READ, &attr )) continue;
1791 memset( &reg_tzi, 0, sizeof(reg_tzi) );
1792 memcpy(reg_tzi.TimeZoneKeyName, nameW.Buffer, nameW.Length);
1793 reg_tzi.TimeZoneKeyName[nameW.Length/sizeof(WCHAR)] = 0;
1795 if (!reg_query_value(subkey, mui_stdW, REG_SZ, reg_tzi.StandardName, sizeof(reg_tzi.StandardName)) &&
1796 !reg_query_value(subkey, stdW, REG_SZ, reg_tzi.StandardName, sizeof(reg_tzi.StandardName)))
1797 goto next;
1799 if (!reg_query_value(subkey, mui_dltW, REG_SZ, reg_tzi.DaylightName, sizeof(reg_tzi.DaylightName)) &&
1800 !reg_query_value(subkey, dltW, REG_SZ, reg_tzi.DaylightName, sizeof(reg_tzi.DaylightName)))
1801 goto next;
1803 /* Check for Dynamic DST entry first */
1804 InitializeObjectAttributes( &attr, &nameDynamicW, 0, subkey, NULL );
1805 if (!NtOpenKey( &subkey_dyn, KEY_READ, &attr ))
1807 is_dynamic = reg_query_value( subkey_dyn, yearW, REG_BINARY, &tz_data, sizeof(tz_data) );
1808 NtClose( subkey_dyn );
1810 if (!is_dynamic && !reg_query_value( subkey, tziW, REG_BINARY, &tz_data, sizeof(tz_data) ))
1811 goto next;
1813 reg_tzi.Bias = tz_data.bias;
1814 reg_tzi.StandardBias = tz_data.std_bias;
1815 reg_tzi.DaylightBias = tz_data.dlt_bias;
1816 reg_tzi.StandardDate = tz_data.std_date;
1817 reg_tzi.DaylightDate = tz_data.dlt_date;
1819 TRACE("%s: bias %d\n", debugstr_us(&nameW), reg_tzi.Bias);
1820 TRACE("std (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
1821 reg_tzi.StandardDate.wDay, reg_tzi.StandardDate.wMonth,
1822 reg_tzi.StandardDate.wYear, reg_tzi.StandardDate.wDayOfWeek,
1823 reg_tzi.StandardDate.wHour, reg_tzi.StandardDate.wMinute,
1824 reg_tzi.StandardDate.wSecond, reg_tzi.StandardDate.wMilliseconds,
1825 reg_tzi.StandardBias);
1826 TRACE("dst (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
1827 reg_tzi.DaylightDate.wDay, reg_tzi.DaylightDate.wMonth,
1828 reg_tzi.DaylightDate.wYear, reg_tzi.DaylightDate.wDayOfWeek,
1829 reg_tzi.DaylightDate.wHour, reg_tzi.DaylightDate.wMinute,
1830 reg_tzi.DaylightDate.wSecond, reg_tzi.DaylightDate.wMilliseconds,
1831 reg_tzi.DaylightBias);
1833 if (match_tz_info( tzi, &reg_tzi ) && match_tz_name( tz_name, &reg_tzi ))
1835 *tzi = reg_tzi;
1836 NtClose( subkey );
1837 NtClose( key );
1838 return;
1840 next:
1841 NtClose( subkey );
1843 NtClose( key );
1845 if (idx == 1) return; /* registry info not initialized yet */
1847 FIXME("Can't find matching timezone information in the registry for "
1848 "%s, bias %d, std (d/m/y): %u/%02u/%04u, dlt (d/m/y): %u/%02u/%04u\n",
1849 tz_name, tzi->Bias,
1850 tzi->StandardDate.wDay, tzi->StandardDate.wMonth, tzi->StandardDate.wYear,
1851 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth, tzi->DaylightDate.wYear);
1854 static time_t find_dst_change(unsigned long min, unsigned long max, int *is_dst)
1856 time_t start;
1857 struct tm *tm;
1859 start = min;
1860 tm = localtime(&start);
1861 *is_dst = !tm->tm_isdst;
1862 TRACE("starting date isdst %d, %s", !*is_dst, ctime(&start));
1864 while (min <= max)
1866 time_t pos = (min + max) / 2;
1867 tm = localtime(&pos);
1869 if (tm->tm_isdst != *is_dst)
1870 min = pos + 1;
1871 else
1872 max = pos - 1;
1874 return min;
1877 static RTL_CRITICAL_SECTION TIME_tz_section;
1878 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
1880 0, 0, &TIME_tz_section,
1881 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
1882 0, 0, { (DWORD_PTR)(__FILE__ ": TIME_tz_section") }
1884 static RTL_CRITICAL_SECTION TIME_tz_section = { &critsect_debug, -1, 0, 0, 0, 0 };
1886 static void get_timezone_info( RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi )
1888 static RTL_DYNAMIC_TIME_ZONE_INFORMATION cached_tzi;
1889 static int current_year = -1, current_bias = 65535;
1890 struct tm *tm;
1891 char tz_name[16];
1892 time_t year_start, year_end, tmp, dlt = 0, std = 0;
1893 int is_dst, bias;
1895 RtlEnterCriticalSection( &TIME_tz_section );
1897 year_start = time(NULL);
1898 tm = gmtime(&year_start);
1899 bias = (LONG)(mktime(tm) - year_start) / 60;
1901 tm = localtime(&year_start);
1902 if (current_year == tm->tm_year && current_bias == bias)
1904 *tzi = cached_tzi;
1905 RtlLeaveCriticalSection( &TIME_tz_section );
1906 return;
1909 memset(tzi, 0, sizeof(*tzi));
1910 if (!strftime(tz_name, sizeof(tz_name), "%Z", tm)) {
1911 /* not enough room or another error */
1912 tz_name[0] = '\0';
1915 TRACE("tz data will be valid through year %d, bias %d\n", tm->tm_year + 1900, bias);
1916 current_year = tm->tm_year;
1917 current_bias = bias;
1919 tzi->Bias = bias;
1921 tm->tm_isdst = 0;
1922 tm->tm_mday = 1;
1923 tm->tm_mon = tm->tm_hour = tm->tm_min = tm->tm_sec = tm->tm_wday = tm->tm_yday = 0;
1924 year_start = mktime(tm);
1925 TRACE("year_start: %s", ctime(&year_start));
1927 tm->tm_mday = tm->tm_wday = tm->tm_yday = 0;
1928 tm->tm_mon = 12;
1929 tm->tm_hour = 23;
1930 tm->tm_min = tm->tm_sec = 59;
1931 year_end = mktime(tm);
1932 TRACE("year_end: %s", ctime(&year_end));
1934 tmp = find_dst_change(year_start, year_end, &is_dst);
1935 if (is_dst)
1936 dlt = tmp;
1937 else
1938 std = tmp;
1940 tmp = find_dst_change(tmp, year_end, &is_dst);
1941 if (is_dst)
1942 dlt = tmp;
1943 else
1944 std = tmp;
1946 TRACE("std: %s", ctime(&std));
1947 TRACE("dlt: %s", ctime(&dlt));
1949 if (dlt == std || !dlt || !std)
1950 TRACE("there is no daylight saving rules in this time zone\n");
1951 else
1953 tmp = dlt - tzi->Bias * 60;
1954 tm = gmtime(&tmp);
1955 TRACE("dlt gmtime: %s", asctime(tm));
1957 tzi->DaylightBias = -60;
1958 tzi->DaylightDate.wYear = tm->tm_year + 1900;
1959 tzi->DaylightDate.wMonth = tm->tm_mon + 1;
1960 tzi->DaylightDate.wDayOfWeek = tm->tm_wday;
1961 tzi->DaylightDate.wDay = tm->tm_mday;
1962 tzi->DaylightDate.wHour = tm->tm_hour;
1963 tzi->DaylightDate.wMinute = tm->tm_min;
1964 tzi->DaylightDate.wSecond = tm->tm_sec;
1965 tzi->DaylightDate.wMilliseconds = 0;
1967 TRACE("daylight (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
1968 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth,
1969 tzi->DaylightDate.wYear, tzi->DaylightDate.wDayOfWeek,
1970 tzi->DaylightDate.wHour, tzi->DaylightDate.wMinute,
1971 tzi->DaylightDate.wSecond, tzi->DaylightDate.wMilliseconds,
1972 tzi->DaylightBias);
1974 tmp = std - tzi->Bias * 60 - tzi->DaylightBias * 60;
1975 tm = gmtime(&tmp);
1976 TRACE("std gmtime: %s", asctime(tm));
1978 tzi->StandardBias = 0;
1979 tzi->StandardDate.wYear = tm->tm_year + 1900;
1980 tzi->StandardDate.wMonth = tm->tm_mon + 1;
1981 tzi->StandardDate.wDayOfWeek = tm->tm_wday;
1982 tzi->StandardDate.wDay = tm->tm_mday;
1983 tzi->StandardDate.wHour = tm->tm_hour;
1984 tzi->StandardDate.wMinute = tm->tm_min;
1985 tzi->StandardDate.wSecond = tm->tm_sec;
1986 tzi->StandardDate.wMilliseconds = 0;
1988 TRACE("standard (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
1989 tzi->StandardDate.wDay, tzi->StandardDate.wMonth,
1990 tzi->StandardDate.wYear, tzi->StandardDate.wDayOfWeek,
1991 tzi->StandardDate.wHour, tzi->StandardDate.wMinute,
1992 tzi->StandardDate.wSecond, tzi->StandardDate.wMilliseconds,
1993 tzi->StandardBias);
1996 find_reg_tz_info(tzi, tz_name, current_year + 1900);
1997 cached_tzi = *tzi;
1998 RtlLeaveCriticalSection( &TIME_tz_section );
2002 /******************************************************************************
2003 * NtQuerySystemInformation (NTDLL.@)
2005 NTSTATUS WINAPI NtQuerySystemInformation( SYSTEM_INFORMATION_CLASS class,
2006 void *info, ULONG size, ULONG *ret_size )
2008 NTSTATUS ret = STATUS_SUCCESS;
2009 ULONG len = 0;
2011 TRACE( "(0x%08x,%p,0x%08x,%p)\n", class, info, size, ret_size );
2013 switch (class)
2015 case SystemBasicInformation:
2017 SYSTEM_BASIC_INFORMATION sbi;
2019 virtual_get_system_info( &sbi );
2020 len = sizeof(sbi);
2021 if (size == len)
2023 if (!info) ret = STATUS_ACCESS_VIOLATION;
2024 else memcpy( info, &sbi, len);
2026 else ret = STATUS_INFO_LENGTH_MISMATCH;
2027 break;
2030 case SystemCpuInformation:
2031 if (size >= (len = sizeof(cpu_info)))
2033 if (!info) ret = STATUS_ACCESS_VIOLATION;
2034 else memcpy(info, &cpu_info, len);
2036 else ret = STATUS_INFO_LENGTH_MISMATCH;
2037 break;
2039 case SystemPerformanceInformation:
2041 SYSTEM_PERFORMANCE_INFORMATION spi;
2042 static BOOL fixme_written = FALSE;
2044 get_performance_info( &spi );
2045 len = sizeof(spi);
2046 if (size >= len)
2048 if (!info) ret = STATUS_ACCESS_VIOLATION;
2049 else memcpy( info, &spi, len);
2051 else ret = STATUS_INFO_LENGTH_MISMATCH;
2052 if(!fixme_written) {
2053 FIXME("info_class SYSTEM_PERFORMANCE_INFORMATION\n");
2054 fixme_written = TRUE;
2056 break;
2059 case SystemTimeOfDayInformation:
2061 struct tm *tm;
2062 time_t now;
2063 SYSTEM_TIMEOFDAY_INFORMATION sti = {{{ 0 }}};
2065 sti.BootTime.QuadPart = server_start_time;
2066 now = time( NULL );
2067 tm = gmtime( &now );
2068 sti.TimeZoneBias.QuadPart = mktime( tm ) - now;
2069 tm = localtime( &now );
2070 if (tm->tm_isdst) sti.TimeZoneBias.QuadPart -= 3600;
2071 sti.TimeZoneBias.QuadPart *= TICKSPERSEC;
2072 NtQuerySystemTime( &sti.SystemTime );
2074 if (size <= sizeof(sti))
2076 len = size;
2077 if (!info) ret = STATUS_ACCESS_VIOLATION;
2078 else memcpy( info, &sti, size);
2080 else ret = STATUS_INFO_LENGTH_MISMATCH;
2081 break;
2084 case SystemProcessInformation:
2086 unsigned int process_count, i, j;
2087 char *buffer = NULL;
2088 unsigned int pos = 0;
2090 if (size && !(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2092 ret = STATUS_NO_MEMORY;
2093 break;
2096 SERVER_START_REQ( list_processes )
2098 wine_server_set_reply( req, buffer, size );
2099 ret = wine_server_call( req );
2100 len = reply->info_size;
2101 process_count = reply->process_count;
2103 SERVER_END_REQ;
2105 if (ret)
2107 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2108 break;
2111 len = 0;
2113 for (i = 0; i < process_count; i++)
2115 SYSTEM_PROCESS_INFORMATION *nt_process = (SYSTEM_PROCESS_INFORMATION *)((char *)info + len);
2116 const struct process_info *server_process;
2117 const WCHAR *server_name, *file_part;
2118 ULONG proc_len;
2119 ULONG name_len = 0;
2121 pos = (pos + 7) & ~7;
2122 server_process = (const struct process_info *)(buffer + pos);
2123 pos += sizeof(*server_process);
2125 server_name = (const WCHAR *)(buffer + pos);
2126 file_part = server_name + (server_process->name_len / sizeof(WCHAR));
2127 pos += server_process->name_len;
2128 while (file_part > server_name && file_part[-1] != '\\')
2130 file_part--;
2131 name_len++;
2134 proc_len = sizeof(*nt_process) + server_process->thread_count * sizeof(SYSTEM_THREAD_INFORMATION)
2135 + (name_len + 1) * sizeof(WCHAR);
2136 len += proc_len;
2138 if (len <= size)
2140 memset(nt_process, 0, sizeof(*nt_process));
2141 if (i < process_count - 1)
2142 nt_process->NextEntryOffset = proc_len;
2143 nt_process->CreationTime.QuadPart = server_process->start_time;
2144 nt_process->dwThreadCount = server_process->thread_count;
2145 nt_process->dwBasePriority = server_process->priority;
2146 nt_process->UniqueProcessId = UlongToHandle(server_process->pid);
2147 nt_process->ParentProcessId = UlongToHandle(server_process->parent_pid);
2148 nt_process->HandleCount = server_process->handle_count;
2149 get_thread_times( server_process->unix_pid, -1, &nt_process->KernelTime, &nt_process->UserTime );
2150 fill_vm_counters( &nt_process->vmCounters, server_process->unix_pid );
2153 pos = (pos + 7) & ~7;
2154 for (j = 0; j < server_process->thread_count; j++)
2156 const struct thread_info *server_thread = (const struct thread_info *)(buffer + pos);
2158 if (len <= size)
2160 nt_process->ti[j].CreateTime.QuadPart = server_thread->start_time;
2161 nt_process->ti[j].ClientId.UniqueProcess = UlongToHandle(server_process->pid);
2162 nt_process->ti[j].ClientId.UniqueThread = UlongToHandle(server_thread->tid);
2163 nt_process->ti[j].dwCurrentPriority = server_thread->current_priority;
2164 nt_process->ti[j].dwBasePriority = server_thread->base_priority;
2165 get_thread_times( server_process->unix_pid, server_thread->unix_tid,
2166 &nt_process->ti[j].KernelTime, &nt_process->ti[j].UserTime );
2169 pos += sizeof(*server_thread);
2172 if (len <= size)
2174 nt_process->ProcessName.Buffer = (WCHAR *)&nt_process->ti[server_process->thread_count];
2175 nt_process->ProcessName.Length = name_len * sizeof(WCHAR);
2176 nt_process->ProcessName.MaximumLength = (name_len + 1) * sizeof(WCHAR);
2177 memcpy(nt_process->ProcessName.Buffer, file_part, name_len * sizeof(WCHAR));
2178 nt_process->ProcessName.Buffer[name_len] = 0;
2182 if (len > size) ret = STATUS_INFO_LENGTH_MISMATCH;
2183 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2184 break;
2187 case SystemProcessorPerformanceInformation:
2189 SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi = NULL;
2190 unsigned int cpus = 0;
2191 int out_cpus = size / sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION);
2193 if (out_cpus == 0)
2195 len = 0;
2196 ret = STATUS_INFO_LENGTH_MISMATCH;
2197 break;
2199 else
2200 #ifdef __APPLE__
2202 processor_cpu_load_info_data_t *pinfo;
2203 mach_msg_type_number_t info_count;
2205 if (host_processor_info( mach_host_self (),
2206 PROCESSOR_CPU_LOAD_INFO,
2207 &cpus,
2208 (processor_info_array_t*)&pinfo,
2209 &info_count) == 0)
2211 int i;
2212 cpus = min(cpus,out_cpus);
2213 len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
2214 sppi = RtlAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, len);
2215 for (i = 0; i < cpus; i++)
2217 sppi[i].IdleTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_IDLE];
2218 sppi[i].KernelTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_SYSTEM];
2219 sppi[i].UserTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_USER];
2221 vm_deallocate (mach_task_self (), (vm_address_t) pinfo, info_count * sizeof(natural_t));
2224 #else
2226 FILE *cpuinfo = fopen("/proc/stat", "r");
2227 if (cpuinfo)
2229 unsigned long clk_tck = sysconf(_SC_CLK_TCK);
2230 unsigned long usr,nice,sys,idle,remainder[8];
2231 int i, count;
2232 char name[32];
2233 char line[255];
2235 /* first line is combined usage */
2236 while (fgets(line,255,cpuinfo))
2238 count = sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2239 name, &usr, &nice, &sys, &idle,
2240 &remainder[0], &remainder[1], &remainder[2], &remainder[3],
2241 &remainder[4], &remainder[5], &remainder[6], &remainder[7]);
2243 if (count < 5 || strncmp( name, "cpu", 3 )) break;
2244 for (i = 0; i + 5 < count; ++i) sys += remainder[i];
2245 sys += idle;
2246 usr += nice;
2247 cpus = atoi( name + 3 ) + 1;
2248 if (cpus > out_cpus) break;
2249 len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
2250 if (sppi)
2251 sppi = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sppi, len );
2252 else
2253 sppi = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, len );
2255 sppi[cpus-1].IdleTime.QuadPart = (ULONGLONG)idle * 10000000 / clk_tck;
2256 sppi[cpus-1].KernelTime.QuadPart = (ULONGLONG)sys * 10000000 / clk_tck;
2257 sppi[cpus-1].UserTime.QuadPart = (ULONGLONG)usr * 10000000 / clk_tck;
2259 fclose(cpuinfo);
2262 #endif
2263 if (cpus == 0)
2265 static int i = 1;
2266 unsigned int n;
2267 cpus = min(NtCurrentTeb()->Peb->NumberOfProcessors, out_cpus);
2268 len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
2269 sppi = RtlAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, len);
2270 FIXME("stub info_class SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION\n");
2271 /* many programs expect these values to change so fake change */
2272 for (n = 0; n < cpus; n++)
2274 sppi[n].KernelTime.QuadPart = 1 * i;
2275 sppi[n].UserTime.QuadPart = 2 * i;
2276 sppi[n].IdleTime.QuadPart = 3 * i;
2278 i++;
2281 if (size >= len)
2283 if (!info) ret = STATUS_ACCESS_VIOLATION;
2284 else memcpy( info, sppi, len);
2286 else ret = STATUS_INFO_LENGTH_MISMATCH;
2288 RtlFreeHeap(GetProcessHeap(),0,sppi);
2289 break;
2292 case SystemModuleInformation:
2293 /* FIXME: should be system-wide */
2294 if (!info) ret = STATUS_ACCESS_VIOLATION;
2295 else ret = LdrQueryProcessModuleInformation( info, size, &len );
2296 break;
2298 case SystemHandleInformation:
2300 struct handle_info *handle_info;
2301 DWORD i, num_handles;
2303 if (size < sizeof(SYSTEM_HANDLE_INFORMATION))
2305 ret = STATUS_INFO_LENGTH_MISMATCH;
2306 break;
2309 if (!info)
2311 ret = STATUS_ACCESS_VIOLATION;
2312 break;
2315 num_handles = (size - FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION, Handle )) / sizeof(SYSTEM_HANDLE_ENTRY);
2316 if (!(handle_info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*handle_info) * num_handles )))
2317 return STATUS_NO_MEMORY;
2319 SERVER_START_REQ( get_system_handles )
2321 wine_server_set_reply( req, handle_info, sizeof(*handle_info) * num_handles );
2322 if (!(ret = wine_server_call( req )))
2324 SYSTEM_HANDLE_INFORMATION *shi = info;
2325 shi->Count = wine_server_reply_size( req ) / sizeof(*handle_info);
2326 len = FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION, Handle[shi->Count] );
2327 for (i = 0; i < shi->Count; i++)
2329 memset( &shi->Handle[i], 0, sizeof(shi->Handle[i]) );
2330 shi->Handle[i].OwnerPid = handle_info[i].owner;
2331 shi->Handle[i].HandleValue = handle_info[i].handle;
2332 shi->Handle[i].AccessMask = handle_info[i].access;
2333 /* FIXME: Fill out ObjectType, HandleFlags, ObjectPointer */
2336 else if (ret == STATUS_BUFFER_TOO_SMALL)
2338 len = FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION, Handle[reply->count] );
2339 ret = STATUS_INFO_LENGTH_MISMATCH;
2342 SERVER_END_REQ;
2344 RtlFreeHeap( GetProcessHeap(), 0, handle_info );
2345 break;
2348 case SystemCacheInformation:
2350 SYSTEM_CACHE_INFORMATION sci = { 0 };
2352 len = sizeof(sci);
2353 if (size >= len)
2355 if (!info) ret = STATUS_ACCESS_VIOLATION;
2356 else memcpy( info, &sci, len);
2358 else ret = STATUS_INFO_LENGTH_MISMATCH;
2359 FIXME("info_class SYSTEM_CACHE_INFORMATION\n");
2360 break;
2363 case SystemInterruptInformation:
2365 SYSTEM_INTERRUPT_INFORMATION sii = {{ 0 }};
2367 len = sizeof(sii);
2368 if (size >= len)
2370 if (!info) ret = STATUS_ACCESS_VIOLATION;
2371 else memcpy( info, &sii, len);
2373 else ret = STATUS_INFO_LENGTH_MISMATCH;
2374 FIXME("info_class SYSTEM_INTERRUPT_INFORMATION\n");
2375 break;
2378 case SystemTimeAdjustmentInformation:
2380 SYSTEM_TIME_ADJUSTMENT_QUERY query = { 156250, 156250, TRUE };
2382 len = sizeof(query);
2383 if (size == len)
2385 if (!info) ret = STATUS_ACCESS_VIOLATION;
2386 else memcpy( info, &query, len );
2388 else ret = STATUS_INFO_LENGTH_MISMATCH;
2389 break;
2392 case SystemKernelDebuggerInformation:
2394 SYSTEM_KERNEL_DEBUGGER_INFORMATION skdi;
2396 skdi.DebuggerEnabled = FALSE;
2397 skdi.DebuggerNotPresent = TRUE;
2398 len = sizeof(skdi);
2399 if (size >= len)
2401 if (!info) ret = STATUS_ACCESS_VIOLATION;
2402 else memcpy( info, &skdi, len);
2404 else ret = STATUS_INFO_LENGTH_MISMATCH;
2405 break;
2408 case SystemRegistryQuotaInformation:
2410 /* Something to do with the size of the registry *
2411 * Since we don't have a size limitation, fake it *
2412 * This is almost certainly wrong. *
2413 * This sets each of the three words in the struct to 32 MB, *
2414 * which is enough to make the IE 5 installer happy. */
2415 SYSTEM_REGISTRY_QUOTA_INFORMATION srqi;
2417 srqi.RegistryQuotaAllowed = 0x2000000;
2418 srqi.RegistryQuotaUsed = 0x200000;
2419 srqi.Reserved1 = (void*)0x200000;
2420 len = sizeof(srqi);
2422 if (size >= len)
2424 if (!info) ret = STATUS_ACCESS_VIOLATION;
2425 else
2427 FIXME("SystemRegistryQuotaInformation: faking max registry size of 32 MB\n");
2428 memcpy( info, &srqi, len);
2431 else ret = STATUS_INFO_LENGTH_MISMATCH;
2432 break;
2435 case SystemTimeZoneInformation:
2437 RTL_DYNAMIC_TIME_ZONE_INFORMATION tz;
2439 get_timezone_info( &tz );
2440 len = sizeof(RTL_TIME_ZONE_INFORMATION);
2441 if (size >= len)
2443 if (!info) ret = STATUS_ACCESS_VIOLATION;
2444 else memcpy( info, &tz, len);
2446 else ret = STATUS_INFO_LENGTH_MISMATCH;
2447 break;
2450 case SystemLogicalProcessorInformation:
2452 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *buf;
2454 /* Each logical processor may use up to 7 entries in returned table:
2455 * core, numa node, package, L1i, L1d, L2, L3 */
2456 len = 7 * NtCurrentTeb()->Peb->NumberOfProcessors;
2457 buf = RtlAllocateHeap(GetProcessHeap(), 0, len * sizeof(*buf));
2458 if (!buf)
2460 ret = STATUS_NO_MEMORY;
2461 break;
2464 ret = create_logical_proc_info(&buf, NULL, &len, RelationAll);
2465 if( ret != STATUS_SUCCESS )
2467 RtlFreeHeap(GetProcessHeap(), 0, buf);
2468 break;
2471 if (size >= len)
2473 if (!info) ret = STATUS_ACCESS_VIOLATION;
2474 else memcpy( info, buf, len);
2476 else ret = STATUS_INFO_LENGTH_MISMATCH;
2477 RtlFreeHeap(GetProcessHeap(), 0, buf);
2478 break;
2481 case SystemRecommendedSharedDataAlignment:
2483 len = sizeof(DWORD);
2484 if (size >= len)
2486 if (!info) ret = STATUS_ACCESS_VIOLATION;
2487 else
2489 #ifdef __arm__
2490 *((DWORD *)info) = 32;
2491 #else
2492 *((DWORD *)info) = 64;
2493 #endif
2496 else ret = STATUS_INFO_LENGTH_MISMATCH;
2497 break;
2500 case SystemFirmwareTableInformation:
2502 SYSTEM_FIRMWARE_TABLE_INFORMATION *sfti = info;
2503 len = FIELD_OFFSET(SYSTEM_FIRMWARE_TABLE_INFORMATION, TableBuffer);
2504 if (size < len)
2506 ret = STATUS_INFO_LENGTH_MISMATCH;
2507 break;
2510 switch (sfti->Action)
2512 case SystemFirmwareTable_Get:
2513 ret = get_firmware_info(sfti, size, &len);
2514 break;
2515 default:
2516 len = 0;
2517 ret = STATUS_NOT_IMPLEMENTED;
2518 FIXME("info_class SYSTEM_FIRMWARE_TABLE_INFORMATION action %d\n", sfti->Action);
2520 break;
2523 case SystemDynamicTimeZoneInformation:
2525 RTL_DYNAMIC_TIME_ZONE_INFORMATION tz;
2527 get_timezone_info( &tz );
2528 len = sizeof(tz);
2529 if (size >= len)
2531 if (!info) ret = STATUS_ACCESS_VIOLATION;
2532 else memcpy( info, &tz, len);
2534 else ret = STATUS_INFO_LENGTH_MISMATCH;
2535 break;
2538 default:
2539 FIXME( "(0x%08x,%p,0x%08x,%p) stub\n", class, info, size, ret_size );
2541 /* Several Information Classes are not implemented on Windows and return 2 different values
2542 * STATUS_NOT_IMPLEMENTED or STATUS_INVALID_INFO_CLASS
2543 * in 95% of the cases it's STATUS_INVALID_INFO_CLASS, so use this as the default
2545 ret = STATUS_INVALID_INFO_CLASS;
2548 if (ret_size) *ret_size = len;
2549 return ret;
2553 /******************************************************************************
2554 * NtQuerySystemInformationEx (NTDLL.@)
2556 NTSTATUS WINAPI NtQuerySystemInformationEx( SYSTEM_INFORMATION_CLASS class,
2557 void *query, ULONG query_len,
2558 void *info, ULONG size, ULONG *ret_size )
2560 ULONG len = 0;
2561 NTSTATUS ret = STATUS_NOT_IMPLEMENTED;
2563 TRACE( "(0x%08x,%p,%u,%p,%u,%p) stub\n", class, query, query_len, info, size, ret_size );
2565 switch (class)
2567 case SystemLogicalProcessorInformationEx:
2569 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buf;
2571 if (!query || query_len < sizeof(DWORD))
2573 ret = STATUS_INVALID_PARAMETER;
2574 break;
2577 len = 3 * sizeof(*buf);
2578 buf = RtlAllocateHeap(GetProcessHeap(), 0, len);
2579 if (!buf)
2581 ret = STATUS_NO_MEMORY;
2582 break;
2585 ret = create_logical_proc_info(NULL, &buf, &len, *(DWORD *)query);
2586 if (ret != STATUS_SUCCESS)
2588 RtlFreeHeap(GetProcessHeap(), 0, buf);
2589 break;
2592 if (size >= len)
2594 if (!info) ret = STATUS_ACCESS_VIOLATION;
2595 else memcpy(info, buf, len);
2597 else
2598 ret = STATUS_INFO_LENGTH_MISMATCH;
2600 RtlFreeHeap(GetProcessHeap(), 0, buf);
2601 break;
2604 default:
2605 FIXME( "(0x%08x,%p,%u,%p,%u,%p) stub\n", class, query, query_len, info, size, ret_size );
2606 break;
2608 if (ret_size) *ret_size = len;
2609 return ret;
2613 #ifdef linux
2615 /* Fallback using /proc/cpuinfo for Linux systems without cpufreq. For
2616 * most distributions on recent enough hardware, this is only likely to
2617 * happen while running in virtualized environments such as QEMU. */
2618 static ULONG mhz_from_cpuinfo(void)
2620 char line[512];
2621 char *s, *value;
2622 double cmz = 0;
2623 FILE *f = fopen("/proc/cpuinfo", "r");
2624 if(f)
2626 while (fgets(line, sizeof(line), f) != NULL)
2628 if (!(value = strchr(line,':'))) continue;
2629 s = value - 1;
2630 while ((s >= line) && (*s == ' ' || *s == '\t')) s--;
2631 s[1] = 0;
2632 value++;
2633 if (!strcmp( line, "cpu MHz" ))
2635 sscanf(value, " %lf", &cmz);
2636 break;
2639 fclose( f );
2641 return cmz;
2644 static const char * get_sys_str(const char *path, char *s)
2646 FILE *f = fopen(path, "r");
2647 const char *ret = NULL;
2649 if (f)
2651 if (fgets(s, 16, f)) ret = s;
2652 fclose(f);
2654 return ret;
2657 static int get_sys_int(const char *path, int def)
2659 char s[16];
2660 return get_sys_str(path, s) ? atoi(s) : def;
2663 static NTSTATUS fill_battery_state( SYSTEM_BATTERY_STATE *bs )
2665 char s[16], path[64];
2666 unsigned int i = 0;
2667 LONG64 voltage; /* microvolts */
2669 bs->AcOnLine = get_sys_int("/sys/class/power_supply/AC/online", 1);
2671 for (;;)
2673 sprintf(path, "/sys/class/power_supply/BAT%u/status", i);
2674 if (!get_sys_str(path, s)) break;
2675 bs->Charging |= (strcmp(s, "Charging\n") == 0);
2676 bs->Discharging |= (strcmp(s, "Discharging\n") == 0);
2677 bs->BatteryPresent = TRUE;
2678 i++;
2681 if (bs->BatteryPresent)
2683 voltage = get_sys_int("/sys/class/power_supply/BAT0/voltage_now", 0);
2684 bs->MaxCapacity = get_sys_int("/sys/class/power_supply/BAT0/charge_full", 0) * voltage / 1e9;
2685 bs->RemainingCapacity = get_sys_int("/sys/class/power_supply/BAT0/charge_now", 0) * voltage / 1e9;
2686 bs->Rate = -get_sys_int("/sys/class/power_supply/BAT0/current_now", 0) * voltage / 1e9;
2687 if (!bs->Charging && (LONG)bs->Rate < 0)
2688 bs->EstimatedTime = 3600 * bs->RemainingCapacity / -(LONG)bs->Rate;
2689 else
2690 bs->EstimatedTime = ~0u;
2693 return STATUS_SUCCESS;
2696 #elif defined(HAVE_IOKIT_IOKITLIB_H)
2698 static NTSTATUS fill_battery_state( SYSTEM_BATTERY_STATE *bs )
2700 CFArrayRef batteries;
2701 CFDictionaryRef battery;
2702 CFNumberRef prop;
2703 uint32_t value, voltage;
2704 CFTimeInterval remain;
2706 if (IOPMCopyBatteryInfo( kIOMasterPortDefault, &batteries ) != kIOReturnSuccess)
2707 return STATUS_ACCESS_DENIED;
2709 if (CFArrayGetCount( batteries ) == 0)
2711 /* Just assume we're on AC with no battery. */
2712 bs->AcOnLine = TRUE;
2713 return STATUS_SUCCESS;
2715 /* Just use the first battery. */
2716 battery = CFArrayGetValueAtIndex( batteries, 0 );
2718 prop = CFDictionaryGetValue( battery, CFSTR(kIOBatteryFlagsKey) );
2719 CFNumberGetValue( prop, kCFNumberSInt32Type, &value );
2721 if (value & kIOBatteryInstalled)
2722 bs->BatteryPresent = TRUE;
2723 else
2724 /* Since we are executing code, we must have AC power. */
2725 bs->AcOnLine = TRUE;
2726 if (value & kIOBatteryChargerConnect)
2728 bs->AcOnLine = TRUE;
2729 if (value & kIOBatteryCharge)
2730 bs->Charging = TRUE;
2732 else
2733 bs->Discharging = TRUE;
2735 /* We'll need the voltage to be able to interpret the other values. */
2736 prop = CFDictionaryGetValue( battery, CFSTR(kIOBatteryVoltageKey) );
2737 CFNumberGetValue( prop, kCFNumberSInt32Type, &voltage );
2739 prop = CFDictionaryGetValue( battery, CFSTR(kIOBatteryCapacityKey) );
2740 CFNumberGetValue( prop, kCFNumberSInt32Type, &value );
2741 bs->MaxCapacity = value * voltage;
2742 /* Apple uses "estimated time < 10:00" and "22%" for these, but we'll follow
2743 * Windows for now (5% and 33%). */
2744 bs->DefaultAlert1 = bs->MaxCapacity / 20;
2745 bs->DefaultAlert2 = bs->MaxCapacity / 3;
2747 prop = CFDictionaryGetValue( battery, CFSTR(kIOBatteryCurrentChargeKey) );
2748 CFNumberGetValue( prop, kCFNumberSInt32Type, &value );
2749 bs->RemainingCapacity = value * voltage;
2751 prop = CFDictionaryGetValue( battery, CFSTR(kIOBatteryAmperageKey) );
2752 CFNumberGetValue( prop, kCFNumberSInt32Type, &value );
2753 bs->Rate = value * voltage;
2755 remain = IOPSGetTimeRemainingEstimate();
2756 if (remain != kIOPSTimeRemainingUnknown && remain != kIOPSTimeRemainingUnlimited)
2757 bs->EstimatedTime = (ULONG)remain;
2759 CFRelease( batteries );
2760 return STATUS_SUCCESS;
2763 #else
2765 static NTSTATUS fill_battery_state( SYSTEM_BATTERY_STATE *bs )
2767 FIXME("SystemBatteryState not implemented on this platform\n");
2768 return STATUS_NOT_IMPLEMENTED;
2771 #endif
2773 /******************************************************************************
2774 * NtPowerInformation (NTDLL.@)
2776 NTSTATUS WINAPI NtPowerInformation( POWER_INFORMATION_LEVEL level, void *input, ULONG in_size,
2777 void *output, ULONG out_size )
2779 TRACE( "(%d,%p,%d,%p,%d)\n", level, input, in_size, output, out_size );
2780 switch (level)
2782 case SystemPowerCapabilities:
2784 PSYSTEM_POWER_CAPABILITIES PowerCaps = output;
2785 FIXME("semi-stub: SystemPowerCapabilities\n");
2786 if (out_size < sizeof(SYSTEM_POWER_CAPABILITIES)) return STATUS_BUFFER_TOO_SMALL;
2787 /* FIXME: These values are based off a native XP desktop, should probably use APM/ACPI to get the 'real' values */
2788 PowerCaps->PowerButtonPresent = TRUE;
2789 PowerCaps->SleepButtonPresent = FALSE;
2790 PowerCaps->LidPresent = FALSE;
2791 PowerCaps->SystemS1 = TRUE;
2792 PowerCaps->SystemS2 = FALSE;
2793 PowerCaps->SystemS3 = FALSE;
2794 PowerCaps->SystemS4 = TRUE;
2795 PowerCaps->SystemS5 = TRUE;
2796 PowerCaps->HiberFilePresent = TRUE;
2797 PowerCaps->FullWake = TRUE;
2798 PowerCaps->VideoDimPresent = FALSE;
2799 PowerCaps->ApmPresent = FALSE;
2800 PowerCaps->UpsPresent = FALSE;
2801 PowerCaps->ThermalControl = FALSE;
2802 PowerCaps->ProcessorThrottle = FALSE;
2803 PowerCaps->ProcessorMinThrottle = 100;
2804 PowerCaps->ProcessorMaxThrottle = 100;
2805 PowerCaps->DiskSpinDown = TRUE;
2806 PowerCaps->SystemBatteriesPresent = FALSE;
2807 PowerCaps->BatteriesAreShortTerm = FALSE;
2808 PowerCaps->BatteryScale[0].Granularity = 0;
2809 PowerCaps->BatteryScale[0].Capacity = 0;
2810 PowerCaps->BatteryScale[1].Granularity = 0;
2811 PowerCaps->BatteryScale[1].Capacity = 0;
2812 PowerCaps->BatteryScale[2].Granularity = 0;
2813 PowerCaps->BatteryScale[2].Capacity = 0;
2814 PowerCaps->AcOnLineWake = PowerSystemUnspecified;
2815 PowerCaps->SoftLidWake = PowerSystemUnspecified;
2816 PowerCaps->RtcWake = PowerSystemSleeping1;
2817 PowerCaps->MinDeviceWakeState = PowerSystemUnspecified;
2818 PowerCaps->DefaultLowLatencyWake = PowerSystemUnspecified;
2819 return STATUS_SUCCESS;
2822 case SystemBatteryState:
2824 if (out_size < sizeof(SYSTEM_BATTERY_STATE)) return STATUS_BUFFER_TOO_SMALL;
2825 memset(output, 0, sizeof(SYSTEM_BATTERY_STATE));
2826 return fill_battery_state(output);
2829 case SystemExecutionState:
2831 ULONG *state = output;
2832 WARN("semi-stub: SystemExecutionState\n"); /* Needed for .NET Framework, but using a FIXME is really noisy. */
2833 if (input != NULL) return STATUS_INVALID_PARAMETER;
2834 /* FIXME: The actual state should be the value set by SetThreadExecutionState which is not currently implemented. */
2835 *state = ES_USER_PRESENT;
2836 return STATUS_SUCCESS;
2839 case ProcessorInformation:
2841 const int cannedMHz = 1000; /* We fake a 1GHz processor if we can't conjure up real values */
2842 PROCESSOR_POWER_INFORMATION* cpu_power = output;
2843 int i, out_cpus;
2845 if ((output == NULL) || (out_size == 0)) return STATUS_INVALID_PARAMETER;
2846 out_cpus = NtCurrentTeb()->Peb->NumberOfProcessors;
2847 if ((out_size / sizeof(PROCESSOR_POWER_INFORMATION)) < out_cpus) return STATUS_BUFFER_TOO_SMALL;
2848 #if defined(linux)
2850 char filename[128];
2851 FILE* f;
2853 for(i = 0; i < out_cpus; i++) {
2854 sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq", i);
2855 f = fopen(filename, "r");
2856 if (f && (fscanf(f, "%d", &cpu_power[i].CurrentMhz) == 1)) {
2857 cpu_power[i].CurrentMhz /= 1000;
2858 fclose(f);
2860 else {
2861 if(i == 0) {
2862 cpu_power[0].CurrentMhz = mhz_from_cpuinfo();
2863 if(cpu_power[0].CurrentMhz == 0)
2864 cpu_power[0].CurrentMhz = cannedMHz;
2866 else
2867 cpu_power[i].CurrentMhz = cpu_power[0].CurrentMhz;
2868 if(f) fclose(f);
2871 sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i);
2872 f = fopen(filename, "r");
2873 if (f && (fscanf(f, "%d", &cpu_power[i].MaxMhz) == 1)) {
2874 cpu_power[i].MaxMhz /= 1000;
2875 fclose(f);
2877 else {
2878 cpu_power[i].MaxMhz = cpu_power[i].CurrentMhz;
2879 if(f) fclose(f);
2882 sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq", i);
2883 f = fopen(filename, "r");
2884 if(f && (fscanf(f, "%d", &cpu_power[i].MhzLimit) == 1)) {
2885 cpu_power[i].MhzLimit /= 1000;
2886 fclose(f);
2888 else
2890 cpu_power[i].MhzLimit = cpu_power[i].MaxMhz;
2891 if(f) fclose(f);
2894 cpu_power[i].Number = i;
2895 cpu_power[i].MaxIdleState = 0; /* FIXME */
2896 cpu_power[i].CurrentIdleState = 0; /* FIXME */
2899 #elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__DragonFly__)
2901 int num;
2902 size_t valSize = sizeof(num);
2903 if (sysctlbyname("hw.clockrate", &num, &valSize, NULL, 0))
2904 num = cannedMHz;
2905 for(i = 0; i < out_cpus; i++) {
2906 cpu_power[i].CurrentMhz = num;
2907 cpu_power[i].MaxMhz = num;
2908 cpu_power[i].MhzLimit = num;
2909 cpu_power[i].Number = i;
2910 cpu_power[i].MaxIdleState = 0; /* FIXME */
2911 cpu_power[i].CurrentIdleState = 0; /* FIXME */
2914 #elif defined (__APPLE__)
2916 size_t valSize;
2917 unsigned long long currentMhz;
2918 unsigned long long maxMhz;
2920 valSize = sizeof(currentMhz);
2921 if (!sysctlbyname("hw.cpufrequency", &currentMhz, &valSize, NULL, 0))
2922 currentMhz /= 1000000;
2923 else
2924 currentMhz = cannedMHz;
2926 valSize = sizeof(maxMhz);
2927 if (!sysctlbyname("hw.cpufrequency_max", &maxMhz, &valSize, NULL, 0))
2928 maxMhz /= 1000000;
2929 else
2930 maxMhz = currentMhz;
2932 for(i = 0; i < out_cpus; i++) {
2933 cpu_power[i].CurrentMhz = currentMhz;
2934 cpu_power[i].MaxMhz = maxMhz;
2935 cpu_power[i].MhzLimit = maxMhz;
2936 cpu_power[i].Number = i;
2937 cpu_power[i].MaxIdleState = 0; /* FIXME */
2938 cpu_power[i].CurrentIdleState = 0; /* FIXME */
2941 #else
2942 for(i = 0; i < out_cpus; i++) {
2943 cpu_power[i].CurrentMhz = cannedMHz;
2944 cpu_power[i].MaxMhz = cannedMHz;
2945 cpu_power[i].MhzLimit = cannedMHz;
2946 cpu_power[i].Number = i;
2947 cpu_power[i].MaxIdleState = 0; /* FIXME */
2948 cpu_power[i].CurrentIdleState = 0; /* FIXME */
2950 WARN("Unable to detect CPU MHz for this platform. Reporting %d MHz.\n", cannedMHz);
2951 #endif
2952 for(i = 0; i < out_cpus; i++) {
2953 TRACE("cpu_power[%d] = %u %u %u %u %u %u\n", i, cpu_power[i].Number,
2954 cpu_power[i].MaxMhz, cpu_power[i].CurrentMhz, cpu_power[i].MhzLimit,
2955 cpu_power[i].MaxIdleState, cpu_power[i].CurrentIdleState);
2957 return STATUS_SUCCESS;
2960 default:
2961 /* FIXME: Needed by .NET Framework */
2962 WARN( "Unimplemented NtPowerInformation action: %d\n", level );
2963 return STATUS_NOT_IMPLEMENTED;