Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891), страница 66
Текст из файла (страница 66)
But if the quantity of data is small, it is not possible toretain the chunk handle or data address between accesses, or somecontrol is required for access to the data then another approach isneeded.Publish and subscribe may be the answer, as one way to look at thisservice is as a set of ‘‘global variables’’ that both user- and kernel-modesoftware can access by ID. The service also provides access control foreach value, based around the platform security architecture, and somereal-time guarantees. See Chapter 4, Inter-thread Communication, for adetailed description of this service.7.6 Memory allocationThe following tables provide a comparison across the various memorymodels of how the memory models reserve and allocate the memoryused for different purposes within the OS.7.6.1 Kernel memoryMoving memory modelMultiple memory modelEmulatormodelSupervisor modestackAllocated as pages from the kernel’s ‘‘SvStack’’disconnected chunk, with 4 K uncommittedguard pages in between.There is nosupervisor‘‘mode’’.Non-XIP devicedriver codeAllocated as pages in theglobal ‘‘KERN$CODE’’disconnected chunk.Allocated bythe Windowsloader.Non-XIP devicedriver static dataAllocated in the kernel heap.Free store/heapcellsAllocated in the kernel heap, which uses the kernel’s dynamic‘‘SvHeap’’ chunk.Allocated as pages in thekernel’s ‘‘$CODE’’disconnected chunk.Allocated bythe Windowsloader.310MEMORY MODELSMoving memory modelMultiple memory modelEmulatormodelI/O addressspaceSome mapped by the bootstrap into reserved region.Otherwise created as mappings in the kernel section.n/aI/O and sharedbuffersCreated as chunks within the kernel section.Created using achunk.7.6.2 User memoryMoving modelMultiple modelEmulatormodelUser-modestackAllocated as pages from the process’s ‘‘$DAT’’disconnected chunk, with 8 K uncommittedguard pages in between.Allocated byWindows when thethread is created.Non-XIP codeAllocated and mappedas pages in the global‘‘USER$CODE’’disconnected chunk.Allocated by theWindows loader.EXE static dataAllocated as pages at the beginning of theprocess’s ‘‘$DAT’’ chunk.Allocated by theWindows loader.DLL static dataAllocated as pages from the process’s‘‘DLL$DATA’’ disconnected chunk.Allocated by theWindows loader.Freestore/heapcellsAllocated in the current allocator.
By default this is a heap in anunnamed, private, dynamic chunk.ChunksFurther chunks can be created and are allocated in the user section ofthe address space.Thread LocalStorage (TLS)Each word of TLS is allocated in a map on the kernel heap. Access tothe TLS data requires use of a kernel executive call.Publish &subscribepropertiesProperty data is allocated on the kernel heap, allowing it to be sharedand protected.Allocated as pages in theUser Code section.Mapped into the processin the process’s‘‘$CODE’’ disconnectedchunk.LOW MEMORY3117.7 Low memoryOn modern desktop computers, we certainly notice when the system runsout of memory: everything begins to slow down, the hard disk starts to getvery busy and we get warning messages about running low on memory.But we aren’t generally informed that there is not enough memory tocarry out a request, as we would have been on a desktop system 10 yearsago – instead the system will struggle on, even if it becomes unusable.This change in behavior is mainly because of demand paging andvirtual memory systems – the OS has the ability to save to disk a copyof memory that has not been accessed recently and then copy it back into main memory again the next time a program tries to use the memory.This way, the system can appear to have far more physical memory thanit really has.
One side effect is that the ‘‘hard’’ limit of memory capacityhas become a softer restriction – very rarely will an application find thata memory allocation request fails.7.7.1Handling allocation failureAs I said earlier, Symbian OS does not support demand paging andhas small amounts of physical memory when compared with desktopdevices. This combination means that all kernel, system and applicationsoftware must expect that all memory allocation requests will fail fromtime to time. The result is that all software for Symbian OS must bewritten carefully to ensure that Out of Memory (OOM) errors are handledcorrectly and as gracefully as possible.As well as correctly handling a failure to allocate memory, a server orapplication must also manage all of its allocated memory.
Long runningservices (such as the kernel) must be able to free memory that was acquiredfor a resource when a program releases that resource – the alternative isthe slow ‘‘leakage’’ of memory over time, eventually resulting in memoryexhaustion and system failure.For user-side code, the TRAP and Leave mechanism, and the cleanupstack provide much of the support required to manage memory allocationand recovery on failure. These services are covered extensively in bookssuch as Symbian OS C++ for Mobile Phones.2Within the EKA2 kernel, there are no mechanisms such as TRAP,Leave and the cleanup stack.
This contrasts with EKA1, in which weused the TRAP mechanism inside the kernel. Our experience showsthat the use of TRAP, Leave and the cleanup stack make user-sidecode simpler, more readable and often more compact. However, thisexperience does not carry over to the implementation of EKA2 – thepresence of fine-grained synchronization and possibility of preemption at2Symbian OS C++ for Mobile Phones: Professional Development on ConstrainedDevices, by Richard Harrison. Symbian Press.312MEMORY MODELSalmost all points in the code often requires more complex error detectionand recovery code.
Additionally, optimizations to accelerate importantoperations or to reduce context switch ‘‘thrashing’’ remove the symmetrythat is desirable for using a cleanup stack push/pop protocol.So instead of providing an equivalent to TRAP, the kernel providesa number of supporting services that help ensure that threads executingin kernel mode do not leak memory, even during long running kernelservices when it is quite possible that the thread may be terminated.Thread critical sectionsThese bear little relation to the user-side synchronization primitive of thesame name, RCriticalSection. Rather, these are code regions duringwhich the thread cannot be unilaterally suspended or terminated – thethread will only act on suspend or exit requests once it leaves the criticalsection. The kernel uses these extensively to ensure that when a threadis modifying a shared data structure in the kernel, the modifications willrun to completion rather than the thread stopping part way through.Holding a fast mutex places a thread in an implicit critical section,as the scheduler depends on the fact that such a thread cannot block orotherwise be removed from the ready list.Exception trappingWhen inside a critical section, it is illegal for a thread to do any actionthat would result in the kernel terminating it – such as panicking it (dueto invalid user arguments) or terminating it because it took an exception.The latter scenario can occur if a kernel service must copy data frommemory supplied by the user-mode program, but the memory pointerprovided is invalid.This makes the copying of user-mode data difficult, particularly whenthe thread needs to hold the system lock at the same time (which is animplicit thread critical section).
EKA2 provides an exception handlingand trapping system, XTRAP, which behaves in a similar way to the userside TRAP/Leave, but instead it can catch hardware exceptions such asthose generated by faulty memory access. The kernel most frequently usesXTRAP to safely copy user-mode memory while inside a thread criticalsection. Any errors reported can then result in the thread safely exitingthe critical section before reporting the failure.Transient objectsOccasionally a thread needs to allocate a temporary object during partof a kernel executive call. As the owning reference to this object isthe thread’s registers and call stack, the thread would have to enter acritical section to prevent a memory leak happening if the thread wereterminated.
However, thread critical sections make error handling morecomplex as they require the use of exception trapping and deferring oferror reporting until the critical section is released.LOW MEMORY313We provide some help here: each DThread in the kernel has twomembers to hold a DObject on which the thread has a temporaryreference, and a temporary heap cell. If non-null, iTempObj and iExtTempObj are closed and iTempAlloc is deleted during thread exitprocessing. Kernel code can use these members to ‘‘own’’ such temporary objects during an executive call, enabling the thread to release thecritical section earlier.7.7.2 System memory managementIt is quite possible to write a single application that manages its ownmemory carefully, handles OOM scenarios and can adjust its behaviorwhen less memory is available.
However, a single application cannoteasily determine whether it should release some non-critical memory (forexample, a cache) so that another application can run.However, the kernel provides some support to the system as a whole, toenable the implementation of system-wide memory management policies,typically within a component in the UI.The memory model keeps track of the number of unused pages of memory. When this goes below a certain threshold, the kernel completes anyRChangeNotifier subscriptions with EChangesFreeMemory.
Whenthe amount of free memory increases the kernel signals the notifiers again.In addition, should any RAM allocation request fail due to insufficientmemory, the kernel signals the notifiers with EChangesOutOfMemory.The EUSER function UserSvr::SetMemoryThresholds() setstwo values that control when the memory model should signal thenotifiers.Typically, the UI component responsible for managing the systemmemory policy will set the thresholds and then monitor the notifier forindications that free memory is getting low or has been exhausted. Whenthis occurs, the system might employ various strategies for freeing somecurrently used memory:• The manager can request that applications reduce their memoryconsumption.
For example, a browser could reduce a RAM cache it isusing, or a Java Virtual Machine could garbage collect, and compactits memory space• The manager can request (or demand) that applications and OSservices that have not been used recently to save any data and thenexit. This is quite acceptable on a phone, as the user-concept ofrunning many applications at once is still very much one that is tiedto computers and not to phones.The mechanism by which such requests arrive at an application arepresently specific to the UI, if they are used at all.314MEMORY MODELSIn some respects, you can envisage this system level memory manageras implementing an application level garbage collector.