Главная » Просмотр файлов » Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU

Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891), страница 13

Файл №779891 Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (Symbian Books) 13 страницаWiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891) страница 132018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 13)

As I’ve already hinted, the most important differencebetween the CPU power modes to Symbian OS is the time it takes totransition from Run to a mode and the time taken to get back to Runmode again. The decision about which CPU mode to use is determinedheuristically within the idle software, based on recent use and pendingtimer events.42HARDWARE FOR SYMBIAN OSDedicated hardware accelerators allow for excellent performancewith low power consumption, whereas general purpose ARM softwareis infinitely reprogrammable, but execution is more expensive in powerand time.

The trick is to get the right balance between fixed hardwareand flexible software, and ensure that the real phone requirements canbe met two years after the silicon is finalized.Power management is a pervasive topic. It requires careful hardwaredesign and focused software to achieve the system design goals.2.11SummaryIn this chapter I have described the core hardware that is needed to runSymbian OS, with some emphasis on the power management implicationsof those hardware choices.

There are a great many more peripherals andtopics that I do not have space to cover here, including:• Real-time clock• Touch screen• IPC interface to BP• Debug interfaces• Flash programming• Multiple displays• IRDA• Booting• Removable media, SD, MMC• 2D Graphics• 3D Graphics• DSP• Multimedia accelerators• USB interfaces• Advance power management• Bluetooth modules• Watchdogs and resets• Security hardware.SUMMARY43Within Symbian, we refer to the software layers that control the hardware,including the bootstrap, kernel port and device drivers as the baseport,and more generically as the Board Support Package (BSP).To enable all of the hardware on a phone is the job of the people inthe base porting team, who use their skills and experience to populate thelowest layers of hardware abstraction within Symbian OS.

You can findfurther information in the Base Porting Kit (BPK) and Device Driver Kit(DDK) documentation, both of which are available to Symbian Partners,see www.symbian.com/partners for more information.Designing hardware for a Symbian OS phone requires a system view ofthe final product. The designers need to consider real-world performanceuse cases, select hardware with enough (but not too much) capacity, andwith every decision, they need to analyze power consumption.I hope that this chapter will have given you an insight into the designchoices you will need to make if you are building a Symbian OS phone.In the next chapter, I will start to look at the fundamental entitiesthat underlie the running of code on Symbian OS – threads, processesand libraries.3Threads, Processes and Librariesby Jane SalesOne of the main causes of the fall of the Roman Empire was that, lackingzero, they had no way to indicate successful termination of theirC programs.Robert FirthIn this chapter, I will look at the entities – that is, threads, processes andlibraries – that are concerned with executing code under Symbian OS.

I’llbegin by examining threads, which are the fundamental unit of executionof Symbian OS.Because processes and threads touch so many components in SymbianOS, this chapter will refer to many areas that I will explain in more detailin other chapters.3.1 What is a thread?Under Symbian OS, our definition of a thread is that it is the unit ofexecution; it is the entity that the kernel schedules, the entity to which thekernel allocates CPU resources.

You can think of a thread as a collectionof kernel data structures that describe the point a program has reached inits execution. In fact, more accurately, these data structures describe oneof the points a program has reached in its execution, because a programcan contain more than one thread.The Symbian OS definition of a process is that it is a collection ofthreads that share a particular address mapping. In other words, theparticular mapping of virtual to physical memory at a particular timedepends on the process that is running.

Each thread within a processcan read and write from any other thread’s memory, since they sharean address space. But more on this later – for now, let’s concentrateon threads.46THREADS, PROCESSES AND LIBRARIES3.2 Nanokernel threadsThe nanokernel provides the most basic thread support for SymbianOS in the form of nanokernel threads (which from now on I’ll callnanothreads).

The nanokernel provides support for the scheduling ofnanothreads, and for their synchronization and timing services. Thethread services the nanokernel provides are very simple – simpler eventhan those provided by a typical RTOS. We chose them to be the minimalset needed to support a GSM signaling stack.Nanothreads only ever run in supervisor mode; they never run in usermode. Because of this, each nanothread needs only a single, supervisormode stack. The nanokernel keeps the address of the nanothread’s stack inthe NThread class’s iStackBase, and the stack’s size in iStackSize.The kernel uses these two variables for initialization and, when anexception occurs, for stack checking to protect against stack overflows.Each nanothread’s member data also contains its last saved stackpointer value, iSavedSP. Whenever the nanothread blocks or is preempted, the scheduler saves the ARM processor’s context on the nanothread’s stack.

Next, the scheduler saves the value of the processor’ssupervisor-stack-pointer register in iSavedSP. Then the scheduler overwrites the processor’s supervisor-stack-pointer register, by loading it fromthe iSavedSP of the new nanothread. Finally, the scheduler restoresthe processor’s context from the new stack, thus bringing about a threadswitch. I will cover scheduling in more detail later.3.2.1 NThread classThe NThread class is derived from a base class, NThreadBase, whichis defined in nk_priv.h. Here is a cut-down version of NThreadBase,showing the main points of interest:class NThreadBase : public TPriListLink{public:enum NThreadState{EReady,ESuspended,EWaitFastSemaphore,ESleep,EBlocked,EDead,EWaitDfc,ENumNStates};enum NThreadOperation{ESuspend=0,NANOKERNEL THREADS47EResume=1,EForceResume=2,ERelease=3,EChangePriority=4,ELeaveCS=5,ETimeout=6,};public:NThreadBase();TInt Create(SNThreadCreateInfo& anInfo,TBool aInitial);IMPORT_C void CheckSuspendThenReady();IMPORT_C void Ready();void DoCsFunction();IMPORT_C TBool Suspend(TInt aCount);IMPORT_C TBool Resume();IMPORT_C TBool ForceResume();IMPORT_C void Release(TInt aReturnCode);IMPORT_C void RequestSignal();IMPORT_C void SetPriority(TInt aPriority);void SetEntry(NThreadFunction aFunction);IMPORT_C void Kill();void Exit();void ForceExit();public:NFastMutex* iHeldFastMutex;// fast mutex heldNFastMutex* iWaitFastMutex;// fast mutex on which blockedTAny* iAddressSpace;TInt iTime; // time remainingTInt iTimeslice;NFastSemaphore iRequestSemaphore;TAny* iWaitObj;// object on which this thread is waitingTInt iSuspendCount; // how many times we have been suspendedTInt iCsCount; // critical section countTInt iCsFunction; // what to do on leaving CS:// +n=suspend n times, 0=nothing, -1=exitNTimer iTimer;TInt iReturnValue;TLinAddr iStackBase;TInt iStackSize;const SNThreadHandlers* iHandlers; // + thread event handlersconst SFastExecTable* iFastExecTable;const SSlowExecEntry* iSlowExecTable; //first entry iEntries[0]TLinAddr iSavedSP;TAny* iExtraContext; // coprocessor contextTInt iExtraContextSize; // +ve=dynamically allocated// 0=none, -ve=statically allocated};You can see that the thread base class itself is derived from TPriListLink – this means that the thread is part of a priority-ordered doublylinked list, which is used in scheduling.The NThread class itself is CPU-dependent – at the moment threeversions of it exist, one for ARM, one for X86 and the other for theemulator.

To give you a flavor for the kind of functionality that you findin NThread, here is a cut-down ARM version:48THREADS, PROCESSES AND LIBRARIESclass NThread : public NThreadBase{public:TInt Create(SNThreadCreateInfo& aInfo, TBool aInitial);inline void Stillborn() {}// Value indicating what event caused thread to// enter privileged mode.enum TUserContextType{EContextNone=0,/* Thread has no user context */EContextException=1, /* HW exception while in user mode */EContextUndefined,EContextUserInterrupt, /* Preempted by int in user mode */// Killed while preempted by interrupt taken in user modeEContextUserInterruptDied,// Preempted by interrupt taken in executive call handlerEContextSvsrInterrupt1,// Killed while preempted by interrupt taken in// executive call handlerEContextSvsrInterrupt1Died,// Preempted by interrupt taken in executive call handlerEContextSvsrInterrupt2,// Killed while preempted by interrupt taken in// executive call handler */EContextSvsrInterrupt2Died,EContextWFAR, // Blocked on User::WaitForAnyRequest()// Killed while blocked on User::WaitForAnyRequest()EContextWFARDied,EContextExec, // Slow executive callEContextKernel, // Kernel-side context (for kernel threads)};IMPORT_C static const TArmContextElement*const* UserContextTables();IMPORT_C TUserContextType UserContextType();inline TInt SetUserContextType(){ return iSpare3=UserContextType(); }inline void ResetUserContextType(){if(iSpare3>EContextUndefined) iSpare3=EContextUndefined; }void GetUserContext(TArmRegSet& aContext,TUint32& aAvailRegistersMask);void SetUserContext(const TArmRegSet& aContext);void ModifyUsp(TLinAddr aUsp);#ifdef __CPU_ARM_USE_DOMAINSTUint32 Dacr();void SetDacr(TUint32 aDacr);TUint32 ModifyDacr(TUint32 aClearMask, TUint32 aSetMask);#endif#ifdef __CPU_HAS_COPROCESSOR_ACCESS_REGvoid SetCar(TUint32 aDacr);#endifIMPORT_C TUint32 Car();IMPORT_C TUint32 ModifyCar(TUint32 aClearMask, TUint32 aSetMask);NANOKERNEL THREADS49#ifdef __CPU_HAS_VFPvoid SetFpExc(TUint32 aDacr);#endifIMPORT_C TUint32 FpExc();IMPORT_C TUint32 ModifyFpExc(TUint32 aClearMask, TUint32 aSetMask);};Key member data of NThread and NThreadBaseiPriorityThe thread’s absolute scheduling priority, between 0 and 63 inclusive.iNStateThe state of the thread, that is, ready or blocked.

Essentially this determineswhich queue if any the thread is linked into.iAttributesBit mask that determines scheduling policy with respect to the systemlock and whether the thread requires an address space switch in general.iAddressSpaceAddress space identifier for the thread, used to determine whether the correct address space is already active. The actual value has no significanceto the nanokernel, only to the Symbian OS memory model.iTimeCounter used to count timer ticks before thread should yield to next equalpriority thread.iTimesliceNumber of low-level timer ticks before thread yields to equal prioritythreads. If negative, it will not yield unless it blocks.iRequestSemaphoreAn NFastSemaphore that we use for general ‘‘wait for any event’’.

Характеристики

Тип файла
PDF-файл
Размер
6,63 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6508
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее