12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523 |
- /*++
- Copyright (c) 2012 Minoca Corp. All Rights Reserved
- Module Name:
- init.c
- Abstract:
- This module implements the kernel system startup.
- Author:
- Evan Green 2-Jul-2012
- Environment:
- Kernel Initialization
- --*/
- //
- // ------------------------------------------------------------------- Includes
- //
- #include <minoca/kernel/kernel.h>
- #include <minoca/lib/bconf.h>
- #include <minoca/kernel/bootload.h>
- //
- // ---------------------------------------------------------------- Definitions
- //
- //
- // The first row has at max 11 * 4 = 44 characters of value.
- // The second row has at max 13 + (4 * 4) + 11 + 11 = 51 characters of value.
- //
- #define KE_BANNER_FULL_WIDTH 116
- #define KE_BANNER_FULL_MEMORY_FORMAT \
- "Memory Used/Total: %s Paged Pool: %s Non-Paged Pool: %s Cache: %s"
- #define KE_BANNER_FULL_TIME_FORMAT \
- "Uptime: %s CPU User: %s Kernel: %s Interrupt: %s Idle: %s IO: %s%s"
- #define KE_BANNER_FULL_PAGING_FORMAT " Pg: %s"
- #define KE_BANNER_SHORT_WIDTH 80
- #define KE_BANNER_SHORT_MEMORY_FORMAT \
- "Memory: %s Paged: %s Non-paged: %s Cache: %s"
- #define KE_BANNER_SHORT_TIME_FORMAT \
- "%s U: %s K: %s In: %s Id: %s IO: %s%s"
- #define KE_BANNER_SHORT_PAGING_FORMAT " Pg: %s"
- #define KE_BANNER_TINY_WIDTH 40
- #define KE_BANNER_TINY_MEMORY_FORMAT "Memory: %s Cache: %s"
- #define KE_BANNER_TINY_TIME_FORMAT \
- "%s U%s K%s IO:%s"
- #define KE_BANNER_TINY_PAGING_FORMAT ""
- //
- // ------------------------------------------------------ Data Type Definitions
- //
- typedef enum _KERNEL_SUBSYSTEM {
- KernelSubsystemInvalid,
- KernelSubsystemKernelDebugger,
- KernelSubsystemKernelExecutive,
- KernelSubsystemMemoryManager,
- KernelSubsystemObjectManager,
- KernelSubsystemAcpi,
- KernelSubsystemHardwareLayer,
- KernelSubsystemProcess,
- KernelSubsystemInputOutput,
- KernelSubsystemProfiler
- } KERNEL_SUBSYSTEM, *PKERNEL_SUBSYSTEM;
- typedef struct _SYSTEM_USAGE_CONTEXT {
- ULONGLONG TimeCounter;
- ULONGLONG TimeCounterFrequency;
- ULONGLONG CycleCounterFrequency;
- ULONGLONG UserCycles;
- ULONGLONG KernelCycles;
- ULONGLONG InterruptCycles;
- ULONGLONG IdleCycles;
- ULONGLONG TotalCycles;
- ULONG UserPercent;
- ULONG KernelPercent;
- ULONG InterruptPercent;
- ULONG IdlePercent;
- } SYSTEM_USAGE_CONTEXT, *PSYSTEM_USAGE_CONTEXT;
- //
- // ----------------------------------------------- Internal Function Prototypes
- //
- VOID
- KepApplicationProcessorStartup (
- PPROCESSOR_START_BLOCK StartBlock
- );
- VOID
- KepCompleteSystemInitialization (
- PVOID Parameter
- );
- VOID
- KepAcquireProcessorStartLock (
- VOID
- );
- VOID
- KepReleaseProcessorStartLock (
- VOID
- );
- VOID
- KepBannerThread (
- PVOID Context
- );
- VOID
- KepUpdateSystemUsage (
- PSYSTEM_USAGE_CONTEXT Context
- );
- VOID
- KepPrintFormattedMemoryUsage (
- PCHAR String,
- ULONG StringSize,
- ULONGLONG UsedValue,
- ULONGLONG TotalValue
- );
- ULONG
- KepPrintFormattedSize (
- PCHAR String,
- ULONG StringSize,
- ULONGLONG Value
- );
- ULONG
- KepPrintFormattedPercent (
- PCHAR String,
- ULONG StringSize,
- ULONG PercentTimesTen
- );
- VOID
- KepQueueDistributionTimer (
- VOID
- );
- VOID
- KepDistributionTimerDpcRoutine (
- PDPC Dpc
- );
- VOID
- KepDistributionTimerWorkRoutine (
- PVOID Parameter
- );
- //
- // -------------------------------------------------------------------- Globals
- //
- //
- // Define a lock used to serializes parts of the AP startup execution.
- //
- volatile ULONG KeProcessorStartLock = 0;
- volatile ULONG KeProcessorsReady = 0;
- volatile BOOL KeAllProcessorsInitialize = FALSE;
- volatile BOOL KeAllProcessorsGo = FALSE;
- //
- // ------------------------------------------------------------------ Functions
- //
- VOID
- KepStartSystem (
- PKERNEL_INITIALIZATION_BLOCK Parameters
- )
- /*++
- Routine Description:
- This routine implements the first function called in the kernel from the
- boot loader.
- Arguments:
- Parameters - Supplies information about the system and memory layout as
- set up by the loader.
- Return Value:
- This function does not return.
- --*/
- {
- PBOOT_ENTRY BootEntry;
- PDEBUG_DEVICE_DESCRIPTION DebugDevice;
- KERNEL_SUBSYSTEM FailingSubsystem;
- ULONG ProcessorCount;
- KSTATUS Status;
- DebugDevice = NULL;
- FailingSubsystem = KernelSubsystemInvalid;
- //
- // Perform very basic processor initialization, preparing it to take
- // exceptions and use the serial port.
- //
- ArInitializeProcessor(FALSE, NULL);
- AcpiInitializePreDebugger(Parameters);
- Status = MmInitialize(Parameters, NULL, 0);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemMemoryManager;
- goto StartSystemEnd;
- }
- HlInitializePreDebugger(Parameters, 0, &DebugDevice);
- //
- // Initialize the debugging subsystem.
- //
- BootEntry = Parameters->BootEntry;
- if ((BootEntry != NULL) &&
- ((BootEntry->Flags & BOOT_ENTRY_FLAG_DEBUG) != 0)) {
- Status = KdInitialize(DebugDevice, Parameters->KernelModule);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemKernelDebugger;
- goto StartSystemEnd;
- }
- }
- //
- // Initialize the kernel executive.
- //
- Status = KeInitialize(0, Parameters);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemKernelExecutive;
- goto StartSystemEnd;
- }
- //
- // Perform phase 1 MM Initialization.
- //
- Status = MmInitialize(Parameters, NULL, 1);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemMemoryManager;
- goto StartSystemEnd;
- }
- //
- // Initialize the Object Manager.
- //
- Status = ObInitialize();
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemObjectManager;
- goto StartSystemEnd;
- }
- //
- // Perform phase 1 executive initialization, which sets up primitives like
- // queued locks and events.
- //
- Status = KeInitialize(1, Parameters);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemKernelExecutive;
- goto StartSystemEnd;
- }
- //
- // Initialize ACPI.
- //
- Status = AcpiInitialize(Parameters);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemAcpi;
- goto StartSystemEnd;
- }
- //
- // Initialize the hardware layer.
- //
- Status = HlInitialize(Parameters, 0);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemHardwareLayer;
- goto StartSystemEnd;
- }
- //
- // Initialize the process and thread subsystem.
- //
- Status = PsInitialize(0,
- Parameters,
- Parameters->KernelStack.Buffer,
- Parameters->KernelStack.Size);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemProcess;
- goto StartSystemEnd;
- }
- //
- // Perform phase 1 hardware layer initialization. The scheduler becomes
- // active at this point.
- //
- Status = HlInitialize(Parameters, 1);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemHardwareLayer;
- goto StartSystemEnd;
- }
- //
- // Now that the system is multithreaded, lock down MM.
- //
- Status = MmInitialize(Parameters, NULL, 2);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemMemoryManager;
- goto StartSystemEnd;
- }
- //
- // Perform additional process initialization now that MM is fully up.
- //
- Status = PsInitialize(1, Parameters, NULL, 0);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemProcess;
- goto StartSystemEnd;
- }
- //
- // Start all processors. Wait for all processors to initialize before
- // allowing the debugger to start broadcasting NMIs.
- //
- Status = HlStartAllProcessors(KepApplicationProcessorStartup,
- &ProcessorCount);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemHardwareLayer;
- goto StartSystemEnd;
- }
- KeAllProcessorsInitialize = TRUE;
- RtlAtomicAdd32(&KeProcessorsReady, 1);
- while (KeProcessorsReady != ProcessorCount) {
- ArProcessorYield();
- }
- KdEnableNmiBroadcast(TRUE);
- //
- // Perform phase 2 executive initialization, which creates things like the
- // worker threads.
- //
- Status = KeInitialize(2, Parameters);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemKernelExecutive;
- goto StartSystemEnd;
- }
- //
- // Initialize the system profiler subsystem, which will start profiling
- // only if early profiling is enabled.
- //
- Status = SpInitializeProfiler();
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemProfiler;
- goto StartSystemEnd;
- }
- //
- // Create a thread to continue system initialization that may involve
- // blocking, letting this thread become the idle thread. After this point,
- // the idle thread really is the idle thread.
- //
- Status = PsCreateKernelThread(KepCompleteSystemInitialization,
- Parameters,
- "Init");
- if (!KSUCCESS(Status)) {
- goto StartSystemEnd;
- }
- //
- // Boot mappings will be freed by the thread just kicked off, so the
- // parameters are now untouchable.
- //
- Parameters = NULL;
- StartSystemEnd:
- if (!KSUCCESS(Status)) {
- KeVideoPrintString(0, 14, "Kernel Failure: 0x");
- KeVideoPrintHexInteger(18, 14, Status);
- KeVideoPrintString(0, 15, "Subsystem: ");
- KeVideoPrintInteger(11, 15, FailingSubsystem);
- KeCrashSystem(CRASH_SYSTEM_INITIALIZATION_FAILURE,
- FailingSubsystem,
- Status,
- 0,
- 0);
- }
- //
- // Drop into the idle loop.
- //
- KeIdleLoop();
- return;
- }
- VOID
- KepApplicationProcessorStartup (
- PPROCESSOR_START_BLOCK StartBlock
- )
- /*++
- Routine Description:
- This routine implements the main initialization routine for processors
- other than P0.
- Arguments:
- StartBlock - Supplies a pointer to the processor start block that contains
- this processor's initialization information.
- Return Value:
- This function does not return, this thread eventually becomes the idle
- thread.
- --*/
- {
- KSTATUS Status;
- //
- // Mark the core as started.
- //
- StartBlock->Started = TRUE;
- RtlMemoryBarrier();
- //
- // Wait here until P0 says it's okay to initialize. This barrier allows
- // all processors to get out of the stub code as quickly as possible and
- // not have to worry about contending for non-paged pool locks while
- // allocating an idle stack.
- //
- while (KeAllProcessorsInitialize == FALSE) {
- ArProcessorYield();
- }
- KepAcquireProcessorStartLock();
- ArInitializeProcessor(FALSE, StartBlock->ProcessorStructures);
- //
- // Initialize the kernel executive.
- //
- Status = KeInitialize(0, NULL);
- if (!KSUCCESS(Status)) {
- goto ApplicationProcessorStartupEnd;
- }
- //
- // Perform phase 1 MM Initialization.
- //
- Status = MmInitialize(NULL, StartBlock, 1);
- if (!KSUCCESS(Status)) {
- goto ApplicationProcessorStartupEnd;
- }
- //
- // Perform phase 1 executive initialization.
- //
- Status = KeInitialize(1, NULL);
- if (!KSUCCESS(Status)) {
- goto ApplicationProcessorStartupEnd;
- }
- //
- // Initialize the hardware layer. The clock interrupt becomes active at
- // this point. As a result, this routine raises the run level from low to
- // dispatch to prevent the scheduler from becoming active before the
- // process and thread subsystem is initialized.
- //
- Status = HlInitialize(NULL, 0);
- if (!KSUCCESS(Status)) {
- goto ApplicationProcessorStartupEnd;
- }
- //
- // Initialize the process and thread subsystem.
- //
- Status = PsInitialize(0,
- NULL,
- StartBlock->StackBase,
- StartBlock->StackSize);
- if (!KSUCCESS(Status)) {
- goto ApplicationProcessorStartupEnd;
- }
- //
- // Perform phase 1 hardware layer initialization.
- //
- Status = HlInitialize(NULL, 1);
- if (!KSUCCESS(Status)) {
- goto ApplicationProcessorStartupEnd;
- }
- ApplicationProcessorStartupEnd:
- KeFreeProcessorStartBlock(StartBlock, FALSE);
- KepReleaseProcessorStartLock();
- StartBlock = NULL;
- //
- // On failure, take the system down.
- //
- if (!KSUCCESS(Status)) {
- KeCrashSystem(CRASH_SYSTEM_INITIALIZATION_FAILURE,
- KeGetCurrentProcessorNumber(),
- Status,
- 0,
- 0);
- }
- //
- // Wait until all processors are ready, and drop down to low level.
- //
- RtlAtomicAdd32(&KeProcessorsReady, 1);
- while (KeAllProcessorsGo == FALSE) {
- ArProcessorYield();
- }
- KeLowerRunLevel(RunLevelLow);
- KeIdleLoop();
- return;
- }
- //
- // --------------------------------------------------------- Internal Functions
- //
- VOID
- KepCompleteSystemInitialization (
- PVOID Parameter
- )
- /*++
- Routine Description:
- This routine completes initial kernel startup. It is performed on a
- separate thread to allow the startup thread to mature into the idle thread
- before blocking work starts. There is no guarantee that this routine will
- be executed exclusively on any one processor, the scheduler and all
- processors are active at this point.
- Arguments:
- Parameter - Supplies information about the system and memory layout as
- set up by the loader, the kernel initialization block.
- Return Value:
- None.
- --*/
- {
- KERNEL_SUBSYSTEM FailingSubsystem;
- PKERNEL_INITIALIZATION_BLOCK Parameters;
- KSTATUS Status;
- FailingSubsystem = KernelSubsystemInvalid;
- Parameters = (PKERNEL_INITIALIZATION_BLOCK)Parameter;
- //
- // Let all processors idle.
- //
- KeAllProcessorsGo = TRUE;
- //
- // Perform phase 0 initialization of the I/O subsystem, which will
- // initialize boot start drivers.
- //
- Status = IoInitialize(0, Parameters);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemInputOutput;
- goto CompleteSystemInitializationEnd;
- }
- //
- // Perform phase 3 executive initialization, which signs up for entropy
- // interface notifications.
- //
- Status = KeInitialize(3, NULL);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemKernelExecutive;
- goto CompleteSystemInitializationEnd;
- }
- //
- // Perform phase 3 initialization of the memory manager, which completes
- // initialization by freeing all boot allocations. From here on out, the
- // parameters pointer is inaccessible.
- //
- Status = MmInitialize(Parameters, NULL, 3);
- if (!KSUCCESS(Status)) {
- FailingSubsystem = KernelSubsystemMemoryManager;
- goto CompleteSystemInitializationEnd;
- }
- //
- // Fire up the banner thread.
- //
- PsCreateKernelThread(KepBannerThread, NULL, "KepBannerThread");
- //
- // Enable this for the free public builds.
- //
- #if 0
- KepQueueDistributionTimer();
- #endif
- CompleteSystemInitializationEnd:
- if (!KSUCCESS(Status)) {
- KeVideoPrintString(0, 24, "Failure: 0x");
- KeVideoPrintHexInteger(11, 24, Status);
- KeCrashSystem(CRASH_SYSTEM_INITIALIZATION_FAILURE,
- FailingSubsystem,
- Status,
- 0,
- 0);
- }
- return;
- }
- VOID
- KepAcquireProcessorStartLock (
- VOID
- )
- /*++
- Routine Description:
- This routine acquires the processor start lock.
- Arguments:
- None.
- Return Value:
- None.
- --*/
- {
- ULONG LockValue;
- while (TRUE) {
- LockValue = RtlAtomicCompareExchange32(&KeProcessorStartLock, 1, 0);
- if (LockValue == 0) {
- break;
- }
- ArProcessorYield();
- }
- return;
- }
- VOID
- KepReleaseProcessorStartLock (
- VOID
- )
- /*++
- Routine Description:
- This routine releases the processor start lock.
- Arguments:
- None.
- Return Value:
- None.
- --*/
- {
- ULONG LockValue;
- LockValue = RtlAtomicExchange32(&KeProcessorStartLock, 0);
- //
- // Assert if the lock was not held.
- //
- ASSERT(LockValue != 0);
- return;
- }
- VOID
- KepBannerThread (
- PVOID Context
- )
- /*++
- Routine Description:
- This routine prints an updated banner at the top of the screen.
- Arguments:
- Context - Supplies an unused context pointer.
- Return Value:
- None.
- --*/
- {
- CHAR BannerString[120];
- IO_CACHE_STATISTICS Cache;
- CHAR CacheString[16];
- CHAR CpuIdleString[16];
- CHAR CpuInterruptString[16];
- CHAR CpuKernelString[16];
- CHAR CpuUserString[16];
- ULONGLONG Days;
- ULONGLONG Frequency;
- ULONGLONG Hours;
- IO_GLOBAL_STATISTICS IoStatistics;
- CHAR IoString[16];
- MM_STATISTICS Memory;
- PSTR MemoryFormat;
- ULONGLONG Minutes;
- CHAR NonPagedPoolString[16];
- CHAR PagedPoolString[16];
- ULONG PageSize;
- PSTR PagingFormat;
- CHAR PagingString[24];
- CHAR PagingValueString[16];
- IO_GLOBAL_STATISTICS PreviousIoStatistics;
- ULONGLONG ReadDifference;
- ULONGLONG Seconds;
- ULONG Size;
- KSTATUS Status;
- ULONGLONG TimeCounter;
- PSTR TimeFormat;
- PKTIMER Timer;
- TIMER_QUEUE_TYPE TimerQueueType;
- CHAR TotalMemoryString[16];
- CHAR UptimeString[16];
- SYSTEM_USAGE_CONTEXT UsageContext;
- UINTN UsedSize;
- ULONG Width;
- ULONGLONG WriteDifference;
- Frequency = HlQueryTimeCounterFrequency();
- PageSize = MmPageSize();
- RtlZeroMemory(&Memory, sizeof(MM_STATISTICS));
- RtlZeroMemory(&Cache, sizeof(IO_CACHE_STATISTICS));
- RtlZeroMemory(&UsageContext, sizeof(SYSTEM_USAGE_CONTEXT));
- RtlZeroMemory(&PreviousIoStatistics, sizeof(IO_GLOBAL_STATISTICS));
- IoStatistics.Version = IO_GLOBAL_STATISTICS_VERSION;
- Memory.Version = MM_STATISTICS_VERSION;
- Cache.Version = IO_CACHE_STATISTICS_VERSION;
- if (!KSUCCESS(KeVideoGetDimensions(&Width, NULL))) {
- return;
- }
- if (Width > sizeof(BannerString) - 1) {
- Width = sizeof(BannerString) - 1;
- }
- //
- // Determine the right format given the width of the console.
- //
- if (Width >= KE_BANNER_FULL_WIDTH) {
- MemoryFormat = KE_BANNER_FULL_MEMORY_FORMAT;
- TimeFormat = KE_BANNER_FULL_TIME_FORMAT;
- PagingFormat = KE_BANNER_FULL_PAGING_FORMAT;
- } else if (Width >= KE_BANNER_SHORT_WIDTH) {
- MemoryFormat = KE_BANNER_SHORT_MEMORY_FORMAT;
- TimeFormat = KE_BANNER_SHORT_TIME_FORMAT;
- PagingFormat = KE_BANNER_SHORT_PAGING_FORMAT;
- } else if (Width >= KE_BANNER_TINY_WIDTH) {
- MemoryFormat = KE_BANNER_TINY_MEMORY_FORMAT;
- TimeFormat = KE_BANNER_TINY_TIME_FORMAT;
- PagingFormat = KE_BANNER_TINY_PAGING_FORMAT;
- } else {
- return;
- }
- Timer = KeCreateTimer(KE_ALLOCATION_TAG);
- if (Timer == NULL) {
- return;
- }
- while (TRUE) {
- Status = MmGetMemoryStatistics(&Memory);
- if (!KSUCCESS(Status)) {
- RtlDebugPrint("Failed to get MM statistics.\n");
- break;
- }
- Status = IoGetCacheStatistics(&Cache);
- if (!KSUCCESS(Status)) {
- RtlDebugPrint("Failed to get IO cache statistics.\n");
- }
- IoGetGlobalStatistics(&IoStatistics);
- TimeCounter = KeGetRecentTimeCounter();
- Seconds = TimeCounter / Frequency;
- Minutes = Seconds / 60;
- Seconds %= 60;
- Hours = Minutes / 60;
- Minutes %= 60;
- Days = Hours / 24;
- Hours %= 24;
- KepPrintFormattedMemoryUsage(TotalMemoryString,
- sizeof(TotalMemoryString),
- Memory.AllocatedPhysicalPages * PageSize,
- Memory.PhysicalPages * PageSize);
- UsedSize = Memory.PagedPool.TotalHeapSize -
- Memory.PagedPool.FreeListSize;
- KepPrintFormattedMemoryUsage(PagedPoolString,
- sizeof(PagedPoolString),
- UsedSize,
- Memory.PagedPool.TotalHeapSize);
- UsedSize = Memory.NonPagedPool.TotalHeapSize -
- Memory.NonPagedPool.FreeListSize;
- KepPrintFormattedMemoryUsage(NonPagedPoolString,
- sizeof(NonPagedPoolString),
- UsedSize,
- Memory.NonPagedPool.TotalHeapSize);
- KepPrintFormattedMemoryUsage(CacheString,
- sizeof(CacheString),
- Cache.DirtyPageCount * PageSize,
- Cache.PhysicalPageCount * PageSize);
- if (Width >= KE_BANNER_SHORT_WIDTH) {
- Size = RtlPrintToString(BannerString,
- Width + 1,
- CharacterEncodingDefault,
- MemoryFormat,
- TotalMemoryString,
- PagedPoolString,
- NonPagedPoolString,
- CacheString);
- } else {
- Size = RtlPrintToString(BannerString,
- Width + 1,
- CharacterEncodingDefault,
- MemoryFormat,
- TotalMemoryString,
- CacheString);
- }
- Size -= 1;
- while (Size < Width) {
- BannerString[Size] = ' ';
- Size += 1;
- }
- BannerString[Size] = '\0';
- KeVideoPrintString(0, 0, BannerString);
- //
- // Also update the second line, which contains the system usage.
- //
- KepUpdateSystemUsage(&UsageContext);
- if (Days == 0) {
- RtlPrintToString(UptimeString,
- sizeof(UptimeString),
- CharacterEncodingAscii,
- "%02I64d:%02I64d:%02I64d",
- Hours,
- Minutes,
- Seconds);
- } else {
- RtlPrintToString(UptimeString,
- sizeof(UptimeString),
- CharacterEncodingAscii,
- "%02I64d:%02I64d:%02I64d:%02I64d",
- Days,
- Hours,
- Minutes,
- Seconds);
- }
- KepPrintFormattedPercent(CpuUserString,
- sizeof(CpuUserString),
- UsageContext.UserPercent);
- KepPrintFormattedPercent(CpuKernelString,
- sizeof(CpuKernelString),
- UsageContext.KernelPercent);
- KepPrintFormattedPercent(CpuInterruptString,
- sizeof(CpuInterruptString),
- UsageContext.InterruptPercent);
- KepPrintFormattedPercent(CpuIdleString,
- sizeof(CpuIdleString),
- UsageContext.IdlePercent);
- ReadDifference = IoStatistics.BytesRead -
- PreviousIoStatistics.BytesRead;
- WriteDifference = IoStatistics.BytesWritten -
- PreviousIoStatistics.BytesWritten;
- KepPrintFormattedMemoryUsage(IoString,
- sizeof(IoString),
- ReadDifference,
- WriteDifference);
- ReadDifference = IoStatistics.PagingBytesRead -
- PreviousIoStatistics.PagingBytesRead;
- WriteDifference = IoStatistics.PagingBytesWritten -
- PreviousIoStatistics.PagingBytesWritten;
- PagingString[0] = '\0';
- if ((ReadDifference != 0) || (WriteDifference != 0)) {
- KepPrintFormattedMemoryUsage(PagingValueString,
- sizeof(PagingValueString),
- ReadDifference,
- WriteDifference);
- RtlPrintToString(PagingString,
- sizeof(PagingString),
- CharacterEncodingAscii,
- PagingFormat,
- PagingValueString);
- }
- RtlCopyMemory(&PreviousIoStatistics,
- &IoStatistics,
- sizeof(IO_GLOBAL_STATISTICS));
- if (Width >= KE_BANNER_SHORT_WIDTH) {
- Size = RtlPrintToString(BannerString,
- Width + 1,
- CharacterEncodingDefault,
- TimeFormat,
- UptimeString,
- CpuUserString,
- CpuKernelString,
- CpuInterruptString,
- CpuIdleString,
- IoString,
- PagingString);
- } else {
- Size = RtlPrintToString(BannerString,
- Width + 1,
- CharacterEncodingDefault,
- TimeFormat,
- UptimeString,
- CpuUserString,
- CpuKernelString,
- IoString);
- }
- Size -= 1;
- while (Size < Width) {
- BannerString[Size] = ' ';
- Size += 1;
- }
- BannerString[Size] = '\0';
- KeVideoPrintString(0, 1, BannerString);
- TimerQueueType = TimerQueueSoftWake;
- if ((Seconds % 5) == 0) {
- TimerQueueType = TimerQueueSoft;
- }
- KeQueueTimer(Timer,
- TimerQueueType,
- TimeCounter + Frequency,
- 0,
- 0,
- NULL);
- ObWaitOnObject(Timer, 0, WAIT_TIME_INDEFINITE);
- }
- KeDestroyTimer(Timer);
- return;
- }
- VOID
- KepUpdateSystemUsage (
- PSYSTEM_USAGE_CONTEXT Context
- )
- /*++
- Routine Description:
- This routine updates the system usage information.
- Arguments:
- Context - Supplies a pointer to the context information.
- Return Value:
- None.
- --*/
- {
- PROCESSOR_CYCLE_ACCOUNTING Cycles;
- ULONGLONG DeltaTotal;
- ULONGLONG ExpectedTotalDelta;
- ULONGLONG IdleDelta;
- ULONGLONG InterruptDelta;
- ULONGLONG KernelDelta;
- ULONGLONG StoppedCycles;
- ULONGLONG TimeCounter;
- ULONGLONG TimeCounterDelta;
- ULONGLONG TotalCycles;
- ULONGLONG TotalDelta;
- ULONGLONG UserDelta;
- if (Context->TimeCounterFrequency == 0) {
- Context->TimeCounterFrequency = HlQueryTimeCounterFrequency();
- }
- if (Context->CycleCounterFrequency == 0) {
- Context->CycleCounterFrequency = HlQueryProcessorCounterFrequency();
- }
- //
- // Snap the time counter and cycle counters.
- //
- TimeCounter = HlQueryTimeCounter();
- KeGetTotalProcessorCycleAccounting(&Cycles);
- //
- // The cycle counter may not count while the processor is idle. Use the
- // time counter to figure out how many cycles there should have been, and
- // compare to how many there actually are. Any difference gets added to the
- // idle cycles.
- //
- TimeCounterDelta = TimeCounter - Context->TimeCounter;
- if (TimeCounterDelta == 0) {
- return;
- }
- //
- // TcTicks * CcTicks/ * s/ = CcTicks.
- // s TcTicks
- //
- ExpectedTotalDelta = TimeCounterDelta * Context->CycleCounterFrequency *
- KeGetActiveProcessorCount() /
- Context->TimeCounterFrequency;
- TotalCycles = Cycles.UserCycles + Cycles.KernelCycles +
- Cycles.InterruptCycles + Cycles.IdleCycles;
- TotalDelta = TotalCycles - Context->TotalCycles;
- StoppedCycles = 0;
- if (ExpectedTotalDelta > TotalDelta) {
- StoppedCycles = ExpectedTotalDelta - TotalDelta;
- }
- //
- // Compute the differences between this time and last time.
- //
- UserDelta = Cycles.UserCycles - Context->UserCycles;
- KernelDelta = Cycles.KernelCycles - Context->KernelCycles;
- InterruptDelta = Cycles.InterruptCycles - Context->InterruptCycles;
- IdleDelta = Cycles.IdleCycles - Context->IdleCycles + StoppedCycles;
- DeltaTotal = UserDelta + KernelDelta + InterruptDelta + IdleDelta;
- //
- // Save this snapshot into the context as the new previous snapshot.
- //
- Context->TimeCounter = TimeCounter;
- Context->UserCycles = Cycles.UserCycles;
- Context->KernelCycles = Cycles.KernelCycles;
- Context->InterruptCycles = Cycles.InterruptCycles;
- Context->IdleCycles = Cycles.IdleCycles;
- Context->TotalCycles = TotalCycles;
- //
- // Finally, update the percent (times ten) values.
- //
- Context->UserPercent = UserDelta * 1000 / DeltaTotal;
- Context->KernelPercent = KernelDelta * 1000 / DeltaTotal;
- Context->InterruptPercent = InterruptDelta * 1000 / DeltaTotal;
- Context->IdlePercent = IdleDelta * 1000 / DeltaTotal;
- return;
- }
- VOID
- KepPrintFormattedMemoryUsage (
- PCHAR String,
- ULONG StringSize,
- ULONGLONG UsedValue,
- ULONGLONG TotalValue
- )
- /*++
- Routine Description:
- This routine prints two formatted sizes a la 5.8M/64M.
- Arguments:
- String - Supplies a pointer to the string buffer to print to.
- StringSize - Supplies the total size of the string buffer in bytes.
- UsedValue - Supplies the first value to print.
- TotalValue - Supplies the second value to print.
- Return Value:
- None.
- --*/
- {
- ULONG Size;
- Size = KepPrintFormattedSize(String, StringSize, UsedValue);
- if (Size != 0) {
- Size -= 1;
- }
- String += Size;
- StringSize -= Size;
- if (StringSize > 1) {
- *String = '/';
- String += 1;
- StringSize -= 1;
- }
- if (StringSize > 1) {
- KepPrintFormattedSize(String, StringSize, TotalValue);
- }
- return;
- }
- ULONG
- KepPrintFormattedSize (
- PCHAR String,
- ULONG StringSize,
- ULONGLONG Value
- )
- /*++
- Routine Description:
- This routine prints a formatted size a la 5.8M (M for megabytes).
- Arguments:
- String - Supplies a pointer to the string buffer to print to.
- StringSize - Supplies the total size of the string buffer in bytes.
- Value - Supplies the value in bytes to print.
- Return Value:
- Returns the length of the final string after all formatting has been
- completed.
- --*/
- {
- ULONG Size;
- CHAR Suffix;
- Suffix = 'B';
- if (Value > 1024) {
- Suffix = 'K';
- Value = (Value * 10) / 1024;
- if (Value / 10 >= 1024) {
- Suffix = 'M';
- Value /= 1024;
- if (Value / 10 >= 1024) {
- Suffix = 'G';
- Value /= 1024;
- }
- }
- }
- ASSERT(Value < 1024 * 10);
- if (Suffix == 'B') {
- Size = RtlPrintToString(String,
- StringSize,
- CharacterEncodingAscii,
- "%d",
- (ULONG)Value);
- } else {
- if (Value < 100) {
- Size = RtlPrintToString(String,
- StringSize,
- CharacterEncodingAscii,
- "%d.%d%c",
- (ULONG)Value / 10,
- (ULONG)Value % 10,
- Suffix);
- } else {
- Size = RtlPrintToString(String,
- StringSize,
- CharacterEncodingAscii,
- "%d%c",
- (ULONG)Value / 10,
- Suffix);
- }
- }
- return Size;
- }
- ULONG
- KepPrintFormattedPercent (
- PCHAR String,
- ULONG StringSize,
- ULONG PercentTimesTen
- )
- /*++
- Routine Description:
- This routine prints a formatted percentage a la 5.8% or 99%. The field
- width is always 4.
- Arguments:
- String - Supplies a pointer to the string buffer to print to.
- StringSize - Supplies the total size of the string buffer in bytes.
- PercentTimesTen - Supplies ten times the percentage value. So 54.8% would
- have a value of 548. This value will be rounded to the precision that
- is printed.
- Offset - Supplies a pointer that on input supplies the offset within the
- string to print. This value will be updated to the new end of the
- string.
- Return Value:
- Returns the length of the final string after all formatting has been
- completed.
- --*/
- {
- ULONG Size;
- //
- // For values less than 10%, print the single digit and first decimal
- // point.
- //
- if (PercentTimesTen < 100) {
- Size = RtlPrintToString(String,
- StringSize,
- CharacterEncodingAscii,
- "%d.%d%%",
- PercentTimesTen / 10,
- PercentTimesTen % 10);
- } else {
- PercentTimesTen += 5;
- Size = RtlPrintToString(String,
- StringSize,
- CharacterEncodingAscii,
- "%3d%%",
- PercentTimesTen / 10);
- }
- return Size;
- }
- VOID
- KepQueueDistributionTimer (
- VOID
- )
- /*++
- Routine Description:
- This routine queues the distribution timer.
- Arguments:
- None.
- Return Value:
- None.
- --*/
- {
- PDPC Dpc;
- ULONGLONG DueTime;
- ULONGLONG Interval;
- KSTATUS Status;
- PKTIMER Timer;
- Dpc = NULL;
- //
- // Create the reset timer that reboots the system every few days.
- //
- Timer = KeCreateTimer(MM_ALLOCATION_TAG);
- if (Timer == NULL) {
- goto QueueDistributionTimerEnd;
- }
- Dpc = KeCreateDpc(KepDistributionTimerDpcRoutine, Timer);
- if (Dpc == NULL) {
- goto QueueDistributionTimerEnd;
- }
- Interval = MICROSECONDS_PER_SECOND * SECONDS_PER_DAY * 3;
- DueTime = KeGetRecentTimeCounter() +
- KeConvertMicrosecondsToTimeTicks(Interval);
- Status = KeQueueTimer(Timer, TimerQueueSoftWake, DueTime, 0, 0, Dpc);
- if (!KSUCCESS(Status)) {
- goto QueueDistributionTimerEnd;
- }
- Timer = NULL;
- Dpc = NULL;
- QueueDistributionTimerEnd:
- if (Timer != NULL) {
- KeDestroyTimer(Timer);
- }
- if (Dpc != NULL) {
- KeDestroyDpc(Dpc);
- }
- return;
- }
- VOID
- KepDistributionTimerDpcRoutine (
- PDPC Dpc
- )
- /*++
- Routine Description:
- This routine implements the distribution DPC routine. It is called when the
- distribution timer fires.
- Arguments:
- Dpc - Supplies a pointer to the DPC.
- Return Value:
- None.
- --*/
- {
- KeCreateAndQueueWorkItem(NULL,
- WorkPriorityNormal,
- KepDistributionTimerWorkRoutine,
- Dpc);
- return;
- }
- VOID
- KepDistributionTimerWorkRoutine (
- PVOID Parameter
- )
- /*++
- Routine Description:
- This routine prototype represents a work item.
- Arguments:
- Parameter - Supplies an optional parameter passed in by the creator of the
- work item.
- Return Value:
- None.
- --*/
- {
- KSTATUS (*ActionRoutine)(SYSTEM_RESET_TYPE);
- PDPC Dpc;
- PKTIMER Timer;
- Dpc = Parameter;
- Timer = Dpc->UserData;
- KeDestroyTimer(Timer);
- KeDestroyDpc(Dpc);
- //
- // Reset the system. Be casually tricky by not just calling the routine
- // directly. Really it's not that tricky.
- //
- ActionRoutine = KeResetSystem;
- ActionRoutine(SystemResetShutdown);
- return;
- }
|