Эмулятор ядра OS Windows

...
  • Ok
  • Jurgen, hello. Changes to critical areas of code, such as the MENUET header, require additional discussion because they affect many programs. Everything after the field i_icon is not standardized and is handled differently in different places (KX extension and GCC extension).
    The patch that you applied, as I understand it, is only needed by your emulator. You either need to figure out how to do it differently. Or he will try to explain why such a decision is necessary. Thank you in advance.
    Изобретайте колёса каждый раз, когда хотите написать новую программу.
  • Эта тема будет про приоритеты потоков

    Винда интенсивно применяет политику приоритетов потоков при своей работе. Эти приоритеты мной игнорировались, что не мешало работе винды. Однако, когда я заметил, что число созданных потоков приближается к двустам, то резонно задуматься о внедрении в Колибри системы приоритетов пользовательских потоков.

    Нашел тему в форуме "Приоритеты в планировщике задач"
    http://board.kolibrios.org/viewtopic.ph ... 0%BE%D0%BA

    В последнем сообщении этого форума CleverMouse сообщает о логике работы планировщика.
    CleverMouse wrote: Fri Jun 07, 2013 8:09 pm r3615+r3617 вносят дополнение: теперь при поступлении IRQ, отличного от таймера, также вызывается планировщик, но со специальным флагом "смотри только на потоки, которые строго более приоритетны, чем текущий". Флаг также меняет логику продвижения очереди: если пользовательский поток A упорно работал и был прерван по таймеру, то следующим пользовательским потоком будет B, следующий в кольце после A; если тот же пользовательский поток A упорно работал и был прерван по другому прерыванию, то следующим пользовательским потоком останется A - возможно, после того, как вмешавшийся ядерный поток что-нибудь сделает.

    В эту логику планировщика я предлагаю добавить один пункт (выделено жирным шрифтом):
    1) Если пользовательский поток A упорно работал и был прерван по таймеру, то следующим пользовательским потоком будет B, следующий в кольце после A;
    2) Если у потока В снижен локальный приоритет и счетчик локального приоритета не обнулен, то переход к следующему потоку этого уровня приоритета.
    3) Если тот же пользовательский поток A упорно работал и был прерван по другому прерыванию, то следующим пользовательским потоком останется A - возможно, после того, как вмешавшийся ядерный поток что-нибудь сделает.


    Предлагаю следующие изменения в ядре Колибри:
    1.) Добавить в структуру TASKDATA в файле const.inc два поля в свободные ячейки:

    struct taskdata.jpg
    struct taskdata.jpg (89.44 KiB)
    Viewed 1190 times
    Примечание:
    Я пытался просто добавить поля в структуре TASKDATA, но в итоге перестает работать кнопка "ПУСК" у Колибри. Видимо происходит затирание других данных если увеличить размер структуры. Поправьте меня, если я ошибаюсь.


    2.) Внедрить код проверки ядром локальных приоритетов пользовательских потоков в файл sched.inc после метки .task_found:

    scheduler.jpg
    scheduler.jpg (168.45 KiB)
    Viewed 1190 times

    3.) В процедуре set_app_params в файле taskman.inc внедрить код установки начального приоритета потока:

    taskman.jpg
    taskman.jpg (54.81 KiB)
    Viewed 1190 times


    Уровень локальных приоритетов пользовательских потоков может быть установлен от 0 до 255 (максимально возможное значение в байте).
    0 - самый высокий локальный приоритет. Этот приоритет установлен по умолчанию при запуске потока.

    Продолжение следует......
  • Продолжение темы....

    Для регулировки приложением локальных приоритетов запущенных потоков созданы новые функции:
    51,3 - получить приоритет потока
    51,4 - установить приоритет потока.
    Заодно я создал функцию 51,2 - получить pid текущего потока чтобы не обращаться к функции 9 только для того, чтобы получить только свой pid потока.
    kernel_func.jpg
    kernel_func.jpg (203.55 KiB)
    Viewed 1186 times
    kernel_func2.jpg
    kernel_func2.jpg (140.58 KiB)
    Viewed 1186 times

    Если не будет возражений или замечаний то, приблизительно через месяц, я внесу код в SVN и пояснения в справочник по функциям 68,24 51,2-51,4
  • Эта тема будет про обработку "контролируемых исключений" в ядре колибри

    Предлагаю для повышения отказоустойчивости ядра Колибри, а также приложений разработанных для Колибри, внедрить механизм обработки "контролируемых исключений" page_fault, вызванных в ходе обработки данных при обращении к памяти для записи/чтения .

    Если разработчик ядра, драйвера или приложения желает обезопасить механизм обработки данных при обращении к памяти для записи/чтения (например, к памяти полученной от пользователя), то он может сделать следующие действия:
    1.) Перед обращением к памяти, установить следующие данные для обработчика "контролируемых исключений" ядра:
    - В регистр edi занести сигнатуру - текст 'EXPT'
    - В регистр esi занести адрес, куда должен передать управление обработчик "контролируемых исключений".
    2.) По адресу, указанном в регистре esi разработчик прописывает необходимые действия в случае получения некорректных данных.


    В итоге:
    1. Значительно повышается стабильность (отказоустойчивость) ядра Колибри или приложения при обработке данных.
    2. Упрощается алгоритм проверки данных на их корректность.
    3. Этот алгоритм могут использовать разработчики приложений без обращения к функции 68,24.


    Ниже показан пример применения механизма обработки некорректных данных.
    Когда нам в ядро приходят непроверенные данные от пользователя, то мы устанавливаем данные для обработчика "контролируемых исключений" (строка 5593-5594).
    Теперь если произойдет исключение из-за обращениия к несуществующей памяти (в строке 5596), то исполнение кода начнется с метки .err_exit: (строка 5619) с корректным завершением обработки запроса от пользователя.

    example_ctrl_ex.jpg
    example_ctrl_ex.jpg (171.13 KiB)
    Viewed 1181 times


    В заключение предлагаю внедрить в файл sys32.inc в процедуре page_fault_exc: код обработчика "контролируемых исключений":

    ctrl_exc.jpg
    ctrl_exc.jpg (53.46 KiB)
    Viewed 1181 times


    Если не будет возражений или замечаний, то приблизительно через месяц я внесу код в SVN, а также внесу пояснения в справочник по функции 68,24.
  • turbocat wrote: Sat Feb 17, 2024 10:47 am Jurgen, hello. Changes to critical areas of code, such as the MENUET header, require additional discussion because they affect many programs. Everything after the field i_icon is not standardized and is handled differently in different places (KX extension and GCC extension).
    The patch that you applied, as I understand it, is only needed by your emulator. You either need to figure out how to do it differently. Or he will try to explain why such a decision is necessary. Thank you in advance.
    The proposed changes should not conflict with programs using other header standards. Because this handler is only fired under a few conditions:
    1. A stack overflow exception occurred
    2. The application is ready to handle exception 12
    3. And if the application is ready to handle exception 12, then it must prepare a backup stack according to the requirement set out in the reference book for function 68.24

    If the application does not fulfill the above conditions, then the stack exception handler will not run and the kernel will perform the default actions --> and an exception will occur in the kernel itself.
  • Jurgen,

    I'm glad you managed to navigate the kernel code and even contribute to it, you're welcome. It wasn't a twenty minutes adventure, I suppose :)

    I should have provided my feedback earlier but here it is.


    1. First a non-technical thing. Could you, please, suggest your kernel changes in the kernel forum? Some people were really surprised to see your commits to the kernel because they didn't track this programs/emulators subforum at all. For example, you linked the existing topic on thread priorities in one of your previous posts. Looks like a good place to continue discussion on properties. If there is no suitable topic for the exception stack, feel free to create one. I'm sorry to put this paperwork on you. Thank you.


    2. On the exception stack. Do I understand correctly that what you propose is essentially POSIX sigaltstack but without an additional syscall? In that case I have a design comment.

    Firstly, if it's really POSIX anyway, then why don't we implement that particular syscall for compatibility? Maybe somebody more experienced in porting software like turbocat can say how sigaltstack is currently handled in our ports. If it would be useful to have true sigaltstack instead of a stub, then why not.

    Then, in case we decide not to care about POSIX, I think the most kolibri-style way to implement the exception stack is to pass its pointer to sf68.24 in esi register. This is a very common thing for kolibri, e.g. see how esi is passed to sf4. You can then store the stack pointer to APPDATA structure, say, after pl0_stack field.

    I understand that having the pointer at the fixed location in header makes it easily accessible with a single instruction. That said, there is a significant drawback too. We've got a number of app headers at the moment: MENUET00, MENUET01, MENUET02, and, unfortunately, counting. KX is a work in progress and even a PE patch exists. Having another variation, even compatible, is what we'd really like to avoid. An optional syscall argument is something one can safely ignore. Another app header variation is something a kernel developer has to always keep in their head.


    3. I only looked through your recent posts on priorities so far. Is it something like POSIX nice?
  • Of the minuses that I have already managed to find. This is that I can't use your feature with GCC and TCC. This field is already used for other purposes. I haven't studied how signals work in POXIS, but Ivan's idea about esi seems to have a right to exist.
    Изобретайте колёса каждый раз, когда хотите написать новую программу.
  • dunkaist wrote: Sat Feb 17, 2024 2:01 pm Jurgen,
    .....
    1. First a non-technical thing. Could you, please, suggest your kernel changes in the kernel forum? Some people were really surprised to see your commits to the kernel because they didn't track this programs/emulators subforum at all. For example, you linked the existing topic on thread priorities in one of your previous posts. Looks like a good place to continue discussion on properties. If there is no suitable topic for the exception stack, feel free to create one. I'm sorry to put this paperwork on you. Thank you.
    .....
    Okay, I will repost on thread priorities and stack exclusion in the kernel forum and in future I will post everything related to changes in the kernel on the kernel forum.

    What complies with the forum rules - to create separate topics for individual proposals for editing the kernel, or to make one topic like “Windows OS emulator and kernel changes” and post all proposals for editing the kernel there?


    dunkaist wrote: Sat Feb 17, 2024 2:01 pm .....
    Then, in case we decide not to care about POSIX, I think the most kolibri-style way to implement the exception stack is to pass its pointer to sf68.24 in esi register. This is a very common thing for kolibri, e.g. see how esi is passed to sf4. You can then store the stack pointer to APPDATA structure, say, after pl0_stack field.
    .....
    turbocat wrote: Sat Feb 17, 2024 2:30 pm Of the minuses that I have already managed to find. This is that I can't use your feature with GCC and TCC. This field is already used for other purposes. I haven't studied how signals work in POXIS, but Ivan's idea about esi seems to have a right to exist.
    Fine. I'll rework the stack exception handling mechanism by passing the address of the backup stack to esi register in function 68.24 and post this variant on the kernel forum for discussion.

    dunkaist wrote: Sat Feb 17, 2024 2:01 pm ....
    3. I only looked through your recent posts on priorities so far. Is it something like POSIX nice?
    I try to stick to the Kolibri OS standards. If I'm wrong somewhere, you and others will correct me.