universalisos/docs-extracted/development/kernel-reference-manual.md
Fábio Coutada ae6144a1c5 feat(docs): extract all extractable PikeOS PDF manuals to markdown
- Extract 37 of 45 PDFs under docs/ to docs-extracted/
- Preserve directory structure (apex, cdk, development, platform, etc.)
- Add docs-extracted/index.md with navigation table
- 8 PDFs were 0-byte/empty and could not be extracted
2026-07-06 23:07:19 +01:00

1.1 MiB
Raw Blame History

title source category pages extracted
Kernel Reference Manual docs/development/kernel-reference-manual.pdf development 645 2026-07-06T23:05:34.775436

Kernel Reference Manual

Extracted from docs/development/kernel-reference-manual.pdf (645 pages). Figures, diagrams, and tables may not render accurately in plain text.

PikeOS Kernel

Reference Manual

Am Pfaffenstein 14, D-55270 Klein-Winternheim

Notice: The contents of this document are proprietary to SYSGO GmbH and shall not be disclosed, disseminated, copied, or used except for purposes expressly authorized in writing by SYSGO GmbH. PikeOS Kernel Reference Manual PikeOS D5.0, Document Version D5.0-278

c 2005 2019 SYSGO GmbH

SYSGO GmbH Email: office@sysgo.com Am Pfaffenstein 14 55270 Klein-Winternheim, Germany http://www.sysgo.com

All rights reserved. PikeOS is a trademark of SYSGO GmbH. The designations used to identify other software or hardware products in this publication may be trademarks of their manufacturers or sellers. Contents

1 The PikeOS Kernel API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 1.1 Header File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 1.2 Global Types and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 1.2.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 1.2.2 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 1.2.3 Function Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 1.2.3.1 __aligned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 1.2.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 1.2.4.1 _p4_entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 1.3 Error Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 1.3.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 1.3.2 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 1.4 UIDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 1.4.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 1.4.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 1.4.2.1 p4_uid_valid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 1.4.2.2 p4_uid_eq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 1.4.2.3 p4_uid_match . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 1.4.2.4 p4_uid_match_all . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 1.4.2.5 p4_uid_is_fq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 1.5 Abilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 1.5.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 1.5.2 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 1.6 Timeouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 1.6.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 1.6.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 1.6.2.1 p4_sleep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 1.6.2.2 p4_get_time_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 1.6.2.3 p4_get_time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 1.6.2.4 p4_get_ts_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 1.6.2.5 p4_get_ts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 1.7 Generic Bitmap Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 1.7.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 1.8 Generic Handling of CPU Masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 1.8.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 1.9 Kernel Info Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 1.9.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 1.9.1.1 struct P4_cpu_info_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 1.9.1.2 struct P4_rom_desc_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 1.9.1.3 struct P4_kinfopage_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 1.9.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 1.9.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

4 CONTENTS

     1.9.4  Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
     1.9.5  Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
             1.9.5.1   p4_cpu_info . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
             1.9.5.2   p4_cpu_distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
             1.9.5.3   p4_kinfopage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
             1.9.5.4   p4_my_uid_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
             1.9.5.5   p4_my_uid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
             1.9.5.6   p4_my_thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
             1.9.5.7   p4_my_task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
             1.9.5.8   p4_my_respart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
             1.9.5.9   p4_my_timepart_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
             1.9.5.10 p4_my_timepart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
             1.9.5.11 p4_fast_get_prio_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
             1.9.5.12 p4_fast_get_prio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
             1.9.5.13 p4_my_prio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
             1.9.5.14 p4_my_cpuid_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
             1.9.5.15 p4_my_cpuid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
             1.9.5.16 p4_fast_set_prio_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
             1.9.5.17 p4_fast_set_prio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
             1.9.5.18 p4_kinfo_get_api_version . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
             1.9.5.19 p4_kinfo_get_kernel_build_id . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
             1.9.5.20 p4_kinfo_get_asp_build_id . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
             1.9.5.21 p4_kinfo_get_psp_build_id . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
             1.9.5.22 p4_kinfo_get_regs_size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
             1.9.5.23 p4_kinfo_get_align_mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
             1.9.5.24 p4_kinfo_get_timeout_resolution . . . . . . . . . . . . . . . . . . . . . . . . . 98
             1.9.5.25 p4_kinfo_get_tp_resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
             1.9.5.26 p4_kinfo_get_num_cpu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
             1.9.5.27 p4_kinfo_get_num_respart . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
             1.9.5.28 p4_kinfo_get_num_task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
             1.9.5.29 p4_kinfo_get_num_thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
             1.9.5.30 p4_kinfo_get_num_timepart . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
             1.9.5.31 p4_kinfo_get_num_prio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
             1.9.5.32 p4_kinfo_get_all_pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
             1.9.5.33 p4_kinfo_get_free_pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
             1.9.5.34 p4_kinfo_arch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
             1.9.5.35 p4_kinfo_roms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
1.10 Communication API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
     1.10.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
     1.10.2 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
     1.10.3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
             1.10.3.1 p4_comm_grant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
             1.10.3.2 p4_comm_link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
1.11 Event API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
     1.11.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
     1.11.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
             1.11.2.1 p4_ev_mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
             1.11.2.2 p4_ev_signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

CONTENTS 5

           1.11.2.3 p4_ev_wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

1.12 IPC API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 1.12.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 1.12.1.1 struct P4_message_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 1.12.1.2 struct P4_ipc_result_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 1.12.2 IPC Stages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 1.12.3 IPC system call flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 1.12.4 IPC status flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 1.12.5 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 1.12.6 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 1.12.7 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 1.12.7.1 p4_ipc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 1.12.7.2 p4_ipc_send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 1.12.7.3 p4_ipc_recv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 1.12.7.4 p4_ipc_buf_send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 1.12.7.5 p4_ipc_buf_recv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 1.12.7.6 p4_ipc_buf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 1.12.7.7 p4_ipc_buf_call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 1.12.7.8 p4_ipc_mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 1.13 Interrupt API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 1.13.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 1.13.1.1 struct P4_interrupt_bitmap_str . . . . . . . . . . . . . . . . . . . . . . . . . . 140 1.13.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 1.13.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 1.13.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 1.13.4.1 p4_int_attach_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 1.13.4.2 p4_int_attach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 1.13.4.3 p4_int_detach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 1.13.4.4 p4_int_wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 1.13.4.5 p4_int_grant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 1.13.4.6 p4_int_link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 1.14 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 1.14.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 1.14.1.1 struct P4_short_ex_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 1.14.2 Page Fault and Exception Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 1.14.3 Exception Reply Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 1.14.4 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 1.14.5 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 1.14.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 1.14.6.1 p4_regs_get_fault . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 1.14.6.2 p4_regs_set_fault . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 1.14.6.3 p4_regs_get_epc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 1.14.6.4 p4_regs_set_epc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 1.14.6.5 p4_regs_get_fp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 1.14.6.6 p4_regs_set_fp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 1.14.6.7 p4_regs_get_sp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 1.14.6.8 p4_regs_set_sp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 1.14.6.9 p4_regs_get_arch1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

6 CONTENTS

             1.14.6.10 p4_regs_set_arch1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
             1.14.6.11 p4_regs_get_arch2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
             1.14.6.12 p4_regs_set_arch2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
             1.14.6.13 p4_regs_get_ex_code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
             1.14.6.14 p4_regs_set_ex_code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
             1.14.6.15 p4_regs_get_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
1.15 Mapping API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
     1.15.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
             1.15.1.1 struct P4_sglist_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
     1.15.2 Mapping Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
     1.15.3 Cache Synchronization Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
     1.15.4 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
     1.15.5 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
     1.15.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
             1.15.6.1 p4_mem_map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
             1.15.6.2 p4_mem_unmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
             1.15.6.3 p4_mem_set_attr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
             1.15.6.4 p4_mem_list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
             1.15.6.5 p4_mem_build_sglist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
             1.15.6.6 p4_mem_create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
             1.15.6.7 p4_ioport_map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
             1.15.6.8 p4_ioport_unmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
             1.15.6.9 p4_ioport_create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
             1.15.6.10 p4_mem_read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
             1.15.6.11 p4_mem_write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
             1.15.6.12 p4_mem_clear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
1.16 Thread API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
     1.16.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
             1.16.1.1 struct P4_thread_attr_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
             1.16.1.2 struct P4_thread_create_str . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
     1.16.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
     1.16.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
     1.16.4 Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
     1.16.5 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
             1.16.5.1 p4_thread_create_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
             1.16.5.2 p4_thread_create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
             1.16.5.3 p4_thread_delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
             1.16.5.4 p4_thread_stop_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
             1.16.5.5 p4_thread_stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
             1.16.5.6 p4_thread_resume . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
             1.16.5.7 p4_thread_alarm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
             1.16.5.8 p4_thread_ex_regs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
             1.16.5.9 p4_thread_get_regs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
             1.16.5.10 p4_thread_set_regs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
             1.16.5.11 p4_thread_unblock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
             1.16.5.12 p4_thread_preempt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
             1.16.5.13 p4_thread_except . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
             1.16.5.14 p4_thread_ex_sched_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . 222


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

CONTENTS 7

          1.16.5.15 p4_thread_ex_sched . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
          1.16.5.16 p4_thread_get_sched . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
          1.16.5.17 p4_thread_set_sched . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
          1.16.5.18 p4_thread_ex_priority . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
          1.16.5.19 p4_thread_get_priority . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
          1.16.5.20 p4_thread_set_priority . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
          1.16.5.21 p4_thread_ex_exh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
          1.16.5.22 p4_thread_get_exh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
          1.16.5.23 p4_thread_set_exh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
          1.16.5.24 p4_thread_ex_affinity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
          1.16.5.25 p4_thread_get_affinity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
          1.16.5.26 p4_thread_set_affinity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
          1.16.5.27 p4_thread_get_attr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
          1.16.5.28 p4_thread_yield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
          1.16.5.29 p4_thread_arg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
          1.16.5.30 p4_thread_fpu_on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
          1.16.5.31 p4_thread_fpu_off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
          1.16.5.32 p4_thread_vec_on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
          1.16.5.33 p4_thread_vec_off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

1.17 Task API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 1.17.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 1.17.1.1 struct P4_task_bitmap_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 1.17.1.2 struct P4_task_attr_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 1.17.1.3 struct P4_task_activate_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 1.17.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 1.17.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 1.17.4 Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 1.17.5 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 1.17.5.1 p4_task_donate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 1.17.5.2 p4_task_activate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 1.17.5.3 p4_task_start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 1.17.5.4 p4_task_terminate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 1.17.5.5 p4_task_get_attr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 1.17.5.6 p4_task_hm_register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 1.17.5.7 p4_task_hm_wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 1.17.5.8 p4_task_hm_wake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 1.17.5.9 p4_get_parent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 1.18 Resource Partition API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 1.18.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 1.18.1.1 struct P4_respart_attr_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 1.18.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 1.18.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 1.18.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 1.18.4.1 p4_respart_get_kmem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 1.18.4.2 p4_respart_alloc_aligned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 1.19 Time Partition API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 1.19.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 1.19.1.1 struct P4_tptable_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

8 CONTENTS

             1.19.1.2 struct P4_timepart_wtable_str . . . . . . . . . . . . . . . . . . . . . . . . . . 269
             1.19.1.3 struct P4_timepart_window_attr_str . . . . . . . . . . . . . . . . . . . . . . . 270
     1.19.2 Time partition switch flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
     1.19.3 Time partition window flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
     1.19.4 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
     1.19.5 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
     1.19.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
             1.19.6.1 p4_timepart_load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
             1.19.6.2 p4_timepart_switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
             1.19.6.3 p4_fast_timepart_switch_disable . . . . . . . . . . . . . . . . . . . . . . . . . 281
             1.19.6.4 p4_fast_timepart_switch_enable . . . . . . . . . . . . . . . . . . . . . . . . . 282
             1.19.6.5 p4_timepart_window_get_attr . . . . . . . . . . . . . . . . . . . . . . . . . . 283
1.20 Thread Local Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
     1.20.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
             1.20.1.1 struct P4_tls_area_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
     1.20.2 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
     1.20.3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
             1.20.3.1 p4_thread_tls_register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
             1.20.3.2 p4_tls_register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
             1.20.3.3 p4_tls_ptr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
             1.20.3.4 p4_tls_get_uint8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
             1.20.3.5 p4_tls_get_uint16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
             1.20.3.6 p4_tls_get_uint32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
             1.20.3.7 p4_tls_get_uint64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
             1.20.3.8 p4_tls_get_ptr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
             1.20.3.9 p4_tls_set_uint8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
             1.20.3.10 p4_tls_set_uint16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
             1.20.3.11 p4_tls_set_uint32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
             1.20.3.12 p4_tls_set_uint64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
             1.20.3.13 p4_tls_set_ptr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
             1.20.3.14 p4_tls_init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
             1.20.3.15 p4_tls_uid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
             1.20.3.16 p4_tls_thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
             1.20.3.17 p4_tls_task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
             1.20.3.18 p4_tls_respart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
             1.20.3.19 p4_tls_timepart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
             1.20.3.20 p4_tls_prio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
             1.20.3.21 p4_tls_change_prio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
             1.20.3.22 p4_tls_sync_prio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
             1.20.3.23 p4_tls_cpuid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
1.21 Kernel Level Device Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
     1.21.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
             1.21.1.1 struct P4_device_bitmap_str . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
     1.21.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
     1.21.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
     1.21.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
             1.21.4.1 p4_dev_grant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
             1.21.4.2 p4_dev_link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

CONTENTS 9

          1.21.4.3 p4_dev_call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317

1.22 Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 1.22.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 1.22.1.1 struct P4_trace_client_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 1.22.1.2 struct P4_trace_info_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 1.22.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 1.22.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 1.22.4 Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 1.22.5 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 1.22.5.1 p4_trace_client_register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 1.22.5.2 p4_trace_client_unregister . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 1.22.5.3 p4_trace_server_register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 1.22.5.4 p4_trace_server_unregister . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 1.22.5.5 p4_trace_set_bufsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 1.22.5.6 p4_trace_map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 1.22.5.7 p4_trace_reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 1.23 Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 1.23.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 1.23.1.1 struct P4_thread_bitmap_str . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 1.23.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 1.23.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 1.23.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 1.23.4.1 p4_mon_respart_get_attr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 1.23.4.2 p4_mon_get_task_map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 1.23.4.3 p4_mon_task_get_thread_map . . . . . . . . . . . . . . . . . . . . . . . . . . 334 1.23.4.4 p4_mon_thread_get_attr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 1.23.4.5 p4_mon_thread_get_regs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 1.23.4.6 p4_mon_get_syscall_name . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 1.23.4.7 p4_mon_get_trap_name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 1.23.4.8 p4_strerror . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 1.23.4.9 p4_strerror_r . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 1.23.4.10 p4_mon_get_error_name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 1.23.4.11 p4_mon_task_get_attr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 1.23.4.12 p4_mon_mem_list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 1.23.4.13 p4_mon_memreg_get_attr . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 1.24 Kernel Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 1.24.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 1.24.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 1.24.2.1 p4_kernel_control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 1.25 Cache Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 1.25.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 1.25.2 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 1.25.3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 1.25.3.1 p4_inval_icache_range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 1.25.3.2 p4_inval_icache_range_alias . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 1.25.3.3 p4_flush_dcache_range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 1.25.3.4 p4_sync_dcache_range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 1.25.3.5 p4_inval_dcache_range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

10 CONTENTS

              1.25.3.6   p4_cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
 1.26 Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
      1.26.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
              1.26.1.1   struct P4_memreg_attr_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
      1.26.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
      1.26.3 Data Type Definitions     . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
      1.26.4 Functions      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
              1.26.4.1   p4_memmap_alloc_phys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
              1.26.4.2   p4_memmap_alloc_aligned           . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
 1.27 System Emulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
      1.27.1 Functions      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
              1.27.1.1   p4_sysemu_enter        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
 1.28 User Space Locking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
      1.28.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
              1.28.1.1   struct P4_ulock_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
              1.28.1.2   struct P4_rulock_list_elem_str . . . . . . . . . . . . . . . . . . . . . . . . . . 372
              1.28.1.3   struct P4_rulock_str     . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
      1.28.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
      1.28.3 Data Type Definitions     . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
      1.28.4 Functions      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
              1.28.4.1   p4_ulock_init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
              1.28.4.2   p4_rulock_init     . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
              1.28.4.3   p4_ulock_wait      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
              1.28.4.4   p4_ulock_wake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
 1.29 Mutexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
      1.29.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
              1.29.1.1   struct P4_mutex_str      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
      1.29.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
      1.29.3 Data Type Definitions     . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
      1.29.4 Functions      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
              1.29.4.1   p4_mutex_init      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
              1.29.4.2   p4_mutex_owned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
              1.29.4.3   p4_mutex_lock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
              1.29.4.4   p4_mutex_trylock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
              1.29.4.5   p4_mutex_unlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
 1.30 Condition variables    . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
      1.30.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
              1.30.1.1   struct P4_cond_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
      1.30.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
      1.30.3 Data Type Definitions     . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
      1.30.4 Functions      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
              1.30.4.1   p4_cond_init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
              1.30.4.2   p4_cond_wait       . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
              1.30.4.3   p4_cond_wake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
              1.30.4.4   p4_cond_signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
              1.30.4.5   p4_cond_broadcast        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

CONTENTS 11

1.31 Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 1.31.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 1.31.1.1 struct P4_sem_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 1.31.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 1.31.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 1.31.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 1.31.4.1 p4_sem_init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 1.31.4.2 p4_sem_value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 1.31.4.3 p4_sem_wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 1.31.4.4 p4_sem_trywait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 1.31.4.5 p4_sem_post . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 1.32 Thread Synchronization Barriers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 1.32.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 1.32.1.1 struct P4_barrier_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 1.32.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 1.32.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 1.32.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 1.32.4.1 p4_barrier_init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 1.32.4.2 p4_barrier_wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 1.33 One Time Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 1.33.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 1.33.1.1 struct P4_once_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 1.33.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 1.33.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 1.33.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409 1.33.4.1 p4_once . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409 1.34 Atomic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 1.34.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 1.34.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 1.34.2.1 p4_atomic_write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 1.34.2.2 p4_atomic_add . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 1.34.2.3 p4_atomic_inc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 1.34.2.4 p4_atomic_dec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 1.34.2.5 p4_atomic_or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 1.34.2.6 p4_atomic_bic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 1.34.2.7 p4_atomic_and . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 1.34.2.8 p4_atomic_xor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418 1.34.2.9 p4_atomic_read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 1.34.2.10 p4_atomic_swap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 1.34.2.11 p4_atomic_fetch_and_add . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 1.34.2.12 p4_atomic_fetch_and_or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422 1.34.2.13 p4_atomic_fetch_and_bic . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423 1.34.2.14 p4_atomic_fetch_and_and . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424 1.34.2.15 p4_atomic_fetch_and_xor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 1.34.2.16 p4_atomic_cas_relaxed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 1.34.2.17 p4_atomic_cas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427 1.34.2.18 p4_atomic_fetch_and_cas_relaxed . . . . . . . . . . . . . . . . . . . . . . . . 428 1.34.2.19 p4_atomic_fetch_and_cas . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

12 CONTENTS

              1.34.2.20 p4_atomic_ptr_write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
              1.34.2.21 p4_atomic_ptr_read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
              1.34.2.22 p4_atomic_ptr_cas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
              1.34.2.23 p4_atomic_ptr_swap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
              1.34.2.24 p4_atomic_ptr_fetch_and_cas . . . . . . . . . . . . . . . . . . . . . . . . . . 434
 1.35 Memory Barriers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
      1.35.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
              1.35.1.1 p4_atomic_read_barrier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
              1.35.1.2 p4_atomic_write_barrier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
              1.35.1.3 p4_atomic_barrier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
              1.35.1.4 p4_atomic_acquire_barrier . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
              1.35.1.5 p4_atomic_release_barrier . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
              1.35.1.6 p4_io_write_barrier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
 1.36 Wait Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
      1.36.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
              1.36.1.1 struct P4_waitq_attr_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
      1.36.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
      1.36.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
      1.36.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
              1.36.4.1 p4_waitq_init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
              1.36.4.2 p4_waitq_wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
              1.36.4.3 p4_waitq_wake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
              1.36.4.4 p4_waitq_get_attr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
 1.37 Health Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
      1.37.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
              1.37.1.1 struct P4_hm_error_str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
      1.37.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
      1.37.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
      1.37.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
              1.37.4.1 p4_hm_register_handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
              1.37.4.2 p4_hm_wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
              1.37.4.3 p4_hm_register_bitmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
              1.37.4.4 p4_hm_inject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
              1.37.4.5 p4_hm_raise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
              1.37.4.6 p4_hm_panic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
 1.38 KDEV User Space API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
      1.38.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
              1.38.1.1 p4_kdev_alert_module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
              1.38.1.2 p4_kdev_alert_part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
              1.38.1.3 p4_kdev_discover_gate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
              1.38.1.4 p4_kdev_ping_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
              1.38.1.5 p4_kdev_ping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
              1.38.1.6 p4_kdev_spawn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
              1.38.1.7 p4_kdev_dup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
              1.38.1.8 p4_kdev_open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
              1.38.1.9 p4_kdev_descend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
              1.38.1.10 p4_kdev_negotiate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
              1.38.1.11 p4_kdev_close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

CONTENTS 13

          1.38.1.12 p4_kdev_pstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
          1.38.1.13 p4_kdev_control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
          1.38.1.14 p4_kdev_read_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
          1.38.1.15 p4_kdev_write_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
          1.38.1.16 p4_kdev_map_to . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
          1.38.1.17 p4_kdev_discard_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
          1.38.1.18 p4_kdev_test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
          1.38.1.19 p4_kdev_psync . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
          1.38.1.20 p4_kdev_lseek_syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
          1.38.1.21 p4_kdev_unlink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
          1.38.1.22 p4_kdev_rename . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
          1.38.1.23 p4_kdev_dir_create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
          1.38.1.24 p4_kdev_dir_read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
          1.38.1.25 p4_kdev_statvfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
          1.38.1.26 p4_kdev_close_all . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
          1.38.1.27 p4_kdev_read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
          1.38.1.28 p4_kdev_write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
          1.38.1.29 p4_kdev_lseek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
          1.38.1.30 p4_kdev_discard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
          1.38.1.31 p4_kdev_discover_prov . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556

1.39 KDEV Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557 1.39.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557 1.39.1.1 struct drv_gate_config_t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557 1.39.1.2 struct drv_status_t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558 1.39.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560 1.39.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565 1.39.4 Function Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566 1.39.4.1 drv_int_handler_t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566 1.40 Processor Speculation Fences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567 1.40.1 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567 1.41 Psp_kdev_decl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568 1.41.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568 1.41.1.1 struct P4_romboot_anchor_str . . . . . . . . . . . . . . . . . . . . . . . . . . 568 1.41.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569 1.41.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569 1.42 File_system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571 1.42.1 Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571 1.42.1.1 struct _vm_sockaddr_reserved_vector_t . . . . . . . . . . . . . . . . . . . . . 571 1.42.1.2 struct vm_sockaddr_vector_t . . . . . . . . . . . . . . . . . . . . . . . . . . . 571 1.42.1.3 struct vm_sockaddr_ip4_vector_t . . . . . . . . . . . . . . . . . . . . . . . . . 571 1.42.1.4 struct vm_sockaddr_ip6_vector_t . . . . . . . . . . . . . . . . . . . . . . . . . 572 1.42.1.5 struct vm_sockaddr_storage_vector_t . . . . . . . . . . . . . . . . . . . . . . 572 1.42.1.6 struct _vm_sockaddr_reserved . . . . . . . . . . . . . . . . . . . . . . . . . . 572 1.42.1.7 struct vm_sockaddr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 1.42.1.8 struct vm_sockaddr_ip4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 1.42.1.9 struct vm_sockaddr_ip6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574 1.42.1.10 struct vm_sockaddr_storage . . . . . . . . . . . . . . . . . . . . . . . . . . . 575 1.42.2 Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

14 CONTENTS

   1.42.3 Data Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
   1.42.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
           1.42.4.1 p4_perm_ok . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580

2 Kernel Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581 A The ROM Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584 A.1 Building the ROM Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585 A.1.1 RBX Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585 A.1.1.1 Basic Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585 A.1.1.2 The RBX Root Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586 A.1.1.3 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 A.1.1.4 Memregions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 A.1.1.5 Partroms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 A.1.1.6 The Root Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 A.1.1.7 PSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588 A.1.1.8 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588 A.2 Physical Memory Partitioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591 A.2.1 Partition ROM Regions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592 A.2.2 Memory Regions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592 A.2.3 Interactions with PSP-defined Memory Regions . . . . . . . . . . . . . . . . . . . . . . . 593 A.2.4 Considerations on num_respart and num_mem_region . . . . . . . . . . . . . . . . . 594 A.2.5 Memregions in Partition Memory Requirements . . . . . . . . . . . . . . . . . . . . . . . 594 A.2.5.1 Shared Memory Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595 A.2.5.2 Partition Cold / Warm Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595 A.2.6 Defining Memory Regions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595 A.2.6.1 Modular Configuration Considerations . . . . . . . . . . . . . . . . . . . . . . 596 A.2.6.2 Partition ROM Image Definitions . . . . . . . . . . . . . . . . . . . . . . . . . 597 A.2.6.3 Memory Region Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . 597 A.3 Building the ROM Image(s) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598 A.3.1 Merging ROM Images (e.g. for Qemu) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599 A.4 Binary Configuration Data and Converter Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599 A.4.1 Configuration Converter (pikeos-configconv) . . . . . . . . . . . . . . . . . . . . . . . . . 600 A.4.1.1 Conversion of XML to Binary Configuration Files . . . . . . . . . . . . . . . . . 600 A.4.1.2 Architecture Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601 A.4.2 XML Input File Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601 A.4.2.1 XML Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602 A.4.2.2 Supported XSD Subset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602 A.4.2.2.1 XSD File Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 602 A.4.2.2.2 Import Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . 603 A.4.2.2.3 Schema Element Declarations . . . . . . . . . . . . . . . . . . . . . 604 A.4.2.2.4 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605 A.4.2.3 Base Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605 A.4.2.3.1 Floats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606 A.4.2.3.2 ID / IDREF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606 A.4.2.3.3 anyURI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607 A.4.2.3.4 Extended Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607 A.4.2.4 Standard Extended Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608 A.4.2.5 User-Defined Simple Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608 A.4.2.5.1 Contiguous Enumeration (enum) Types . . . . . . . . . . . . . . . . 609

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

CONTENTS 15

                 A.4.2.5.2 Explicit Enumeration (enum) Values . . . . . . . . . . . . . . . . . . 612
                 A.4.2.5.3 Bit Field Enumeration (enum) Types . . . . . . . . . . . . . . . . . . 612
                 A.4.2.5.4 Alias Simple Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
       A.4.2.6   Union Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
       A.4.2.7   Struct Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
                 A.4.2.7.1 Group References . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
                 A.4.2.7.2 Any Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
       A.4.2.8   Sorted and Indexed Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
                 A.4.2.8.1 Multi-Step Sort and Index Keys . . . . . . . . . . . . . . . . . . . . . 635
       A.4.2.9   ID and IDREF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
       A.4.2.10 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640
       A.4.2.11 Relocation Entries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640
 A.4.3 Binary Format Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640
       A.4.3.1   CRC Checksums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
 A.4.4 Access Function and Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644


                       c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

1 The PikeOS Kernel API

1.1 Header File

Header file to include, providing functions of libp4 and definitions: #include <p4.h>

1.2 Global Types and Constants

This section describes data types and constants used within the kernel API.

1.2.1 Defines

  P4_FEATURE_32BIT
       PikeOS feature flag indicating a 32-bit processor.
        Description:
        P4_FEATURE_32BIT and P4_FEATURE_64BIT can be used to determine the current compile environ-
        ment. Either one of them is set.

  P4_FEATURE_64BIT
       PikeOS feature flag indicating a 64-bit processor.
        Description:
        P4_FEATURE_32BIT and P4_FEATURE_64BIT can be used to determine the current compile environ-
        ment. Either one of them is set.

  P4_FEATURE_MMU
       PikeOS feature flag indicating MMU support.

  P4_FEATURE_FPU
       PikeOS feature flag indicating FPU support.

  P4_FEATURE_VECTOR
       PikeOS feature flag indicating support of a vector unit.

  P4_FEATURE_TS
       PikeOS feature flag indicating a user readable time stamp counter.

  P4_FEATURE_IOPORT
       PikeOS feature flag indicating a IO port support.

  P4_NEED_ICACHE_COHERENCY
       PikeOS feature flag indicating that the architecture requires synchronization of data and instruction
       caches on application loading to ensure coherent instruction caches.


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Global Types and Constants 17

P4_FEATURE_INVAL_ICACHE_RANGE PikeOS feature flag indicating that the architecture supports synchronization of data and instruction caches in user space.

P4_FEATURE_FLUSH_DCACHE_RANGE PikeOS feature flag indicating that the architecture supports data cache flush operations in user space.

P4_FEATURE_SYNC_DCACHE_RANGE PikeOS feature flag indicating that the architecture supports data cache write-back operations in user space.

P4_FEATURE_INVAL_DCACHE_RANGE PikeOS feature flag indicating that the architecture supports data cache invalidation operations in user space.

P4_API_VERSION Kernel API version information. Description: The kernel API version information consists of a major and minor number part. The major part is kept in the upper 16 bits, the minor part is kept in the lower 16 bits. The API version information is updated on every kernel API change. As long as the API is compatible with previous versions, only the minor number is incremented. Otherwise the major number is incremented and the minor part is set to zero again.

P4_API_MAJOR Kernel API major version number.

P4_API_MINOR Kernel API minor version number.

P4_ARCH_ALIGN Architecture minimum alignment. Description: The minimum alignment usually reflects the size of a cache line on an architecture, or if an ASP supports multiple processors, the largest of the supported processors cache line sizes.

p4_offsetof (s, m) Offset of structure member.

     Parameters:
             s structure data type
            m member name
     Returns:
     Return the offset of a member m within data structure s.

p4_countof (arr) Number of elements in an array.

     Parameters:
           arr Array


                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

18 The PikeOS Kernel API

       Returns:
       Return the number of elements in array arr

 P4_ROUNDUP (n, a)
      Round up to a power of two.
       Description:
       This macro rounds up the value n to the next multiple of a.
       This can be used for unsigned int, unsigned long, and unsigned long long values for n. n is guaran-
       teed to be evaluated only once.

       Note:
       The macro assumes that a is a constant, and it will possibly evaluate the argument multiple times.

       Parameters:
               n Value to round up
               a Alignment, must be a power of two.
       Returns:
       Returns n rounded up and aligned to a.

 P4_ROUNDDOWN (n, a)
      Round down to a power of two.
       Description:
       This macro rounds down the value n to the previous multiple of a.
       This can be used for unsigned int, unsigned long, and unsigned long long values for n. n is guaran-
       teed to be evaluated only once.

       Note:
       The macro assumes that a is a constant, and it will possibly evaluate the argument multiple times.

       Parameters:
               n Value to round down
               a Alignment, must be a power of two.
       Returns:
       Returns n rounded down and aligned to a.

 P4_STRINGIFY (x)
      Helper macro to expand the symbol and get a string of the result.

       Parameters:
               x Symbol to be macro expanded and converted to a string
       Returns:
       Macro expanded x as a string.

 P4X_STRINGIFY (x)


 P4_CONCAT_SYM (A, B)


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Global Types and Constants 19

     Description:
     Helper macro to concatenate two symbols.
     Both symbols are macro expanded before being concatenated.

     Parameters:
               A IN: A and B are two symbols to be concatenated
               B IN: A and B are two symbols to be concatenated
     Returns:
     a single symbol consisting of the two input parts.

P4_BIC (x, c)

P4_PTRDIFF (a, b)

P4_STATIC_ASSERT (X)

     Description:
     Static assertion, i.e., compile time assertion.
     Can be used on anything the compiler can compute. This generates a dummy declaration, so it can be
     put wherever declarations can be put.

     Parameters:
               X is an expression to be checked to be true at compile time.
     Note:
     The macro makes use of compiler defined macros.

P4_NUM_PRIO Number of scheduling priority levels (32, 64, 128 or 256).

P4_NUM_KPRIO Number of kernel-scheduling priority levels (32), not accessible from userspace.

P4_NUM_TIMEPART Number of supported time partitions.

P4_NUM_RESPART Number of supported resource partitions.

P4_NUM_TASK Number of supported tasks.

P4_NUM_THREAD Number of supported threads per task.

P4_UID_SHIFT_RESPART Shifts of respart component in UID.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

20 The PikeOS Kernel API

 P4_UID_SHIFT_TASK
      Shifts of task component in UID.

 P4_UID_SHIFT_THREAD
      Shifts of thread component in UID.

 P4_UID_INVALID_FLAG
      General "invalid" flag in UID.

 P4_UID_MASK_RESPART
      Masks of respart component in UID.

 P4_UID_MASK_TASK
      Masks of task component in UID.

 P4_UID_MASK_THREAD
      Masks of thread component in UID.

 P4_NAMELEN
      Maximum length for names in the PikeOS kernel API, including a terminating NUL character.

 P4_NUM_CPU
      Number of supported processors.

 P4_NUM_WAITQ
      Number of supported wait queues.

 FALSE
      Definition for FALSE.

 TRUE
        Definition for TRUE.

 P4_BYTE_MAX
      Limit for basic data type, unsigned byte.

 P4_INTID_INVALID
      Invalid P4 Interrupt ID.

 P4_UINT8_MAX
      Limit for basic data type, unsigned 8 bit integer.

 P4_UINT16_MAX
      Limit for basic data type, unsigned 16 bit integer.

 P4_UINT32_MAX
      Limit for basic data type, unsigned 32 bit integer.

 P4_UINT64_MAX
      Limit for basic data type, unsigned 64 bit integer.


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Global Types and Constants 21

P4_SINT8_MAX Upper limit for basic data type, signed 8 bit integer.

P4_SINT16_MAX Upper limit for basic data type, signed 16 bit integer.

P4_SINT32_MAX Upper limit for basic data type, signed 32 bit integer.

P4_SINT64_MAX Upper limit for basic data type, signed 64 bit integer.

P4_SINT8_MIN Lower limit for basic data type, signed 8 bit integer.

P4_SINT16_MIN Lower limit for basic data type, signed 16 bit integer.

P4_SINT32_MIN Lower limit for basic data type, signed 32 bit integer.

P4_SINT64_MIN Lower limit for basic data type, signed 64 bit integer.

P4_bool_t Boolean type.

P4_TIME_MIN Lower limit for P4_time_t type (unsigned 64 bit integer) Description: Specifies an absolute 64-bit wide time logically representing zero time.

P4_TIME_MAX Upper limit for P4_time_ type (unsigned 64 bit integer) Description: Specifies an absolute 64-bit wide time logically representing an infinite time.

      Note:
      Since the maximum specifiable timeout (P4_TIMEOUT_INFINITE) is 60-bit wide, P4_TIME_MAX
      should not be used as timeout value to avoid possible interference with the time partition switching
      related timeouts.

1.2.2 Data Type Definitions

P4_byte_t Basic data type, unsigned byte. P4_uint8_t Basic data type, unsigned 8 bit integer. P4_uint16_t Basic data type, unsigned 16 bit integer. P4_uint32_t Basic data type, unsigned 32 bit integer. P4_uint64_t Basic data type, unsigned 64 bit integer.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

22 The PikeOS Kernel API

 P4_sint8_t Basic data type, signed 8 bit integer.
 P4_sint16_t Basic data type, signed 16 bit integer.
 P4_sint32_t Basic data type, signed 32 bit integer.
 P4_sint64_t Basic data type, signed 64 bit integer.
 P4_cpureg_t Machine register size of the target architecture.
       The dataword size depends on the architecture (unsigned long). On 32-bit platforms it will be 32-bit and
       on 64-bit platforms it will be 64-bit.
 P4_address_t Numerical representation of a virtual address.
 P4_phys_addr_t Numerical representation of a physical address.
 P4_size_t Numerical representation of sizes.
 P4_task_t P4 task numbers.
 P4_thr_t P4 thread numbers.
 P4_prio_t P4 priorities.
 P4_intid_t P4 interrupt IDs.
 P4_devid_t P4 kernel level device IDs.
 P4_cpuid_t P4 processor logical numbers.
 P4_waitqid_t P4 wait queue IDs.
 P4_cpumask_t P4 bitmask of processors, the bit positions correspond to a processors logical number.
 P4_uid_t Type definition for PikeOS UIDs.
       PikeOS UIDs are a combination of task number, thread number, time partition, and resource partition
       encoded into a P4_uid_t data type object.
       Task and thread number uniquely identify a thread in the system. The time partition included in the UID
       is included for informational purposes only and will be ignored by the kernel when a UID is passed as a
       parameter in a service call.
 P4_timeout_t Timeout specifier.
       Timeouts are stored in a 64-bit data object (unsigned long long on 32-bit platforms). The data object
       contains:


          • the timeout value in nanosecond resolution stored in 60-bits,
          • a flag indicating whether the timeout value is a relative or an absolute timeout,
               and
          • two bit flags to control where to wait for time partition switching related timeouts.


       Note:
       Algebraic operations on timeout values can cause an overflow which sets or clears the timeouts status
       bits. Incorrect combinations of timeout values and flags raise an error when used.
 P4_ex_code_t Exception message status code.
       This data type contains an exception status code when an exception message is sent by the kernel.
       The exception status code keeps a trapcode in its upper bits and, in the case of a page fault exception,
       some page fault flags in its lower bits.

       Note:


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Global Types and Constants 23

        Use P4_EX() (see section 1.14.4), P4_EX_TRAP_CODE() (see section 1.14.4), and
        P4_EX_TRAP_INFO() (see section 1.14.4) macros to extract trapcode and additional trapcode
        information like page fault or health monitoring flags.
        Reply to an exception with P4_EX_CONTINUE or P4_EX_NEXT_EXCEPTION.

P4_access_t Mapping flags for access permissions and cache attributes. The Mapping Flags (see section 1.15.2) are of this type. P4_cache_op_t Cache operation. The "cache operations" in the cache API are of this type. P4_atomic_t Atomic data type, 32-bit. This type is used for atomic operations.

        Note:
        The atomic data type is a 32-bit unsigned integer.

P4_atomic_ptr_t Atomic pointer type. This type is used for atomic pointer operations.

1.2.3 Function Type Definitions

1.2.3.1 __aligned

P4 internal time, 64-bit in nanoseconds.

Synopsis:

typedef P4_uint64_t P4_time_t __aligned(8)

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

24 The PikeOS Kernel API

1.2.4 Functions

1.2.4.1 _p4_entry

Entry Point declaration for PikeOS bare userspace programs.

Synopsis:

void _p4_entry(void)

Description: This function is the entry point for bare PikeOS userspace programs. The function is normally wrapped via personalities layers such as the PikeOS native personality, and needs not to be explicitly defined by userspace programs. The function does not correspond to a syscall, and is not implemented by the library layer.

Returns: The function does not return.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Error Codes 25

1.3 Error Codes

This section describes all error codes used within the kernel API. When dealing with numerical error codes, the relation between the code and the human readable representation shown in the table below can be retrieved using the function p4_mon_get_error_name() (see section 1.23.4.10).

1.3.1 Defines

  P4_E_NUM


       Description:
       Total number of defined error codes

  P4_E_OK      0

       Description:
       No error.
       Generated only if no software layer returns an error.
       Note that if the return code is not P4_E_OK, intermediate software layers and frameworks may deduce
       that an error occurred unless specified otherwise.

  P4_E_TRUNC        1

       Description:
       The transferred data was truncated and it is unclear how much was transferred, or it is impossible to
       recover the rest of the data, or to send it again. This should be used as a warning: the operation was
       started and finished, without the need to repeat it, but it could not be completed fully successfully.
       This is an exceptional warning code: it does not indicate a total failure.
       Note that this must not be returned during open() requests, because the framework only recognises
       P4_E_OK as a success.
       Raised by:
       Driver.
       Contrasts with:
       P4_E_LIMIT: The request was not started because some other limit was not OK, e.g. some resource
       we cannot wait for is not available to do the operation now.
       P4_E_SIZE: The buffer is too small or too large, for the message, e.g. if the underlying system always
       requires full block transfers not matching the buffer size.
       P4_E_ALIGN: The buffer size or pointer does not obey alignment constraints imposed by the driver.
       P4_E_TIMEOUT: the operation could not be started because a start condition was not fulfilled within
       the limits of the allowed timeout.

  P4_E_PERM        2

       Description:
       Access permissions are insufficient.


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

26 The PikeOS Kernel API

     Raised by:
     Typically by the framework (e.g. for read()/write()). Driver callbacks may place the burden for checking
     this on the driver, e.g. in ioctl() and discard().
     Contrasts with:
     P4_E_RESTRICTED: In inherent system or configuration setting apart from the file/port/gate access
     permission bits lead to the the request to be denied. E.g., the file system is read-only.
     P4_E_NOABILITY: The requester needs an ability to be allowed, and this ability is not assigned to the
     requester.
     P4_E_CONFIG: There is a configuration setting not related to permissions that means the operation
     cannot proceed. E.g. a configured setting does not match the devices.

 P4_E_RESTRICTED           3

     Description:
     Access to the operation is inherently restricted, e.g. by configuration, but not by mere permission flags
     that apply to the specific file/port/gate.
     Raised by:
     Driver.
     Contrasts with:
     P4_E_PERM, P4_E_NOABILITY, P4_E_CONFIG.

 P4_E_NOABILITY        4

     Description:
     There is a system ability that controls access, and the requester does not have that ability.
     Raised by:
     Framework.
     Contrasts with:
     P4_E_PERM, P4_E_RESTRICTED, P4_E_CONFIG.

 P4_E_NOTIMPL     5

     Description:
     The operation is not implemented in this version of the system, and thus the request is not supported.
     Raised by:
     Framework, driver.

 P4_E_CONFIG      6

     Description:
     Something in the configuration prevents successful operation. This is the generic fallback for configura-
     tion related errors if no other error code applies.
     Raised by:
     Framework, driver.
     Contrasts with:


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Error Codes 27

     P4_E_LIMIT: Some configured or inherent limit that the framework/driver cannot block on and that is no
     system memory resource would be exceeded, so the request cannot be fulfilled.
     P4_E_NOKMEM: The framework or kernel is out of system memory to fulfill this request.
     P4_E_NOABILITY, P4_E_RESTRICTED.

P4_E_OVERMAP 7

     Description:
     An error in the mapping API: the page that is requested for mapping is already mapped. It would be
     re-mapped, and the request currently did not precede because of that. I.e., the caller tried to create a
     mapping for a virtual memory area that is already mapped and did not set the P4_M_REPLACE bit.
     Raised by:
     Framework.

P4_E_BADMAP 8

     Description:
     An error in the mapping API: a page needed for the request is not there.
     Raised by:
     Framework.

_P4_E_RESERVED4 9

     Description:
     This value is reserved, it was used in the past and should not be used anymore.
     History: This used to be called P4_E_INVAL_MEM, for which P4_E_INVAL (for a wrong address of
     whatever kind) or P4_E_PAGEFAULT (for an actual page fault in the kernel) should be used in new
     code.

P4_E_PAGEFAULT 10

     Description:
     An access to a pointer (i.e., a virtual address) caused or would cause a pagefault, therefore the operation
     cannot be fulfilled. This may be because for example, a memory mapping is missing, or is protected,
     or in the case of mismatching caching attributes (e.g., memory mapped as uncached, when cached
     memory is expected).
     Raised by:
     Framework. Drivers may produce these indirectly by using framework functions that return this code.
     Contrasts with:
     P4_E_INVAL

P4_E_SIZE 11

     Description:
     There is something wrong (other than the alignment) with the passed (buffer) size. Typically, the size
     is either to larger or too small. E.g., a message is too big: an IPC operation was performed and the
     receiver specified a data buffer or mapping that was not large enough to hold the entire message.


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

28 The PikeOS Kernel API

     Raised by:
     Framework. Rarely, drivers have additional constraints on sizes and may produce this. More typically,
     min/max sizes are already set up so that the framework can produce this error and the driver does not
     need to do this. In that case, a driver should assert() the correct size instead of returning an error.
     Contrasts with:
     P4_E_ALIGN: if the size (or an address) is not properly aligned.
     P4_E_OVERFLOW: if there was a numeric overflow or underflow or if a numeric type cannot represent
     a given number. This is typically not related to buffer sizes, but e.g. to file positions.

 P4_E_ALIGN    12

     Description:
     Some size or pointer or a combination of several sizes and/or pointers is not properly aligned for the
     request to be fulfilled.
     Raised by:
     Framework, driver.
     Contrasts with:
     P4_E_SIZE, P4_E_BADMEM.

 P4_E_INVAL   13

     Description:
     Catch-all error code for any invalid parameter or combination of parameters. This should be avoided
     and instead, one of the more specific error codes should be used instead, if possible.
     Raised by:
     Framework, driver.
     Contrasts with:
     P4_E_BADMEM: An address is appropriate.
     P4_E_SIZE: A size parameter is erroneous.
     P4_E_ALIGN: There is an alignment problem among the parameters.
     P4_E_NAME: Some problem was found related to a name (i.e., a string).
     P4_E_BADUID: A thread number or an UID or a part thereof is invalid.
     P4_E_BADTASK: A task number is invalid.
     P4_E_BADTIMEOUT: A timeout parameter is either too far in the future or is in the past.
     Possibly other error codes are also more specific.

 _P4_E_RESERVED1       14

     Description:
     This value is reserved, it was used in the past and should not be used anymore.
     History: This used to be called P4_E_HANDLE, for which P4_E_INVAL should be used in new code.

 P4_E_NAME    15

     Description:


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Error Codes 29

     The given name, a string, is too long. For historical reasons driver framework code usually returns
     P4_E_INVAL if invalid names are passed which includes missing null termination after the maximum
     string length. P4_E_NAME is reserved to be used by drivers (like volume providers) indicating that
     their maximum supported name length is shorter than the one supported by the framework. By using
     P4_E_NAME compliance to e.g. APEX can be ensured where there is an explicit differentiation between
     too long and syntactically invalid names.
     Raised by:
     Driver.
     Contrasts with:
     P4_E_NOENT: The name was good in principal, but the address item was not found.

P4_E_BADTIMEOUT 16

     Description:
     The passed timeout value is either too far in the future or is in the past. Other invalid timeouts are
     handled by P4_E_INVAL, e.g., if bit-combinations are not supported. The reason for the distinction is
     the sliding time window PikeOS uses: if the request is outside the bounds to identify exactly the time,
     then this error is raised.
     Raised by:
     Framework.
     Contrasts with:
     P4_E_INVAL: The timeout parameter is inherently wrong in other ways but too far in future/past.
     P4_E_TIMEOUT: The timeout parameter was good, has expired before the operation could be started.
     Or non-blocking operation was selected and the request could not be started because an event that the
     system could principally wait for has not happened.

P4_E_BADUID 17

     Description:
     A thread number, task number in an UID, resource partition ID, or an UID or a part thereof is invalid or
     missing or inappropriate for the given request. This is neither for time-partition IDs, nor for static prob-
     lems with ranges of IDs. For example, this is raised when calling p4_event_signal() or p4_ipc_send()
     (see section 1.12.7.2) with a UID referencing a thread that does not exist.
     Raised by:
     Framework.
     Contrasts with:
     P4_E_RANGE: For IDs that are out of their inherent static range, e.g., resource partition/thread/task
     IDs that are larger than the maximum partition PikeOS supports.
     P4_E_BADTASK: Used for invalid task numbers.

P4_E_BADTASK 18

     Description:
     A task number is invalid or missing or inappropriate for the given request.
     Raised by:
     Framework.


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

30 The PikeOS Kernel API

     Contrasts with:
     P4_E_BADUID: If a part of an UID is invalid.

 P4_E_NOKMEM        19

     Description:
     System or kernel memory is missing to fulfill the request. This error code is specifically for KMEM that
     can be reclaimed by the kernel. I.e., there may be a chance that if the requester returns KMEM-related
     items, a repeated request may not cause P4_E_NOKMEM.
     Raised by:
     Framework.
     Contrasts with:
     P4_E_OOMEM: Out-of-memory of non-reclaimable memory or any other non-KMEM memory.
     P4_E_LIMIT: Some other resource apart from memory was exhausted.

 P4_E_OOMEM       20

     Description:
     The request cannot be fulfilled because of lack of available memory. This error is not about KMEM,
     but about memory buffers that have no more space. Typically, the requester has no way to rectify this,
     because there is no easy way to deallocate memory. This is also for memory that is not reclaimable at
     all.
     Raised by:
     Framework. Drivers cannot/must not produce this, because they cannot do dynamic memory alloca-
     tion/deallocation, but must allocate all possible memory at init time. At init time, drivers may pass
     through this error code when raised by an API function they invoke, but must not originally raise this.
     Contrasts with:
     P4_E_NOKMEM: Specifically, the kernel KMEM for the given partition has not enough pages to fufil the
     request.
     P4_E_LIMIT: Some other resource apart from memory was exhausted.

 P4_E_NOENT       21

     Description:
     The addressed entity was not found.
     Raised by:
     Framework.

 P4_E_BUSY    22

     Description:
     The addressed resource cannot currently be used, because it is not available or busy. The resource
     cannot be waited for (i.e., this cannot be rectified by providing a longer timeout or otherwise block,
     because blocking is not possible for this resource or this request to the resource).
     Raised by:
     Framework, driver.


                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Error Codes 31

     Contrasts with:
     P4_E_TIMEOUT: We could in principle block to wait that the operation can proceed, but there was no
     timeout or the timeout ran out.

_P4_E_RESERVED5 23

     Description:
     This value is reserved, it was used in the past and should not be used anymore.
     History: This used to be called P4_E_INCOMPLETE and was a very specific error code the PSSW
     raised whenever a thread would raise two requests. The error condition is gone, because blocking was
     removed from the PSSW, so the error code was removed, too.

P4_E_EXIST 24

     Description:
     The addressed resource cannot be created again or some resource cannot be moved into the ad-
     dressed place, because that place is already occupied. E.g., a directory already exists.
     Raised by:
     Framework, driver.

P4_E_TIMEOUT 25

     Description:
     A resource is not avaible and the request was blocking until the given timeout and that timeout has
     expired before the resource became avaible. This is also raised if the timeout was P4_TIMEOUT_NULL
     and the resource was not available, even if this does not envolve waiting.
     Raised by:
     Framework. The driver returns this implicitly by framework functions that raise this.
     Contrasts with:
     P4_E_BUSY, P4_E_STATE.

P4_E_LIMIT 26

     Description:
     Limits other than memory, etc. are exhausted. There was no attempt to do the request, i.e., this is an
     error condition, not a warning about partially completed requests.
     Raised by:
     Kernel, driver.
     Contrasts with:
     P4_E_NOKMEM: For exhausted KMEM.
     P4_E_OOMEM: For other exhausted memory.
     P4_E_TIMEOUT: For exhausted time to wait for a resource.
     P4_E_TRUNC: For a non-erroneous, partial completion of a request.

P4_E_IO 27

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

32 The PikeOS Kernel API

     Description:
     The addressed hardware has indicated an error or is inaccessible.
     Raised by:
     Driver.
     Contrasts with:
     P4_E_STATE, P4_E_BUSY, P4_E_TIMEOUT.

 P4_E_STATE    28

     Description:
     The current state of the device or resource is such that the request cannot be served. This is typically a
     problem with the order of events: by doing the right thing (possibly somewhere else), the problem may
     go away.
     Raised by:
     Framework, driver.
     Contrasts with:
     P4_E_BUSY, P4_E_IO, P4_E_TIMEOUT.

 P4_E_CANCEL       29

     Description:
     The request was cancelled, i.e., the thread that did this was kicked out of the system call be-
     fore completing the request. Cancellation may happen because another thread has performed a
     p4_thread_ex_regs() (see section 1.16.5.8) operation on this thread, the thread was moved to another
     time partition, or the thread was migrated to another CPU.
     Raised by:
     Framework.

 P4_E_ABORT       30

     Description:
     The request was aborted because the IPC partner vanished. This is only raised by the IPC subsystem.
     Tracing is in post-mortem state.
     Raised by:
     Framework.

 P4_E_EVENT    31

     Description:
     The system call returns because an event was received, i.e., another thread has send a signal using
     p4_ev_signal() (see section 1.11.2.2). This is typically returned by the IPC subsystem which can wait
     simultaneously for an IPC and an event.
     Raised by:
     Framework.


                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Error Codes 33

P4_E_NOCONTAINER 32

     Description:
     The addressed resource is not a container-typed thing, but should be. E.g., a file system may have
     operations that only work on directories, but the addressed resource is no directory.
     Raised by:
     Driver.

P4_E_MISMATCH 33

     Description:
     The addressed resource is of a type that cannot be handled by the request. E.g., if the resource is a
     directory, but the request only works on non-directories, this could be raised.
     Raised by:
     Driver.

P4_E_OOFILE 34

     Description:
     Out of files, i.e., there are no more file handles that can be allocated.
     Raised by:
     Framework. In some cases, drivers might raise this if they have their own handles.
     Contrasts with:
     P4_E_OOMEM: Out of memory.

P4_E_SYS 35

     Description:
     This indicates that an error occured one software layer below the one returning this code, typically when
     another function used internally returns an unexpected error.
     This code used to be popular when P4_e_t and vm_e_t were different types in PikeOS 3.x. To avoid
     translating error codes, VM_E_SYS would be returned for any P4_E_* different from P4_E_OK. I.e.,
     in general, this was raised when the translation from P4_E to VM_E encountered an unexpected error
     code that could not be translated.
     This error code should be avoided, however, because it does not clearly indicate what exactly went
     wrong and how to correct the problem. If possible, more specific error codes should be returned.
     Raised by:
     Framework or drivers using other software stacks or other drivers.
     Contrasts with:
     P4_E_IO: communication with hardware or underlying frameworks went wrong.

_P4_E_RESERVED2 36

     Description:
     This value is reserved, it was used in the past and should not be used anymore.
     History: This used to be called VM_E_INDICATED, for which P4_E_IO should be used in new code.


                                   c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

34 The PikeOS Kernel API

 _P4_E_RESERVED3             37

       Description:
       This value is reserved, it was used in the past and should not be used anymore.
       History: This used to be called VM_E_NOT_INITIALIZED, which is never returned by new code.

 P4_E_OVERFLOW              38

       Description:
       Indicates that there was a numeric overflow or underflow in arithmetics or that some number cannot be
       represented because it is out of range. E.g., this may happen when file positions are manipulated.
       Contrasts with:
       P4_E_SIZE: If sizes are out of range not due to overflows or limited types, but due to dynamic or static
       constraints e.g. due to configuration. This error is often related to buffer sizes.

 P4_E_ECCOK           39

       Description:
       Indicates that there was an ECC check error, but that error could be corrected and the data is intact and
       was successfully transferred. This is usually a warning condition, not an error. Note that this must not
       be returned during open() requests, because the framework only recognises P4_E_OK as a success.
       Raised by:
       Driver.
       Contrasts with:
       P4_E_OK: There was no ECC error and everything is fine.
       P4_E_ECCBAD: There was an ECC error and the error could not be corrected.

 P4_E_ECCBAD           40

       Description:
       Indicates that there was an ECC check error that could not be corrected. No data was transferred. In
       contrast to P4_E_ECCOK, this is a full-fletched error.
       Raised by:
       Driver.
       Contrasts with:
       P4_E_ECCOK: There was an ECC error and the error could be corrected.
       P4_E_IO: There was an error with the hardware or underlying device other than an ECC error.

 P4_e_ALL
      Iteration macro This can be used to iterate all values of the corresponding enum type: define macro
      EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

 P4_e_MAX        40

       Description:
       Maximum value of the enum type


                                  c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Error Codes 35

1.3.2 Data Type Definitions

P4_e_t Set of error codes used by PikeOS. This merges both P4_e_t and vm_e_t into a single type. Using only P4_E names is preferable. For compatibility, VM_E codes that existed before are provided. Codes that are new and should not be used with the given name start with an underscore. Depending on the error code, additional information (Raised by) may be provided on the software layer that is entitled to raise the error. Error code whose "Raised by" does not contain "Driver" should not be raised by drivers; in these cases, alternative error codes may be suggested by the "Contrast with" information. Note that the kernel is always entitled to raise an appropriate error code independently of the "Raised by" field.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

36 The PikeOS Kernel API

1.4 UIDs

This section describes constants and access macros provided to access and manipulate PikeOS unique IDs (UIDs).

1.4.1 Defines

  P4_UID_BUILD (respart, task, thread)
       Build a valid UID from resource partition, task number, and thread number.
        Description:
        This macro builds a valid UID from its parameters. The new UID will have resource partition, task
        number, and thread number initialised from the macro parameters and the corresponding valid bits set.

        Parameters:
            respart Resource partition number
            task Task number
            thread Thread number
        Returns:
        Returns the new valid UID.

        Note:
        All parameters must be valid in their defined range, otherwise the result of the macro is undefined.

  P4_UID_GET_RESPART (x)
       Extract resource partition from UID.
        Description:
        This macro extracts the resource partition number from the UID passed as parameter.

        Parameters:
                x UID
        Returns:
        Returns the resource partition number encoded in x.

  P4_UID_GET_TASK (x)
       Extract task number from UID.
        Description:
        This macro extracts the task number from the UID passed as parameter.

        Parameters:
                x UID
        Returns:
        Returns the task number encoded in x.

  P4_UID_GET_THREAD (x)
       Extract thread number from UID.
        Description:


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

UIDs 37

   This macro extracts the thread number from the UID passed as parameter.

   Parameters:
           x UID
   Returns:
   Returns the thread number encoded in x.

P4_UID_KEEP The KEEP UID. Description: Defines P4_UID_KEEP used as special value in API functions.

P4_UID_INVALID The INVALID UID. Description: Defines P4_UID_INVALID used as special value in API functions.

P4_UID_INHERIT The INHERIT UID. Description: In task and thread API calls requests that exception handlers shall be inherited from the calling thread.

P4_UID (task, thread) Build a THREAD UID from task number and thread number. Description: This macro builds a THREAD UID from the given macro parameters task number and thread number. The UID is used to specify "reception from this thread of this task" in IPC and event calls.

   Parameters:
        task Task number
        thread Thread number
   Returns:
   Returns the new UID.

   Note:
   All parameters must be valid in their defined range, otherwise the result of the macro is undefined.

P4_UID_THREAD (uid, thread) Build a THREAD UID from existing UID and thread number. Description: This macro builds a THREAD UID from the given macro parameters UID and thread number.

   Parameters:
         uid UID where the task number is taken from
        thread Thread number
   Returns:
   Returns the new UID.


                        c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

38 The PikeOS Kernel API

      Note:
      All parameters must be valid in their defined range, otherwise the result of the macro is undefined.

 P4_UID_TASK (task)
      Build a TASK UID from task number.
      Description:
      This macro builds a TASK UID from the given macro parameter task number.

      Parameters:
           task Task number
      Returns:
      Returns the new UID.

      Note:
      All parameters must be valid in their defined range, otherwise the result of the macro is undefined.

 P4_UID_RESPART (respart)
      Build a RESOURCE PARTITION UID from resource partition.
      Description:
      This macro builds a RESOURCE PARTITION UID from the given macro parameter resource partition.

      Parameters:
           respart Resource partition number
      Returns:
      Returns the new UID.

      Note:
      All parameters must be valid in their defined range, otherwise the result of the macro is undefined.

 P4_UID_ALL
      The ALL UID.
      Description:
      Defines P4_UID_ALL used as special value in API functions.


                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

UIDs 39

1.4.2 Functions

1.4.2.1 p4_uid_valid

Check for valid UID.

Synopsis:

__forceinline P4_bool_t p4_uid_valid(P4_uid_t id)

Parameters: id IN: UID to validate.

Description: This function checks if the UID id is a valid UID, i.e., not INVALID, INHERIT, or KEEP UID.

Returns: Returns non-zero if the UID id is valid, otherwise returns zero.

                                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

40 The PikeOS Kernel API

1.4.2.2 p4_uid_eq

Compare task and thread number of UIDs.

Synopsis:

__forceinline P4_bool_t p4_uid_eq(P4_uid_t id0, P4_uid_t id1)

Parameters: id0 IN: UID to compare with id1 id1 IN: UID to compare with id0

Description: This function compares task and thread numbers of the UIDs id0 and id1. The invalid flag and resource partition information included in the UIDs is ignored in the comparison.

Returns: Returns TRUE if the UIDs id0 and id1 are equal, otherwise returns FALSE.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

UIDs 41

1.4.2.3 p4_uid_match

Match UIDs.

Synopsis:

__forceinline P4_bool_t p4_uid_match(P4_uid_t id0, P4_uid_t id1)

Parameters: id0 IN: UID id1 IN: UID to match id0

Description: This function checks if the UID id1 matches the requirements of id0. If id0s resource partition, task number, or thread number is set to the corresponding MASK value, any value from id1 fits. Both UID must be valid UIDs.

Returns: Returns TRUE if UID id1 matches UID id0, otherwise returns FALSE.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

42 The PikeOS Kernel API

1.4.2.4 p4_uid_match_all

Check if a UID matches P4_UID_ALL.

Synopsis:

__forceinline P4_bool_t p4_uid_match_all(P4_uid_t uid)

Parameters: uid IN: UID

Description: This function checks if the UID uid matches P4_UID_ALL. uid must be a valid UID.

Returns: Returns TRUE if UID uid matches P4_UID_ALL, otherwise returns FALSE.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

UIDs 43

1.4.2.5 p4_uid_is_fq

Check if a UID is a fully qualified UID.

Synopsis:

__forceinline P4_bool_t p4_uid_is_fq(P4_uid_t uid)

Parameters: uid IN: UID

Description: This function checks if the UID uid is a fully qualified UID that contains a wildcard value in neither the task ID nor the thread number part,i.e. it identifies exactly one thread in the system. The resource partition information included in the UID is ignored in the comparison. uid must be a valid UID.

Returns: Returns TRUE if UID uid is a fully qualified UID, otherwise returns FALSE.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

44 The PikeOS Kernel API

1.5 Abilities

This section describes constants, macros and data types required to access the ability property of a task. (C) Copyright SYSGO AG.

1.5.1 Defines

  P4_AB_GET_BIT (abm_p, ab)
       This macro tests whether the bit for the ability given by ab is set in the ability bitmap pointed to by
       abm_p.

         Parameters:
              abm_p Pointer to the ability bitmap to be tested
                 ab Ability number
         Returns:
         TRUE if the bit is set, FALSE otherwise.

         Note:
         If ab is not a valid ability number, the return value is undefined.

  P4_AB_SET_BIT (abm_p, ab)
       This macro sets the bit for the ability given by ab in the ability bitmap pointed to by abm_p.

         Parameters:
              abm_p Pointer to the ability bitmap
                 ab Ability number
         Note:
         If ab is not a valid ability number, the effects of this macro are undefined.

  P4_AB_FILL_SET (abm_p)
       Initialise ability set with all bits set.
         Description:
         This macro fills the ability set pointed to by abm_p, i.e. all abilities will be set (enabled).

         Parameters:
              abm_p Pointer to the ability bitmap

  P4_AB_CLEAR_SET (abm_p)
       Initialise ability set with all bits cleared.
         Description:
         This macro clears the ability set pointed to by abm_p, i.e. all abilities will be cleared (disabled).

         Parameters:
              abm_p Pointer to the ability bitmap

  P4_NUM_AB
       Maximum number of abilities stored in P4_ability_mask_t.


                                 c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Abilities 45

        Note:
        Not all ability bits in the range [0 .. P4_NUM_AB - 1] may be valid.

P4_AB_TIMEPART_SETUP                1

        Description:
        Ability enabling time partition setup calls. If a task has this ability enabled, threads within the task will be
        allowed to modify the kernels time partition switching table by p4_timepart_load() (see section 1.19.6.1)
        and p4_timepart_switch() (see section 1.19.6.2). This ability is usually restricted to the system software.

P4_AB_PSP_RESET            2

        Description:
        Ability enabling use of PSP reset functionality. If a task has this ability enabled, threads within the task
        will be allowed to reset the target hardware using the PSP reset command via p4_kernel_control() (see
        section 1.24.2.1).

P4_AB_PART_SET_MODE               4

        Description:
        Ability to change operating modes of other partitions. This ability is usually restricted to trusted applica-
        tions.

P4_AB_TIMEPART_CHANGE                   8

        Description:
        Ability enabling time partition change. If a task has this ability enabled, threads within the task will
        be allowed to change their own or another threads time partition using p4_thread_ex_sched() (see
        section 1.16.5.15) and to create threads in a time partition other than their own using p4_task_start()
        (see section 1.17.5.3) and p4_thread_create() (see section 1.16.5.2). This ability is usually restricted to
        trusted applications.

P4_AB_MONITOR           16

        Description:
        Ability enabling task monitoring calls. If a task has this ability enabled, threads within the task will be
        allowed to gather information on the status of tasks and threads which are not child tasks of the callers
        task using p4_mon_task_get_attr() (see section 1.23.4.11), p4_mon_thread_get_attr() (see section
        1.23.4.4), p4_mon_respart_get_attr() (see section 1.23.4.1), p4_mon_thread_get_regs() (see section
        1.23.4.5), p4_mon_mem_list() (see section 1.23.4.12), p4_mon_get_task_map() (see section 1.23.4.2),
        and p4_mon_task_get_thread_map() (see section 1.23.4.3). This ability is usually restricted to trusted
        applications.

P4_AB_PSP_CONSOLE              32

        Description:
        Ability enabling use of PSP console access. If a task has this ability enabled, threads within the task will
        be allowed to use the PSP console commands via p4_kernel_control() (see section 1.24.2.1).


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

46 The PikeOS Kernel API

 P4_AB_MEM_CREATE          64

     Description:
     Ability enabling creation of memory mappings. If a task has this ability enabled, threads within the task
     will be allowed to use p4_mem_create() (see section 1.15.6.6) to create a mapping from a physical to
     a virtual memory area and p4_ioport_create() (see section 1.15.6.9) to install access permissions to
     access I/O ports. This ability is usually restricted to trusted applications.

 P4_AB_HM_INJECT_OTHER            128

     Description:
     Ability to inject partition level errors into the health monitor for other partitions. If a task has this ability
     enabled, threads within the task can inject errors for other threads. Reporting domains are restricted
     to P4_HM_DOMAIN_PART, and P4_HM_DOMAIN_PART_INIT. Causing panic is not alowed. This
     ability may be given to e.g., external file providers servicing multiple partitions to allow them to inject
     configuration errors in the served partitions.

 P4_AB_TRACE      256

     Description:
     Ability enabling trace related functions. If a task has this ability enabled, threads within the task
     will be allowed to use the trace related functions p4_trace_client_register() (see section 1.22.5.1),
     p4_trace_client_unregister() (see section 1.22.5.2), p4_trace_server_register() (see section 1.22.5.3),
     p4_trace_server_unregister() (see section 1.22.5.4), p4_trace_set_bufsize() (see section 1.22.5.5),
     p4_trace_map() (see section 1.22.5.6), and p4_trace_reset() (see section 1.22.5.7).

 P4_AB_CACHE_CHANGE             512

     Description:
     Ability to change cache attributes in memory mappings. If a task has this ability enabled, threads within
     the task will be allowed to change cache attributes of memory mappings in the callers task and its
     child tasks using p4_mem_map() (see section 1.15.6.1) and p4_mem_set_attr() (see section 1.15.6.3)
     together with the P4_M_C_UPDATE flag. The same applies for mappings updated via p4_ipc() (see
     section 1.12.7.1).

 P4_AB_ULOCK_SHARED             1024

     Description:
     Ability to use shareable user space locks, such as semaphores, mutexes or condition variables. If
     participating tasks have this ability enabled, threads of different tasks can synchronize via user space
     locks located in shared memory mappings.

 P4_AB_RESPART_CHANGE            2048

     Description:
     Ability enabling resource partition creation and change. If a task has this ability enabled, threads
     within the task will be allowed to activate tasks in a resource partition other than their own using
     p4_task_activate() (see section 1.17.5.2).


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Abilities 47

P4_AB_KMEM_HANDLING               4096

        Description:
        Ability enabling kernel memory handling. If a task has this ability enabled, threads within the task will be
        allowed to maintain the kernels memory pools. This ability is usually restricted to the system software.

P4_AB_TIMEPART_ENABLE_DISABLE                   8192

        Description:
        Ability enabling time partition switch delays. If a task has this ability enabled, threads within the task
        will be allowed to enable or disable time partition switching by p4_fast_timepart_switch_enable() (see
        section 1.19.6.4) and p4_fast_timepart_switch_disable() (see section 1.19.6.3).

P4_AB_RESPART_SETUP              16384

        Description:
        Ability enabling resource partition setup calls. If a task has this ability enabled, threads within the task
        will be allowed to modify the kernels resource partition attributes by p4_respart_set_exh(). This ability
        is usually restricted to the system software.

P4_AB_KDEV_SETUP            32768

        Description:
        Ability to access KDEV framework in setup mode. If a task wants to initialise and setup the kernel device
        driver (KDEV) framework, this ability is required. This means that some of the KDEV system calls are
        restricted by this ability.

P4_AB_SYSTEM_HM_ERROR                65536

        Description:
        Ability to inject system errors into the health monitor. If a task has this ability enabled, threads within
        the task can inject errors for other threads, domains other than P4_HM_DOMAIN_USER, P4_HM_DO-
        MAIN_PART, and P4_HM_DOMAIN_PART_INIT, and may cause panics. This ability is usually restricted
        to the system software.

P4_ability_mask_ALL
     Iteration macro This can be used to iterate all values of the corresponding enum type: define macro
     EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

P4_ability_mask_MAX          65536

        Description:
        Maximum value of the enum type

P4_ability_mask_MASK          131071

        Description:
        All values of this bitmask enum ORed together into a bitmask


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

48 The PikeOS Kernel API

 VM_AB_TIMEPART_SETUP              1


 VM_AB_PSP_RESET         2


 VM_AB_PART_SET_MODE               4


 VM_AB_TIMEPART_CHANGE                 8


 VM_AB_MONITOR         16


 VM_AB_PSP_CONSOLE            32


 VM_AB_MEM_CREATE             64


 VM_AB_HM_INJECT_OTHER                 128


 VM_AB_TRACE       256


 VM_AB_CACHE_CHANGE                512


 VM_AB_ULOCK_SHARED                1024


 VM_AB_TO_KERNEL     (VM_AB_TIMEPART_CHANGE | VM_AB_MONITOR | VM_AB_PSP_CON-
       SOLE | VM_AB_MEM_CREATE | VM_AB_HM_INJECT_OTHER | VM_AB_TRACE |
       VM_AB_CACHE_CHANGE | VM_AB_ULOCK_SHARED)


 vm_ability_ALL
      Iteration macro This can be used to iterate all values of the corresponding enum type: define macro
      EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

 vm_ability_MAX       1024

       Description:
       Maximum value of the enum type

 vm_ability_MASK       2047

       Description:
       All values of this bitmask enum ORed together into a bitmask


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Abilities 49

1.5.2 Data Type Definitions

P4_ability_mask_t Task ability bitmap structure. The task ability is a set of bits representing the differ-
     ent abilities. The ability set is to be treated as an opaque data type and should only be accessed
     using the macros P4_AB_SET_BIT() (see section 1.5.1), P4_AB_GET_BIT() (see section 1.5.1),
     P4_AB_FILL_SET() (see section 1.5.1), and P4_AB_CLEAR_SET() (see section 1.5.1).
vm_ability_t A subset of P4_AB_* values that are assignable in the VMIT to partitions.


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

50 The PikeOS Kernel API

1.6 Timeouts

This section describes constants, data types, and access macros related to PikeOS timeouts.

1.6.1 Defines

  P4_GET_TS (x)
       Read fast 64-bit high resolution time source.
        Description:
        If available on the platform, this macro returns the current value of the high resolution time source. The
        meaning of this value depends on the architecture used.

        Parameters:
                x 64-bit number

  P4_TIMEOUT_NULL (0x0000000000000000ULL)
       Timeout value to request a zero timeout.
        Description:
        When used as a timeout value, it requests that a call shall return immediately instead of waiting for a
        condition to become true.

  P4_TIMEOUT_MAX (0x0400000000000000ULL)
       Maximum timeout value to wait for.
        Description:
        When used as a relative timeout value, it requests that a call shall wait the maximum possible finite
        timeout for a condition to become true. When using absolute timeouts, this defines the limit of valid
        timeouts in the future.

  P4_TIMEOUT_TP_CHANGE (4ULL << 60)
       Timeout flag to wait for next time partition schema switch.
        Description:
        When used as a timeout value, it requests that a call shall wait at least until the calling threads time
        partition changes (i.e., the currently executing schema changes). This allows waiting for a time partition
        schema switch that should take place at the subsequent major time frame (p4_timepart_switch() (see
        section 1.19.6.2) with parameter P4_TIMEPART_SWITCH_MAJOR).

        Note:
        This flag must be OR-ed with an absolute or relative timeout specifier. To wait for next time partition
        change without a normal timeout, OR with P4_TIMEOUT_INFINITE.

  P4_TIMEOUT_TP_ALL (3ULL << 60)
       Timeout flag to wait for next time partition activation.
        Description:
        When used as a timeout value, it requests that a call shall wait at least until the calling threads time
        partition is activated again. If used by a thread running in time partition zero, the thread will be woken
        up on the next time partition switch, regardless which partition is activated.
        Note that the flag (similarly to all timeout-related flags) has a CPU scope only: the next time partition
        switch refers to the CPU-local time partition switch. Except for the major time partition switches, de-


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Timeouts 51

       pending on the configuration of the window tables in the system, minor time partition switches may take
       place in different time instants on different CPUs.

       Note:
       This flag must be OR-ed with an absolute or relative timeout specifier. To wait for next time partition
       activation without a normal timeout, OR with P4_TIMEOUT_INFINITE.

P4_TIMEOUT_TP_PERIOD (2ULL << 60) Timeout flag to wait for next time partition activation with synchronization on the start of the partitions period. Description: When used as a timeout value, it requests that a call shall wait at least until the calling threads time partition is activated again and the condition of start of the partitions period is met. If used by a thread running in time partition zero, the thread will woken up on an explicit switch to time partition zero. Note that the flag (similarly to all timeout-related flags) has a CPU scope only: the next time partition switch refers to the CPU-local time partition switch. Except for the major time partition switches, de- pending on the configuration of the window tables in the system, minor time partition switches may take place in different time instants on different CPUs.

       Note:
       This flag must be OR-ed with an absolute or relative timeout specifier. To wait for next time partition
       activation without a normal timeout, OR with P4_TIMEOUT_INFINITE.

P4_TIMEOUT_TP_MAJOR (1ULL << 60) Timeout flag to wait for next time partition activation with synchronization on the start of the major time frame. Description: When used as a timeout value, it requests that a call shall wait at least until the calling threads time partition is activated again and the condition of start of the major time frame is met. If used by a thread running in time partition zero, the thread will be woken up whenever a wrap around in the time partition table occurs and processing starts again at the first selected entry in the table.

       Note:
       This flag must be OR-ed with an absolute or relative timeout specifier. To wait for next time partition
       activation without a normal timeout, OR with P4_TIMEOUT_INFINITE.

P4_TIMEOUT_TP_MASK (7ULL << 60) Timeout mask for time partition switch related timeouts. Description: Mask to extract time partition switch related information from an absolute or relative timeout specifier.

P4_TIMEOUT_CLEAR_TP (to) Clear all time partition related information from a timeout value. Description: This macro clears all time partition related flags from timeout to.

       Parameters:
               to timeout value in nanoseconds.
       Returns:


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

52 The PikeOS Kernel API

       Timeout value with all time partition related bits cleared.

 P4_TIMEOUT_SET_TP (to, flags)
      Set time partition related information in a timeout value.
       Description:
       This macro set the time partition related flags in flags to the timeout value to. The flags in flags
       can be one of P4_TIMEOUT_TP_ALL, P4_TIMEOUT_TP_MAJOR, P4_TIMEOUT_TP_PERIOD, or
       P4_TIMEOUT_TP_CHANGE. All other time partition related flags from timeout to are cleared before.

       Parameters:
              to timeout value in nanoseconds.
            flags time partition related flags.
       Returns:
       Timeout value with all time partition related bits cleared.

 P4_TIMEOUT_INFINITE
      Infinite timeout value.
       Description:
       When used as a timeout value, it requests an infinite timeout to wait for a condition to become true.

 P4_TIMEOUT_ABSOLUTE              (8ULL << 60)
      Absolute timeout flag.
       Description:
       Flag (bit) to mark a timeout as an absolute timeout.

 P4_TIMEOUT_ABS (to)
      Builds an absolute timeout value from a timeout value.
       Description:
       This macro marks timeout to as a absolute timeout. Note that to is a P4_timeout_t type, and it is
       therefore limited to P4_TIMEOUT_MAX. The upper bits are reserved to encode time-partition related
       timeouts.
       Using P4_time_t as absolute timeout value may produce unintended results if the upper reserved bits
       are set (if the current system time overlaps with the reserved upper bits, i.e., after approx. 36 years).
       This macro masks the upper bits with P4_TIMEOUT_MASK and sets the P4_TIMEOUT_ABSOLUTE
       bit. The system will complete the upper bits on the basis of the current system time, thus producing the
       intended result.

       Parameters:
              to timeout value in nanoseconds.
       Returns:
       Absolute timeout value.

 P4_TIMEOUT_REL (to)
      Builds a relative timeout value from a timeout value.
       Description:
       This macro marks timeout to as a relative timeout.

       Parameters:


                                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Timeouts 53

             to timeout value in nanoseconds.
       Returns:
       Relative timeout value.

P4_TIMEOUT_MASK (0x0fffffffffffffffULL) Timeout mask for absolute and relative timeouts. Description: Mask to extract timeout value from an absolute or relative timeout specifier.

P4_SEC (to) Converts a timeout value from seconds to nanoseconds. Description: This macro converts the timeout to from seconds to nanoseconds without loss of precision by using a 64-bit multiplication.

       Parameters:
             to timeout (in seconds)
       Returns:
       Returns a timeout data object.

P4_MSEC (to) Converts a timeout value from milliseconds to nanoseconds. Description: This macro converts the timeout to from milliseconds to nanoseconds without loss of precision by using a 64-bit multiplication.

       Parameters:
             to timeout (in milliseconds)
       Returns:
       Returns a timeout data object.

P4_USEC (to) Converts a timeout value from microseconds to nanoseconds. Description: This macro converts the timeout to from microseconds to nanoseconds without loss of precision by using a 64-bit multiplication.

       Parameters:
             to timeout (in microseconds)
       Returns:
       Returns a timeout data object.

P4_NSEC (to) Converts a timeout value to nanoseconds. Description: This macro converts the timeout to to a 64-bit value.

       Parameters:


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

54 The PikeOS Kernel API

       to timeout (in nanoseconds)
 Returns:
 Returns a timeout data object.


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Timeouts 55

1.6.2 Functions

1.6.2.1 p4_sleep

Delay for an amount of time.

Synopsis:

P4_e_t p4_sleep(P4_timeout_t timeout)

Parameters: timeout IN: timeout specifies the time the calling thread will be blocked in the kernel.

Description: A successful call to this function suspends the calling thread until the timeout specified by timeout expires.

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_CANCEL if the sleep was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU. P4_E_BADTIMEOUT if the specified timeout is invalid or in the past.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

56 The PikeOS Kernel API

1.6.2.2 p4_get_time_syscall

Get the system time in nanoseconds.

Synopsis:

P4_e_t p4_get_time_syscall(P4_time_t *time_p)

Parameters: time_p OUT: time_p points to a memory area where the system time is stored. If NULL, no system time will be returned.

Description: This function returns the time in nanoseconds in time_p (if not NULL) from a high resolution time source (if available). The origin and resolution of the time is platform dependent. Unless otherwise noted, PSPs provide the time since boot.

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_INVAL time_p is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT time_p is not NULL and is not fully mapped in the callers virtual address space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Timeouts 57

1.6.2.3 p4_get_time

Get the system time in nanoseconds.

Synopsis:

__forceinline P4_time_t p4_get_time(void)

Description: This function returns the time in nanoseconds since boot from a high resolution time source (if available). The origin and resolution of the time is platform dependent. Unless otherwise noted, PSPs provide the time since boot.

Returns: A call to this function returns the time in nanoseconds since boot.

Note: This function uses p4_get_time_syscall() (see section 1.6.2.2) internally to retrieve the current system time.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

58 The PikeOS Kernel API

1.6.2.4 p4_get_ts_syscall

Read the CPU time stamp counter.

Synopsis:

P4_e_t p4_get_ts_syscall(P4_uint64_t *ts_p)

Parameters: ts_p OUT: ts_p points to a memory area where there time stamp counter is stored. If NULL, no time stamp counter will be returned.

Description: This function returns the CPU time stamp counter in ts_p (if not NULL) if available on the platform, or the current system time otherwise. The origin and resolution of the time is platform dependent.

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_INVAL ts_p is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT ts_p is not NULL and is not fully mapped in the callers virtual address space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Timeouts 59

1.6.2.5 p4_get_ts

Read the CPU time stamp counter.

Synopsis:

P4_uint64_t p4_get_ts(void)

Description: This function returns the CPU time stamp counter if available on the platform, or the current system time otherwise. The origin and resolution of the time is platform dependent.

Returns: A call to this function returns the CPU time stamp counter.

Note: This call is implemented as a user library function and involves no system call if P4_FEATURE_TS is defined. Otherwise, this function uses p4_get_ts_syscall() (see section 1.6.2.4) internally to retrieve the CPU time stamp counter.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

60 The PikeOS Kernel API

1.7 Generic Bitmap Handling

This section describes all constants, data types, access macros, and functions for generic bitmap manipulation.

1.7.1 Defines

  P4_BITMAP_DECLARE (name, size)
       Bitmap data type declaration.

        Parameters:
             name IN: type name (type to declare)
             size IN: size of type
        This macro defines a bitmap data type of size bits named name postfixed by _t. Parameters:

             name IN: Bitmap name, data type is postfixed with _t, structure is postfixed with _str.
             size IN: Number of bits in the bitmap.

  P4_BITMAP_GET_BIT (map, bnum)
       Get bit in bitmap.
        Description:
        This macro returns the value of bit bnum in bitmap map. Parameters:

             map Pointer to bitmap
             bnum Bit number
        Returns:
        Returns FALSE if bit is clear and TRUE if bit is set in bitmap.

  P4_BITMAP_SET_BIT (map, bnum)
       Set bit in bitmap.
        Description:
        This macro sets bit bnum in bitmap map. Parameters:

             map Pointer to bitmap
             bnum Bit number

  P4_BITMAP_CLR_BIT (map, bnum)
       Clear bit in bitmap.
        Description:
        This macro clears bit bnum in bitmap map. Parameters:

             map Pointer to bitmap
             bnum Bit number

  P4_BITMAP_CLEAR (map)
       Clear all bits in bitmap.
        Description:
        This macro clears all bits in bitmap map. Parameters:

             map Pointer to bitmap


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Generic Bitmap Handling 61

P4_BITMAP_FILL (map) Set all bits in bitmap. Description: This macro sets all bits in bitmap map. Parameters:

          map Pointer to bitmap

P4_BITMAP_COPY (type, dst, src) Copy bitmap. Description: This macro copies a bitmap of type type from src to dst. Parameters:

          type Type of source and destination bitmap
           dst Pointer to destination bitmap
           src Pointer to source bitmap

P4_BITMAP_AND (type, dst, src_a, src_b) Bitwise AND operation on bitmaps. Description: This macro performs a bitwise AND of bitmaps src_a and src_b and stores the result in dst. All bitmaps must be of type type. Parameters:

          type Type of source and destination bitmap
           dst Pointer to destination bitmap
          src_a Pointer to first source bitmap
          src_b Pointer to second source bitmap

P4_BITMAP_AND_NOT (type, dst, src_a, src_b) Bitwise AND NOT operation bitmaps. Description: This macro performs a bitwise AND of bitmaps src_a and NOT src_b and stores the result in dst. All bitmaps must be of type type. Parameters:

          type Type of source and destination bitmap
           dst Pointer to destination bitmap
          src_a Pointer to first source bitmap
          src_b Pointer to second source bitmap

P4_BITMAP_OR (type, dst, src_a, src_b) Bitwise OR operation bitmaps. Description: This macro performs a bitwise OR of bitmaps src_a and src_b and stores the result in dst. All bitmaps must be of type type. Parameters:

          type Type of source and destination bitmap
           dst Pointer to destination bitmap
          src_a Pointer to first source bitmap
          src_b Pointer to second source bitmap


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

62 The PikeOS Kernel API

 P4_BITMAP_IS_SUBSET (set, subset, bnum)
      Check if bitmap is included in other bitmap.
       Description:
       This macro checks if the first bnum bits of bitmap subset is also set in set. Parameters:

             set Pointer to bitmap
           subset Pointer to subset bitmap
           bnum Number of bits to check
       Returns:
       Return non-zero if bitmap subset is included in set, zero otherwise

 P4_BITMAP_IS_EQUAL (map_a, map_b, bnum)
      Check if bitmaps are equal.
       Description:
       This macro checks if the first bnum bits of bitmap map_a are equal to map_b. Parameters:

           map_a Pointer to first bitmap
           map_b Pointer to second bitmap
           bnum Number of bits to check
       Returns:
       Return non-zero if bitmap map_a is equal to map_b, zero otherwise

 P4_BITMAP_IS_CLEAR (map, bnum)
      Check if bits in bitmap are cleared.
       Description:
       This macro checks if the first bnum bits of bitmap map are cleared. Parameters:

           map Pointer to bitmap
           bnum Number of bits to check
       Returns:
       Return non-zero if bitmap map is cleared

 P4_BITMAP_FOREACH_SET_BIT (map, n, num, wrd, bit)
      Iterate on all set bits in bitmap.
       Description:
       This macro iterates on the first num set bits in bitmap map. Variable n represents the iterator value.
       Variables wrd and bit are temporary used for iteration purposes and must be of type "unsigned long".
       Parameters:

           map Pointer to bitmap
               n Iterator (being assigned to each set bit)
           num Number of bits to check
            wrd Temporary used, must be of type unsigned long
             bit Temporary used, must be of type unsigned long

 P4_BITMAP_FOREACH_CLR_BIT (map, n, num, wrd, bit)
      Iterate on all cleared bits in bitmap.


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Generic Bitmap Handling 63

     Description:
     This macro iterates on the first num cleared bits in bitmap map. Variable n represents the iterator value.
     Variables wrd and bit are temporary used for iteration purposes and must be of type "unsigned long".
     Parameters:

         map Pointer to bitmap
            n Iterator (being assigned to each cleared bit)
         num Number of bits to check
          wrd Temporary used, must be of type unsigned long
           bit Temporary used, must be of type unsigned long


                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

64 The PikeOS Kernel API

1.8 Generic Handling of CPU Masks

This section describes all access macros and functions for generic manipulation of CPU masks.

1.8.1 Defines

  P4_CPUMASK_FILL_MASK (cpus)
       Get a CPU mask for given number of CPUs without shifting beyond 32/64 bit.
        Description:
        This macro creates a valid CPU mask of type P4_cpumask_t for cpus processors.

        Parameters:
            cpus Number of processors, range 0 <= cpus <= P4_NUM_CPU.
        Returns:
        CPU mask with the bits for cpus processors set.

  P4_CPUMASK_CPU_TO_MASK (cpu)
       Convert a CPU ID to a CPU mask.
        Description:
        This macro returns a valid CPU mask of type P4_cpumask_t for a single processor cpu.

        Parameters:
            cpu CPU ID, range 0 <= cpu < P4_NUM_CPU.
        Returns:
        CPU mask with the bit representing CPU cpu set.

  P4_CPUMASK_SET_CPU (mask, cpu)
       Set a CPU in a CPU mask.
        Description:
        This macro sets the bit of processor cpu in the CPU mask mask of type P4_cpumask_t.

        Parameters:
            mask CPU mask.
            cpu CPU ID, range 0 <= cpu < P4_NUM_CPU.

  P4_CPUMASK_CLEAR_CPU (mask, cpu)
       Clear a CPU in a CPU mask.
        Description:
        This macro clears the bit of processor cpu in the CPU mask mask of type P4_cpumask_t.

        Parameters:
            mask CPU mask.
            cpu CPU ID, range 0 <= cpu < P4_NUM_CPU.

  P4_CPUMASK_IS_SET (mask, cpu)
       Check if a CPU is set in a CPU mask.
        Description:


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Generic Handling of CPU Masks 65

     This macro checks if the bit of processor cpu is set in the CPU mask mask of type P4_cpumask_t.

     Parameters:
         mask CPU mask.
          cpu CPU ID, range 0 <= cpu < P4_NUM_CPU.
     Returns:
     Return TRUE if CPU cpu is included in mask, FALSE otherwise.

P4_CPUMASK_IS_SUBSET (mask, submask) Check if one CPU mask is a subset of another CPU mask. Description: This macro checks if all processors in CPU mask submask are also included in the superset CPU mask mask and returns TRUE.

     Parameters:
         mask Superset CPU mask.
         submask Subset CPU mask.
     Returns:
     Return TRUE if CPU mask submask is included in mask, FALSE otherwise.

P4_CPUMASK_IS_DISJOINED (mask1, mask2) Check if one CPU mask is fully disjoined from another CPU mask. Description: This macro checks if both CPU masks mask1 and mask2 are fully disjoined from each other.

     Parameters:
         mask1 CPU mask.
         mask2 CPU mask.
     Returns:
     Return TRUE if both CPU masks are fully disjoined, FALSE otherwise.

P4_CPUMASK_IS_EQUAL (mask1, mask2) Check if two CPU masks have the same CPUs sets. Description: This macro checks if both CPU masks mask1 and mask2 have the same CPUs set.

     Parameters:
         mask1 CPU mask.
         mask2 CPU mask.
     Returns:
     Return TRUE if both CPU masks are equal, FALSE otherwise.

P4_CPUMASK_FOREACH_CPU (cpu, mask) Iterate over all set CPUs in given CPU mask, starting at LSB. Description: This macro iterates over all set CPUs in the CPU mask mask. Variable cpu represents the iterator value.

     Parameters:


                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

66 The PikeOS Kernel API

 mask CPU mask.
 cpu Iterator of type P4_cpuid_t, being assigned to each set CPU.


                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 67

1.9 Kernel Info Page

The section describes the data structures related to the PikeOS kernel info page. The CPU Information Service Calls module defines the service calls related to Processor Information.

1.9.1 Structure Definitions

1.9.1.1 struct P4_cpu_info_str

CPU relation information. The CPU relation information is used to describe a processor in an SMP system and to calculate the distance between processors. Processors are enumerated by their

  • memory node node (ccNUMA),
  • physical socket socket,
  • physical core core (multi core), and
  • virtual thread thread (SMT) indices, in the given order.

All indices start by zero and counting is local to the level of shared elements.

Synopsis: struct P4_cpu_info_str { P4_uint8_t node; P4_uint8_t socket; P4_uint8_t core; P4_uint8_t thread; };

Structure Element Description: node Index of the ccNUMA node. socket Index of physical existing processor slots, sockets, or packages. core Index of physical core in one socket. thread Index of SMT thread in a core.

Associated Data Type

  P4_cpu_info_t CPU relation information.

1.9.1.2 struct P4_rom_desc_str

ROM image descriptor.

Synopsis: struct P4_rom_desc_str { P4_phys_addr_t phys; P4_size_t size;

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

68 The PikeOS Kernel API

  P4_access_t attrib;
  P4_uint32_t unused;

};

Structure Element Description: phys Physical start address of ROM. size Size in bytes of ROM, if zero, entry is empty. attrib Access permissions and cache attributes. unused

Associated Data Type

 P4_rom_desc_t ROM image descriptor.

1.9.1.3 struct P4_kinfopage_str

Kernel info structure. The kernel info page exports kernel information to user applications. The page is always visible in user space, but is not writeable by the user. Some structure members are for internal use only and will not be documented in the "Field Documentation" subsection below.

Note: the "offset" comments refer to byte offsets

Synopsis: struct P4_kinfopage_str { const char idstring[4]; const P4_uint32_t api_version; const P4_uint32_t regs_size; const P4_bool_t dynamic_ticker_mode; const P4_time_t ns_per_tick; const P4_time_t ns_per_tp_tick; const char kernel_id[P4_NAMELEN]; const char asp_id[P4_NAMELEN]; const char psp_id[P4_NAMELEN]; const P4_uint32_t num_cpu; const P4_uint32_t num_respart; const P4_uint32_t num_task; const P4_uint32_t num_thread; const P4_uint32_t num_timepart; const P4_uint32_t num_prio; const P4_bool_t has_smp; const P4_uint32_t kernel_stack_size; const P4_uint64_t ts_calibration; const P4_time_t ns_per_calibration; const P4_rom_desc_t roms[P4_NUM_ROM_DESC]; const P4_cpu_info_t cpu_info[P4_NUM_CPU]; const P4_address_t align_mask;

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 69

  const P4_size_t allpages;
  P4_size_t freepages;
  const P4_bool_t has_nx;
  const P4_uint32_t tps_sync;
  const P4_haltmode_t haltmode;
  const P4_bool_t kernel_assert;
  const P4_bool_t console_access;
  P4_uint32_t padding[9];
  P4_kinfo_arch_t arch;

};

Structure Element Description: idstring ID string, contains the characters "P4uk". Can be used to identify the kernel info page. This value is a runtime constant. api_version Contains a version number identifying the PikeOS kernel API version. This value is a runtime constant. regs_size Size of a threads register context in bytes This value is a runtime constant. dynamic_ticker_mode Flag indicating dynamic ticker mode. If this flag is TRUE, the system supports fine granular timeouts and runs in non-periodic ticker mode. This value is a runtime constant. ns_per_tick System tick timer period in nanoseconds. On systems using a dynamic ticker mode, the timeout granularity supported by the PSP is reported here. This value is a runtime constant. ns_per_tp_tick Time partition minimum window duration in nanoseconds. This value is a runtime constant. kernel_id Build ID string of kernel, terminated with a NUL character. This value is a runtime constant. asp_id Build ID string of ASP, terminated with a NUL character. This value is a runtime constant. psp_id Build ID string of PSP, terminated with a NUL character. This value is a runtime constant. num_cpu Number of CPUs supported. For uniprocessor kernels, this number is always one. On multiproces- sor implementations of PikeOS, this number is the number of CPUs used by the kernel on the current system. Previous kernel versions used a number of zero to indicate a uniprocessor kernel. This value is a runtime constant. num_respart Number of kernel page pools (resource partitions) This value is a runtime constant. num_task Number of tasks supported by the kernel This value is a runtime constant.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

70 The PikeOS Kernel API

 num_thread Number of threads per task supported by the kernel
       This value is a runtime constant.
 num_timepart Number of supported time domains
       This value is a runtime constant.
 num_prio Number of priorities supported by kernel
       This value is a runtime constant.
 has_smp Kernel SMP support. has_smp is true if the running kernel has been compiled with SMP support.
       This value is a runtime constant.
 kernel_stack_size Configured threads system/kernel stack size.
       This value is a runtime constant.
 ts_calibration Number of timestamp counter increments used during speed calibration at system startup
       (see ns_per_calibration).
       This value is a runtime constant.
 ns_per_calibration Time spent during speed calibration at system startup in nanoseconds (see ts_calibra-
      tion).
       This value is a runtime constant.
 roms List of ROM images.
       This value is a runtime constant.
 cpu_info CPU relation information. This array contains information on the structure and relation of all proces-
      sors in the system.
       Only the first num_cpu entries are valid.
       This value is a runtime constant.
 align_mask Alignment to apply to virtual addresses to meet architecture requirements caused by cache
       aliasing effects. This value has 2n  1 format on affected machines and is zero on architectures without
       problems.
       This value is a runtime constant.
 allpages Number of all pages after bootmem allocation
       This value is a runtime constant.
 freepages Number of free pages in the kernel memory allocator
 has_nx Non-executable mappings. has_nx is true if the running kernel supports non-executable mappings,
      i.e. mappings without the P4_M_EXEC access permissions.
       This value is a runtime constant.
 tps_sync Cached value for the p4/kernel/tps_strong_sync property. If tps_sync is set to 1, strong synchro-
       nization of CPUs at major time frame boundaries is requested.
 haltmode Halt mode reported by the PSP after boot.
 kernel_assert Kernel Assert. kernel_assert is true if assertions are enabled in the kernel.
 console_access Kernel Console Access. console_access is true if the kernel is compiled with access to the
      console for reporting purposes.
 padding
 arch ASP specific information


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 71

Associated Data Type

P4_kinfopage_t Kernel info structure.

1.9.2 Defines

P4_NUM_ROM_DESC Maximum supported number of ROM images.

1.9.3 Data Type Definitions

P4_cpu_info_t CPU relation information. The CPU relation information is used to describe a processor in an SMP system and to calculate the distance between processors. Processors are enumerated by their

         • memory node node (ccNUMA),
         • physical socket socket,
         • physical core core (multi core), and
         • virtual thread thread (SMT) indices, in the given order.

      All indices start by zero and counting is local to the level of shared elements.

P4_rom_desc_t ROM image descriptor. P4_kinfopage_t Kernel info structure. The kernel info page exports kernel information to user applications. The page is always visible in user space, but is not writeable by the user. Some structure members are for internal use only and will not be documented in the "Field Documen- tation" subsection below.

      Note:
      the "offset" comments refer to byte offsets


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

72 The PikeOS Kernel API

1.9.4 Enumerations

Enumeration type P4_cpu_distance_t

CPU distance. This enumeration type is used to calculate the distance between two processors.

Name Description P4_DISTANCE_CORE Processors are virtual SMT threads on the same physical core.

P4_DISTANCE_SOCKET Processors share the same socket and bus to their local memory.

P4_DISTANCE_NODE Processors share the same memory node.

P4_DISTANCE_OTHER Processors are on different memory nodes.

Enumeration type P4_haltmode_t

Consolidated action modes to control the PSP halting behavior and report the halting behavior before system boot. This enum is used for the board_halt callback of the PSP for indicating which type of halting functionality shall be performed as well as to report which halting functionality was used before the system start. The halting mode (if saved by the PSP across reset) is stored in the haltmode field of the KINFO page.

Note: The PSP must take care of retaining the halting mode and reporting it to the kernel in the haltmode field of the psp_descriptor passed to p4_main().

Name Description P4_PSP_HALT Invoking the board_halt callback with this halting mode halts the system. Note: This halting mode is mandatory and must be implemented by board_halt. Note: The kernel calls board_halt selecting this mode with interrupts disabled. Note: When invoked with this halting mode, on SMP the board_halt callback should take care of other processors and halt them, if necessary. An implementation should provide internal locking, if necessary.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 73

P4_PSP_STOP Invoking the board_halt callback with this halting mode stops the current CPU. Note: This halting mode is mandatory and must be implemented by board_halt. Note: The kernel calls board_halt selecting this mode with interrupts disabled. Note: On SMP, board_halt targets the calling CPU only, when invoked with this halting mode. An implementation should provide internal locking, if necessary.

P4_PSP_RESET Invoking the board_halt callback with this halting mode resets the sys- tem. This functionality should be equivalent to pressing the reset button on the outside. If this halting mode is not available, the board_halt func- tion falls back to P4_PSP_HALT as halting mode. Note: This halting mode is optional and the fallback case to P4_PSP_HALT must be implemented by board_halt (e.g., as default case). Note: The kernel calls board_halt selecting this mode with interrupts disabled. Note: When invoked with this halting mode, on SMP the board_halt callback should take care of other processors and halt them, if necessary. An implementation should provide internal locking, if necessary.

P4_PSP_POWEROFF Invoking the board_halt callback with this halting mode will power off the system. If this halting mode is not available, the board_halt function falls back to P4_PSP_HALT as halting mode. Note: This halting mode is optional and the fallback case to P4_PSP_HALT must be implemented by board_halt (e.g., as default case). Note: The kernel calls board_halt selecting this mode with interrupts disabled. Note: When invoked with this halting mode, on SMP the board_halt callback should take care of other processors and halt them, if necessary. An implementation should provide internal locking, if necessary.

                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

74 The PikeOS Kernel API

P4_PSP_ASSERT Invoking the board_halt callback with this halting mode halts the sys- tem. A call of board_halt with this mode is intended to be invoked from assertions in the kernel and is meant for debugging purposes. If this halting mode is not available, the board_halt function falls back to P4_PSP_HALT as halting mode. Note: This halting mode is optional and the fallback case to P4_PSP_HALT must be implemented by board_halt (e.g., as default case). Note: The kernel calls board_halt selecting this mode with interrupts disabled. Note: When invoked with this halting mode, on SMP the board_halt callback should take care of other processors and halt them, if necessary. An implementation should provide internal locking, if necessary.

P4_PSP_HMRESET Invoking the board_halt callback with this halting mode functionally re- sets the system in the same way as P4_PSP_RESET does. This mode informs the PSP that the reset has been triggered by the health monitor- ing. If this halting mode is not available, the board_halt function falls back to P4_PSP_HALT as halting mode. Note: This halting mode is optional and the fallback case to P4_PSP_HALT must be implemented by board_halt (e.g., as default case). Note: The kernel calls board_halt selecting this mode with interrupts disabled. Note: When invoked with this halting mode, on SMP the board_halt callback should take care of other processors and halt them, if necessary. An implementation should provide internal locking, if necessary.

              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 75

1.9.5 Functions

1.9.5.1 p4_cpu_info

Retrieve processor information.

Synopsis:

P4_e_t p4_cpu_info(P4_cpuid_t cpuid, P4_cpu_info_t *info_p)

Parameters: cpuid IN: ID of the processor for which the information shall be retrieved or P4_CPU_MYSELF for the callers processor. info_p OUT: Pointer to CPU information Upon successful completion, the memory referenced by info_p will contain the processor information. A NULL pointer indicates that the attributes should not be retrieved.

Description: This function returns information of processor cpuid in terms of physical memory node, socket, core or thread in info_p.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL cpuid refers to an invalid processor.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

76 The PikeOS Kernel API

1.9.5.2 p4_cpu_distance

Calculate distance between two processors.

Synopsis:

P4_e_t p4_cpu_distance(P4_cpuid_t cpuid_a, P4_cpuid_t cpuid_b, P4_cpu_distance_t *dist_p)

Parameters: cpuid_a IN: ID of the first processor for which the distance shall be calculated or P4_CPU_MYSELF for the callers processor. cpuid_b IN: ID of the second processor for which the distance shall be calculated or P4_CPU_MYSELF for the callers processor. dist_p OUT: Pointer to a CPU distance Upon successful completion, the memory referenced by dist_p will contain the processor distance. A NULL pointer indicates that the distance should not be retrieved.

Description: This function calculates the distance between two processors cpuid_a and cpuid_b in terms of physical memory node, socket or core in dist_p.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL cpuid_a or cpuid_b refer to invalid processors.

Note: If cpuid_a and cpuid_b refer the same processor, the returned distance is P4_DISTANCE_CORE.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 77

1.9.5.3 p4_kinfopage

Retrieve a pointer to the kernel info page.

Synopsis:

__forceinline P4_kinfopage_t* p4_kinfopage(void)

Description: This function returns a pointer to the kernel info page always visible from user space without syscall overhead.

Returns: Upon success, a call to this function returns a pointer to the kernel info page.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

78 The PikeOS Kernel API

1.9.5.4 p4_my_uid_syscall

Retrieve current threads UID.

Synopsis:

P4_e_t p4_my_uid_syscall(P4_uid_t *uid_p)

Parameters: uid_p OUT: uid_p points to a memory area where the UID is stored. If NULL, no UID will be returned.

Description: This function returns the UID of the calling thread in uid_p (if not NULL).

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_INVAL uid_p is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT uid_p is not NULL and is not fully mapped in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 79

1.9.5.5 p4_my_uid

Retrieve current threads UID.

Synopsis:

__forceinline P4_uid_t p4_my_uid(void)

Description: This function returns the UID of the calling thread.

Returns: Upon success, a call to this function returns the current threads UID.

Note: This function uses p4_my_uid_syscall() (see section 1.9.5.4) internally to retrieve the threads UID.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

80 The PikeOS Kernel API

1.9.5.6 p4_my_thread

Retrieve current threads thread number.

Synopsis:

__forceinline P4_thr_t p4_my_thread(void)

Description: This function returns the thread number of the calling thread.

Returns: Upon success, a call to this function returns the current threads thread number.

Note: This function uses p4_my_uid_syscall() (see section 1.9.5.4) internally to retrieve the threads thread number.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 81

1.9.5.7 p4_my_task

Retrieve current threads task number.

Synopsis:

__forceinline P4_task_t p4_my_task(void)

Description: This function returns the task number of the calling thread.

Returns: Upon success, a call to this function returns the current threads task number.

Note: This function uses p4_my_uid_syscall() (see section 1.9.5.4) internally to retrieve the threads task number.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

82 The PikeOS Kernel API

1.9.5.8 p4_my_respart

Retrieve current threads resource partition number.

Synopsis:

__forceinline P4_uint32_t p4_my_respart(void)

Description: This function returns the resource partition of the calling thread.

Returns: Upon success, a call to this function returns the current threads resource partition.

Note: This function uses p4_my_uid_syscall() (see section 1.9.5.4) internally to retrieve the threads resource partition number.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 83

1.9.5.9 p4_my_timepart_syscall

Retrieve current threads time partition number.

Synopsis:

P4_e_t p4_my_timepart_syscall(P4_uint32_t *timepart)

Parameters: timepart OUT: timepart_p points to a memory area where the time partition number is stored. If NULL, no time partition will be returned.

Description: This function returns the time partition of the calling thread in timepart_p (if not NULL).

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_INVAL timepart_p is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT timepart_p is not NULL and is not fully mapped in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

84 The PikeOS Kernel API

1.9.5.10 p4_my_timepart

Retrieve current threads time partition number.

Synopsis:

__forceinline P4_uint32_t p4_my_timepart(void)

Description: This function returns the time partition of the calling thread.

Returns: Upon success, a call to this function returns the current threads time partition.

Note: This function uses p4_my_timepart_syscall() (see section 1.9.5.9) internally to retrieve the threads time partition number.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 85

1.9.5.11 p4_fast_get_prio_syscall

Retrieve the threads priority.

Synopsis:

P4_e_t p4_fast_get_prio_syscall(P4_prio_t *prio_p)

Parameters: prio_p OUT: prio_p points to a memory area where the priority is stored. If NULL, no priority will be returned.

Description: This function retrieves the threads priority in prio_p (if not NULL).

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_INVAL prio_p is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT prio_p is not NULL and is not fully mapped in the callers virtual address space.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

86 The PikeOS Kernel API

1.9.5.12 p4_fast_get_prio

Retrieve the threads priority.

Synopsis:

__forceinline P4_prio_t p4_fast_get_prio(void)

Description: This function retrieves the threads priority.

Returns: Upon success, a call to this function returns the current threads priority.

Note: This function uses p4_fast_get_prio_syscall() (see section 1.9.5.11) internally to retrieve the threads priority.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 87

1.9.5.13 p4_my_prio

Retrieve current threads priority.

Synopsis:

__forceinline P4_prio_t p4_my_prio(void)

Description: This function retrieves the threads priority.

Returns: Upon success, a call to this function returns the current threads priority.

Note: This function uses p4_fast_get_prio_syscall() (see section 1.9.5.11) internally to retrieve the threads priority.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

88 The PikeOS Kernel API

1.9.5.14 p4_my_cpuid_syscall

Retrieve current threads CPU ID.

Synopsis:

P4_e_t p4_my_cpuid_syscall(P4_cpuid_t *cpu_p)

Parameters: cpu_p OUT: cpu_p points to a memory area where the CPU ID is stored. If NULL, no CPU ID will be returned.

Description: This function returns the ID of the calling threads processor in cpu_p (if not NULL).

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_INVAL cpu_p is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT cpu_p is not NULL and is not fully mapped in the callers virtual address space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 89

1.9.5.15 p4_my_cpuid

Retrieve current threads CPU ID.

Synopsis:

__forceinline P4_cpuid_t p4_my_cpuid(void)

Description: This function returns the ID of the calling threads processor.

Returns: Upon success, a call to this function returns the current threads CPU ID.

Note: This function uses p4_my_cpuid_syscall() (see section 1.9.5.14) internally to retrieve the threads CPU ID.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

90 The PikeOS Kernel API

1.9.5.16 p4_fast_set_prio_syscall

Set the current threads priority.

Synopsis:

P4_e_t p4_fast_set_prio_syscall(P4_prio_t new_prio, P4_prio_t *old_prio)

Parameters: new_prio IN: New priority. Invalid or too high priorities are limited to the callers task MCP. old_prio OUT: old_prio points to a memory area where the previous priority is stored. If NULL, no previous priority will be returned.

Description: This function sets the current threads priority to new_prio. Invalid or too high priorities are limited to the callers task MCP. The function returns the previous priority in old_prio (if not NULL).

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_INVAL old_prio is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT old_prio is not NULL and is not fully mapped in the callers virtual address space.

                                 c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 91

1.9.5.17 p4_fast_set_prio

Set the current threads priority.

Synopsis:

__forceinline P4_prio_t p4_fast_set_prio(P4_prio_t new_prio)

Parameters: new_prio IN: New priority. Invalid or too high priorities are limited to the callers task MCP.

Description: This function sets the current threads priority to new_prio. Invalid or too high priorities are limited to the callers task MCP.

Returns: Upon success, a call to this function returns the current threads priority before setting it to new_prio.

Note: This function uses p4_fast_set_prio_syscall() (see section 1.9.5.16) internally to retrieve and change the threads priority.

                                 c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

92 The PikeOS Kernel API

1.9.5.18 p4_kinfo_get_api_version

Retrieve PikeOS kernel API version.

Synopsis:

__forceinline P4_uint32_t p4_kinfo_get_api_version(void)

Returns: Upon success, a call to this function returns kernels API version.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 93

1.9.5.19 p4_kinfo_get_kernel_build_id

Retrieve build ID string of Kernel.

Synopsis:

__forceinline const char* p4_kinfo_get_kernel_build_id(void)

Returns: Upon success, a call to this function returns a NUL terminated string identifying the kernel build ID.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

94 The PikeOS Kernel API

1.9.5.20 p4_kinfo_get_asp_build_id

Retrieve build ID string of ASP.

Synopsis:

__forceinline const char* p4_kinfo_get_asp_build_id(void)

Returns: Upon success, a call to this function returns a NUL terminated string identifying the ASP build ID.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 95

1.9.5.21 p4_kinfo_get_psp_build_id

Retrieve build ID string of PSP.

Synopsis:

__forceinline const char* p4_kinfo_get_psp_build_id(void)

Returns: Upon success, a call to this function returns a NUL terminated string identifying the PSP build ID.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

96 The PikeOS Kernel API

1.9.5.22 p4_kinfo_get_regs_size

Retrieve PikeOS register context size.

Synopsis:

__forceinline P4_uint32_t p4_kinfo_get_regs_size(void)

Returns: Upon success, a call to this function returns the size of a threads register context in bytes.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 97

1.9.5.23 p4_kinfo_get_align_mask

Retrieve mapping align mask.

Synopsis:

__forceinline P4_address_t p4_kinfo_get_align_mask(void)

Returns: Returns alignment to apply to virtual addresses to meet architecture requirements caused by cache aliasing effects. This value has 2n 1 format on affected machines and is zero on architectures without problems. This value is a runtime constant.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

98 The PikeOS Kernel API

1.9.5.24 p4_kinfo_get_timeout_resolution

Retrieve PikeOS timeout resolution.

Synopsis:

__forceinline P4_time_t p4_kinfo_get_timeout_resolution(void)

Returns: Upon success, a call to this function returns the timeout resolution in nanoseconds.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 99

1.9.5.25 p4_kinfo_get_tp_resolution

Retrieve PikeOS time partition minimum window duration.

Synopsis:

__forceinline P4_time_t p4_kinfo_get_tp_resolution(void)

Returns: Upon success, a call to this function returns the time partition minimum window duration in nanoseconds.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

100 The PikeOS Kernel API

1.9.5.26 p4_kinfo_get_num_cpu

Retrieve PikeOS number of processors.

Synopsis:

__forceinline P4_uint32_t p4_kinfo_get_num_cpu(void)

Returns: Upon success, a call to this function returns the number of supported processors. For uniprocessor kernels, this number is always one. On multiprocessor implementations of PikeOS, this number is the number of CPUs used by the kernel on the current system.

Note: Previous kernel versions used a number of zero to indicate a uniprocessor kernel.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 101

1.9.5.27 p4_kinfo_get_num_respart

Retrieve PikeOS number of resource partitions.

Synopsis:

__forceinline P4_uint32_t p4_kinfo_get_num_respart(void)

Returns: Upon success, a call to this function returns the number of resource partitions.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

102 The PikeOS Kernel API

1.9.5.28 p4_kinfo_get_num_task

Retrieve PikeOS number of tasks.

Synopsis:

__forceinline P4_uint32_t p4_kinfo_get_num_task(void)

Returns: Upon success, a call to this function returns the number of supported tasks.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 103

1.9.5.29 p4_kinfo_get_num_thread

Retrieve PikeOS number of threads per task.

Synopsis:

__forceinline P4_uint32_t p4_kinfo_get_num_thread(void)

Returns: Upon success, a call to this function returns the number of supported threads per task.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

104 The PikeOS Kernel API

1.9.5.30 p4_kinfo_get_num_timepart

Retrieve PikeOS number of time partitions.

Synopsis:

__forceinline P4_uint32_t p4_kinfo_get_num_timepart(void)

Returns: Upon success, a call to this function returns the number of time partitions.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 105

1.9.5.31 p4_kinfo_get_num_prio

Retrieve PikeOS number of priority levels.

Synopsis:

__forceinline P4_uint32_t p4_kinfo_get_num_prio(void)

Returns: Upon success, a call to this function returns the number of priority levels.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

106 The PikeOS Kernel API

1.9.5.32 p4_kinfo_get_all_pages

Retrieve initial number of pages.

Synopsis:

__forceinline P4_size_t p4_kinfo_get_all_pages(void)

Returns: Upon success, a call to this function returns the initial number of pages after starting the first user space task.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 107

1.9.5.33 p4_kinfo_get_free_pages

Retrieve number of free pages.

Synopsis:

__forceinline P4_size_t p4_kinfo_get_free_pages(void)

Returns: Upon success, a call to this function returns the number of free pages.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

108 The PikeOS Kernel API

1.9.5.34 p4_kinfo_arch

Retrieve pointer to ASP specific part of kernel info page.

Synopsis:

__forceinline P4_kinfo_arch_t* p4_kinfo_arch(void)

Returns: Upon success, a call to this function returns a pointer to the ASP specific part of the kernel info page.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Info Page 109

1.9.5.35 p4_kinfo_roms

Retrieve pointer to a list of ROMs exported by the kernel. The array contains P4_NUM_ROM_DESC elements.

Synopsis:

__forceinline const P4_rom_desc_t* p4_kinfo_roms(void)

Returns: Upon success, a call to this function returns a pointer to a list of ROMs exported by the kernel in the kernel info page.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

110 The PikeOS Kernel API

1.10 Communication API

This section describes service calls related to the PikeOS communication rights mechanism.

1.10.1 Defines

VM_O_RD 1

       Description:
       Allow reading, e.g. vm_read(), vm_qport_read(), vm_sport_read(), etc. This flag can be used in access
       control lists, gate and port permissions, and vm_open().

VM_O_WR 2

       Description:
       Allow writing, e.g. vm_write(), vm_qport_write(), vm_sport_write(), etc. This flag can be used in access
       control lists, gate and port permissions, and vm_open().

VM_O_EXEC 4

       Description:
       Allow the file/device to be opened for code execution mode, so that it can be mapped with execution
       permissions using vm_map(). This is a file access right and can be used in vm_open().
       For directories, the same semantics as in POSIX holds: with EXEC, sub-directories may be opened.
       This is in contrast to RD permissions on directories, which mean that the contents of the directory can
       be listed.

VM_O_MAP 8

       Description:
       Allow memory mapping (parts of the) device, e.g. using vm_map().

VM_O_NO_DIR 16

       Description:
       For devices that need it: do not open a directory, but only files.

VM_O_CREAT 32

       Description:
       For vm_open(), whether the file should be created if it is not present.

VM_O_TRUNC 64

       Description:
       For vm_open(), whether the file should be truncated to size 0 in case it exists.


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Communication API 111

VM_O_EXCL 128

    Description:
    Whether vm_open() should fail if the file exists. Set this option together with VM_O_CREAT if you
    want to be sure to open a new file. Note that the behaviour of VM_O_EXCL without VM_O_CREAT is
    undefined.

VM_O_WRLOCK 256

    Description:
    Whether vm_open() should try to open the file exclusively for writing. Use this to create a single writeable
    file descriptor for a certain file. It depends on the underlying provider whether this flag has an effect.
    The provider may not support this flag and return successfully in vm_open() without actually locking the
    file.

VM_O_MOUNT 512

    Description:
    Whether vm_open() should open a volume instead of a file.

VM_O_FSPROV 1024

    Description:
    Access right to be used in the file access list of a partition to identify a partition as the file system
    provider for the given path (which must be a device prefix).

VM_O_VOLPROV 2048

    Description:
    Access right to be used in the file access list of a partition to identify a partition as the volume provider
    for the given path (which must be a volume prefix).

VM_O_NONBLOCK 4096

    Description:
    Any function that has no timeout parameter should use P4_TIMEOUT_NULL instead of P4_TIME-
    OUT_INFINITE, i.e., calls to read/write/ioctl/... should all be non-blocking.

VM_O_PRIORITY 8192

    Description:
    For devices that support it: use priority sorted blocking instead of FIFO sorted blocking.

VM_O_DIRECTORY 16384

    Description:
    For devices that need it: open a file for directory iteration. Some devices may use different structures to
    be able to efficiently iterate.


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

112 The PikeOS Kernel API

VM_O_RD_WR (VM_O_RD (see section 1.10.1) | VM_O_WR (see section 1.10.1))

    Description:
    Both read and write access.

VM_O_RD_EXEC (VM_O_RD (see section 1.10.1) | VM_O_EXEC (see section 1.10.1))

    Description:
    Both read and exec access.

VM_O_RD_WR_EXEC (VM_O_RD_WR (see section 1.10.1) | VM_O_EXEC (see section 1.10.1))

    Description:
    Read, write, and and exec access.

VM_O_PERM_MASK (VM_O_RD_WR (see section 1.10.1) | VM_O_EXEC (see sec- tion 1.10.1) | VM_O_MAP (see section 1.10.1) | VM_O_MOUNT (see section 1.10.1) | VM_O_FSPROV (see section 1.10.1) | VM_O_VOLPROV (see section 1.10.1))

    Description:
    These bits that are access permission bits, i.e., if an access control mask misses a bit, an access that
    requests that bit will be rejected.
    If a bit is neither in this nor in VM_O_FORCE_MASK, then it is an option. If it is in both this an
    VM_O_FORCE_MASK, it is a switch, i.e., an access request is granted only if the permission mask
    and the request mask bits are equal.

VM_O_FORCE_MASK (VM_O_MOUNT (see section 1.10.1) | VM_O_FSPROV (see section 1.10.1) | VM_O_VOLPROV (see section 1.10.1))

    Description:
    These bits are enforced for an access, i.e., if an access control mask contains a bit, an access request
    that is missing that bit will be rejected.
    If a bit is neither in this nor in VM_O_PERM_MASK, then it is an option. If it is in both this an
    VM_O_PERM_MASK, it is a switch, i.e., an access request is granted only if the permission mask
    and the request mask bits are equal.

vm_file_access_mode_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

vm_file_access_mode_MAX 16384

    Description:
    Maximum value of the enum type


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Communication API 113

vm_file_access_mode_MASK 32767

     Description:
     All values of this bitmask enum ORed together into a bitmask

VM_PORT_DESTINATION 1

     Description:
     From the point of view of a communication channel, this is the dat destination or sink, i.e., the corre-
     sponding partition can read from this port.

VM_PORT_SOURCE 2

     Description:
     From the point of view of a communication channel, this is the data source, i.e., the correspanding
     partition can read from this port.

vm_port_direction_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

vm_port_direction_MAX 2

     Description:
     Maximum value of the enum type

vm_port_direction_MASK 3

     Description:
     All values of this bitmask enum ORed together into a bitmask

VM_PORT_SAMPLING 1

     Description:
     Marks a sampling port.

VM_PORT_QUEUING 2

     Description:
     Marks a queuing port, including SAP ports.

vm_port_type_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

vm_port_type_MAX 2

     Description:
     Maximum value of the enum type


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

114 The PikeOS Kernel API

1.10.2 Data Type Definitions

vm_file_access_mode_t Open mode for files, handling permission flags like read, write, exec, map permis- sions, but also options like creat, wrlock, or nonblock. This is used both to specify permissions in the VMIT and in vm_open() to request specific permissions or options. To ease permission checks, there is a definition of a mask defining all permissions, which excludes any option bits: VM_O_PERM_MASK. Also, for convenience, some other common multi-bit values are available (like RD_WR etc.). vm_port_direction_t Alias type for ports to specify whether reading or writing is allowed. Ports are unidirec- tional, so it is not possible to have both read and write permissions. vm_port_type_t Whether the port uses queuing or sampling semantics. This is used on channels to select the port type, also because sampling and queuing ports have separate namespaces.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Communication API 115

1.10.3 Functions

1.10.3.1 p4_comm_grant

Grant an active child task the right to communicate with another task.

Synopsis:

P4_e_t p4_comm_grant(P4_task_t dest, const P4_task_bitmap_t *comm_map_p)

Parameters: dest IN: Number of the task which shall receive the communication right. comm_map_p IN: Pointer to communication bitmap.

Description: A call to this function passes the permission to communicate with other tasks to task dest. The parameter comm_map_p points to a task communication bitmap, and the parameter dest specifies the destination task number, which must be a child task of the calling task. A set bit in the bitmap indicates that the corresponding task shall be added to dests communication bitmap. The calling thread must have the permission to communicate with this task. The permission still remains in the calling task. The permission cannot be revoked, except by killing the receiving child task.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if comm_map_p is NULL, or if comm_map_p is invalid or exceeds the virtual address space, or if comm_map_p does not point to a valid address in the callers address space, or if dest does not refer to a valid task number. P4_E_PAGEFAULT if comm_map_p is not fully mapped in the callers address space. P4_E_BADTASK if dest is not a child task of the caller. P4_E_STATE if dest does not exist P4_E_PERM if comm_map_p has bits set of tasks the caller has no right to communicate with.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

116 The PikeOS Kernel API

1.10.3.2 p4_comm_link

Grant an active child task the right to communicate with another task.

Synopsis:

P4_e_t p4_comm_link(P4_task_t dest, P4_task_t which)

Parameters: dest IN: Number of the task which shall receive the communication right to communicate with which. P4_TASK_MYSELF refers to the callers task. which IN: Number of the task which shall receive the communication right to communicate with dest. P4_TASK_MYSELF refers to the callers task.

Description: A call to this function passes the permission to communicate with task which to task dest and vice versa. If the caller has the right to communicate (send or receive IPC or events) with task which, it can grant this right to one of its child tasks by calling this function. This establishes a communication channel between which and dest (and vice versa). The right cannot be revoked, except by killing the child task dest.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if dest or which is not a valid task number. P4_E_BADTASK if dest is not a child task of the caller. P4_E_STATE if dest or which do not exist. P4_E_PERM if which describes a task the caller has no right to communicate to.

Note: Regardless if task which exists or not, this function grants the right to communicate to which to task dest as long as the caller is eligible to communicate with which.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Event API 117

1.11 Event API

This section describes service calls related to the PikeOS event communication API.

1.11.1 Defines

P4_EV_CONSUME_ONE Value definition for p4_ev_wait()flags parameter. Description: Setting this value instructs p4_ev_wait() (see section 1.11.2.3) to consume exactly one event before the function successfully returns to the caller.

P4_EV_CONSUME_ALL Value definition for p4_ev_wait()flags parameter. Description: Setting this value instructs p4_ev_wait() (see section 1.11.2.3) to consume all events before the function successfully returns to the caller.

P4_EV_CTR_MAX Maximum value a threads event counter may take. Description: If a threads event counter has this value, subsequent calls to p4_ev_signal() (see section 1.11.2.2) will fail with error code P4_E_LIMIT.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

118 The PikeOS Kernel API

1.11.2 Functions

1.11.2.1 p4_ev_mask

Set event reception UID mask for the calling thread.

Synopsis:

void p4_ev_mask(P4_uid_t uid_mask)

Parameters: uid_mask IN: UID of the thread(s) allowed to signal an event to the caller. Wildcards may be used for resource partition, task, and thread information. If P4_UID_INVALID is specified, event reception will be disabled.

Description: A call to this function sets the event reception UID mask for the calling thread. The parameter uid_mask specifies the thread(s) allowed to signal an event to the calling thread. The callers event counter is initialized to zero. Parameter uid_mask may be a wildcard UID and the specified thread need not to exist at the time of this call. If event reception was already enabled by a previous call to this function, the event counter is initialized to zero and the communication partner is initialized with the value given by uid_mask. Setting uid_mask to P4_UID_INVALID disables event reception for the calling thread. Any further attempt to signal an event to this thread will return the error code P4_E_BADUID.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Event API 119

1.11.2.2 p4_ev_signal

Signal an event to another thread.

Synopsis:

P4_e_t p4_ev_signal(P4_uid_t uid)

Parameters: uid IN: Fully qualified UID of the thread which shall receive the event

Description: A call to this function signals an event to the destination thread specified by uid. The destination thread must have enabled event reception from the calling thread by a call to p4_ev_mask() (see section 1.11.2.1) and the calling task must be allowed to communicate with the destination task. The event counter of the destination thread will be incremented by one. If the destination thread is currently waiting for an event, it will be unblocked.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_BADUID if the thread referenced by uid does not exist or if it does not allow the caller to signal an event or if the calling threads task does not have the right to communicate with this thread. P4_E_LIMIT if the target threads event counter already reached the value P4_EV_CTR_MAX and thus would overflow when another event is signaled.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

120 The PikeOS Kernel API

1.11.2.3 p4_ev_wait

Wait for an event.

Synopsis:

P4_e_t p4_ev_wait(P4_timeout_t timeout, P4_uint32_t flags, P4_uint32_t *counter)

Parameters: timeout IN: Maximum time to wait for an event to be signaled flags IN: Parameter used to further control event reception. Currently, the following flags are defined:

           • P4_EV_CONSUME_ONE
             The event counter will be decremented by one before the function successfully returns to the
             caller.
           • P4_EV_CONSUME_ALL
             The event counter will be cleared before the function successfully returns to the caller.

       If flags is not P4_EV_CONSUME_ONE or P4_EV_CONSUME_ALL, the event counter of the calling
       thread remains untouched.
       If both P4_EV_CONSUME_ONE and P4_EV_CONSUME_ALL are set, P4_EV_CONSUME_ALL takes
       precedence over P4_EV_CONSUME_ONE.

counter OUT: If not NULL, pointer to location where the calling threads event counter is saved before events are consumed.

Description: If the event counter value is zero, this function suspends the calling thread until the event counter becomes non- zero or the specified timeout expires. When an event is signaled to this thread, the suspended thread resumes execution. After waiting, events can be consumed. Depending on the flags set in flags parameter, the threads event counter remains untouched (no flag is set), is decremented by one (P4_EV_CONSUME_ONE), or set to zero (P4_EV_CONSUME_ALL). On error codes P4_E_OK and P4_E_TIMEOUT, the value of the event counter before modifying it is returned in counter.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller and the event counter remains unmodified: P4_E_BADTIMEOUT if the specified timeout is invalid or in the past. P4_E_TIMEOUT if the specified timeout has expired before an event was signaled to the caller. P4_E_INVAL if counter is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_INVAL if an invalid flag is set in flags. P4_E_PAGEFAULT if counter is not NULL and is not fully mapped in the callers virtual address space. P4_E_CANCEL if the function was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

IPC API 121

1.12 IPC API

This section describes constants, data types, access macros, and service calls related to the PikeOS IPC API.

1.12.1 Structure Definitions

1.12.1.1 struct P4_message_str

IPC message descriptor. Format of an IPC message descriptor used by IPC system calls. One message descriptor is needed for sending and one for receiving.

Synopsis:

struct P4_message_str { P4_timeout_t timeout; void * buf; P4_size_t buf_size; P4_address_t map; P4_size_t map_size; P4_access_t access; P4_uid_t uid; };

Structure Element Description: timeout timeout specifies the time the calling thread shall wait for the IPC operation to start. buf Base address of a data buffer to be copied into the receivers address space (message send) or to receive data copied from the senders address space (message receive). If buf_size is zero, this value is ignored. buf_size Size, in bytes, of the data buffer to be copied from the callers into the receivers address space (message send) or the maximum number of bytes that can be copied into the callers from the senders address space (message receive). If zero, no buffer will be sent or received. The size of the buffer is not limited, but must fit in both address spaces. map Base address of a memory area to be mapped into the receivers address space (message send) or base address where the senders memory area should be mapped into the callers address space (message receive). The value must be a multiple of P4_PAGESIZE. If map_size is zero, this value is ignored. map_size Size, in bytes, of the memory area to be mapped from the callers into the receivers address space (message send) or the maximum size of a memory area that can be mapped from the senders into the callers address space (message receive). If zero, no mapping will be sent or received. The value must be a multiple of P4_PAGESIZE. access Set of bits to control access permissions and cache attributes of the memory area to be mapped into the receivers address space. If zero, access permissions and cache attributes are inherited. Changing the cache attributes (P4_M_C_UPDATE is set) requires the P4_AB_CACHE_CHANGE ability. Ignored on message receive. P4_M_REPLACE is ignored, as any previous mappings in the receive memory area will be overwritten. In the mapping, the P4_M_EXEC permission is always cleared, and the P4_M_READ permission is always set.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

122 The PikeOS Kernel API

  uid UID of IPC partner. uid must be a fully qualified UID on message send and might be P4_UID_ALL
      on message receive. If the wildcard UID P4_UID_ALL is specified in a receive operation, any thread
      with the appropriate communication rights matching the wildcard can send a message to the calling
      thread. If the uid value P4_UID_INVALID is specified in any IPC operation, the respective send or
      receive message is ignored.

Associated Data Type

P4_message_t IPC message descriptor.

1.12.1.2 struct P4_ipc_result_str

IPC result descriptor. Format of an IPC result descriptor used by the IPC system calls. The IPC result descriptor contains information on the received IPC message.

Synopsis:

struct P4_ipc_result_str { P4_uid_t sender; P4_uint32_t status; P4_size_t buf_size; P4_size_t map_size; P4_size_t map_offs; };

Structure Element Description: sender Fully qualified UID of sending thread. status Additional IPC status. Currently, the following bits are defined:

           • P4_IPC_STATUS_EXCEPTION
             The received IPC message contains an exception context if this flag is set.
           • P4_IPC_STATUS_MAP_WRITE
             The received IPC message contains a completely writeable mapping. Only valid when IPC fin-
             ished without errors.

buf_size Size of received data buffer in bytes. map_size Size of received mapping in bytes. map_offs Offset in the receive mapping area of the received mapping in bytes.

Associated Data Type

P4_ipc_result_t IPC result descriptor.

1.12.2 IPC Stages

The following constants are used to identify the different stages of an IPC communication.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

IPC API 123

Defines

P4_STAGE_PREP Preparation stage. Description: This value indicates that an error occurred in an IPC operation while preparing the IPC. In the prepara- tion stage, system call parameters of the IPC are checked.

P4_STAGE_SEND_WAIT Sending stage, waiting for receiver. Description: This value indicates that an error occurred in an IPC operation while waiting for the receiver.

P4_STAGE_SEND_BUF Sending stage, copying data buffer. Description: This value indicates that an error occurred in an IPC operation while sending the message via data copy.

P4_STAGE_SEND_MAP Sending stage, applying mapping. Description: This value indicates that an error occurred in an IPC operation while sending the message via mapping.

P4_STAGE_RECV_WAIT Receiving stage, waiting for sender. Description: This value indicates that an error occurred in an IPC operation while waiting for the sender.

P4_STAGE_RECV_BUF Receiving stage, copying data buffer. Description: This value indicates that an error occurred in an IPC operation while receiving the message via data copy.

P4_STAGE_RECV_MAP Receiving stage, applying mapping. Description: This value indicates that an error occurred in an IPC operation while receiving the message via mapping.

P4_STAGE_DONE Done. Description: This value indicates that an error occurred in an IPC operation while finishing the IPC. In this stage, system call results of the IPC are copied back to the callers address space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

124 The PikeOS Kernel API

1.12.3 IPC system call flags

The following constants represent flags that modify the behaviour of the IPC system call. These flags can be OR-ed together.

Defines

P4_IPC_SHIFT_MAP IPC system call flag: allow shifting of the receivers mapping. Description: Setting this flag instructs the IPC system call to shift the receiver mapping window to fit special archi- tecture alignments. This flag is set by the receiving thread.

P4_IPC_EV_RECV IPC system call flag: allow event reception in the IPC receive path. Description: Setting this flag instructs the IPC system call to wait for events in the IPC receive path. If neither P4_IPC_EV_CONSUME_ONE nor P4_IPC_EV_CONSUME_ALL is set, the threads event counter remains unchanged.

P4_IPC_EV_CONSUME_ONE IPC system call flag: consume one event. Description: Setting this flag instructs the IPC system call to consume exactly one event before returning to the caller. This flag is only valid in combination with P4_IPC_EV_RECV.

P4_IPC_EV_CONSUME_ALL IPC system call flag: consume all events. Description: Setting this flag instructs the IPC system call to consume all events before returning to the caller. This flag is only valid in combination with P4_IPC_EV_RECV.

P4_IPC_EV_RESET IPC system call flag: reset event counter after successful IPC reception. Description: Setting this flag instructs the IPC system call to reset the event counter after successful IPC reception.

1.12.4 IPC status flags

The following constants represent flags for special IPC conditions or types of a received message. These flags are usually OR-ed together.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

IPC API 125

Defines

P4_IPC_STATUS_EXCEPTION IPC status flag: IPC is an exception IPC. Description: If this flag is set in the IPC status output parameter, the received IPC message contains an exception context.

P4_IPC_STATUS_MAP_WRITE IPC status flag: received mapping is writeable. Description: If this flag is set in the IPC status output parameter, the received IPC mapping is writeable for the receiver. The ability to write covers the whole mapping, this flag is not set when the area is only partly writeable. This flag is only valid when the IPC operation finished without errors.

1.12.5 Defines

P4_CC (s, e) IPC completion code: build IPC completion code. Description: This macro builds an IPC error code from IPC stage s and the error code e.

       Parameters:
                s Specifies stage.
                e Specifies error code.

P4_CC_STAGE (cc) IPC completion code: extract stage from IPC completion code. Description: This macro extracts the IPC stage from an IPC completion code.

P4_CC_E (cc) IPC completion code: extract error code from IPC completion code. Description: This macro extracts the error code from an IPC completion code.

P4_CC_OK IPC completion code: IPC successfully finished. Description: This macro indicates that the IPC system call exited without errors.

1.12.6 Data Type Definitions

P4_cc_t IPC completion code. This data type contains an IPC completion code. Use P4_CC_E() (see section 1.12.5) and P4_CC_STAGE() (see section 1.12.5) macros to extract error code and IPC stage.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

126 The PikeOS Kernel API

P4_message_t IPC message descriptor. Format of an IPC message descriptor used by IPC system calls. One message descriptor is needed for sending and one for receiving. P4_ipc_result_t IPC result descriptor. Format of an IPC result descriptor used by the IPC system calls. The IPC result descriptor contains information on the received IPC message.

                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

IPC API 127

1.12.7 Functions

1.12.7.1 p4_ipc

Send an IPC message to one thread and then receive an IPC message from another, extended version.

Synopsis:

P4_cc_t p4_ipc(const P4_message_t *send, const P4_message_t *recv, P4_uint32_t flags, P4_ipc_result_t *result)

Parameters: send IN: Message descriptor of messages to send. If NULL, no message will be sent. recv IN: Message descriptor of messages to receive. If NULL, no message will be received. flags IN: IPC system call flags. Currently, the following flag bits are defined:

           • P4_IPC_SHIFT_MAP
             Setting this flag instructs the IPC system call to shift the receiver mapping window to fit special
             architecture alignments.
           • P4_IPC_EV_RECV
              Setting this flag instructs the IPC system call to allow event reception in the IPC receive path.

                 ◦ P4_IPC_EV_CONSUME_ONE
                   Setting this flag instructs the IPC system call to consume one event in case of event recep-
                   tion. This flag is only valid in combination with P4_IPC_EV_RECV.
                 ◦ P4_IPC_EV_CONSUME_ALL
                   Setting this flag instructs the IPC system call to consume all events in case of event reception.
                   This flag is only valid in combination with P4_IPC_EV_RECV.
                 ◦ P4_IPC_EV_RESET
                   Setting this flag instructs the IPC system call to reset the event counter after a non-event IPC
                   operation, i.e. an operation not returning P4_E_EVENT in any stage.

        If not defined as mutually exclusive, several flag bits can be OR-ed together to form a set of flag bits.
        If none of P4_EV_CONSUME_ONE or P4_EV_CONSUME_ALL is given in case of event reception, the
        event counter remains untouched.
        If both P4_IPC_EV_CONSUME_ONE and P4_IPC_EV_CONSUME_ALL are set, P4_IPC_EV_CON-
        SUME_ALL takes precedence over P4_IPC_EV_CONSUME_ONE.

result OUT: IPC result descriptor for the received message. If NULL, no return values will be returned.

Description: A successful call to this function sends a copied and/or a mapped message described by send to thread send-

uid and then receives an event or a copied and/or a mapped message described by recv from thread recv->uid. If not NULL, detailed information on the received message is saved in result. If send or recv is NULL, or send->uid or recv->uid is P4_UID_INVALID, the respective part of IPC communication is ignored. The send/receive combination call is useful for implementing client and server functionality: The client sets both send->uid and recv->uid to the same server thread uid to "call" the server, whereas the server sends a reply in

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

128 The PikeOS Kernel API

send and accepts new requests from any thread by setting recv->uid to P4_UID_ALL or an appropriate wildcard UID. If send is not NULL and send->uid is not an invalid UID, an IPC send operation is performed: a copied and/or a mapped message described by send is send to thread send->uid. A send message consists of a data buffer specified by send->buf and send->buf_size and a mapping specified by send->map and send->map_size. Mapping attributes such as access permissions and cache attributes are passed in send->access. P4_M_REPLACE is implicitly set, all previously installed mappings will be overwritten. Also, the P4_M_EXEC permission is always cleared to mitigate the Spectre v2 "Branch Target Injection" processor vulnerability. The destination thread send->uid must exist. The calling thread must have the right to communicate with the destination thread and must match the destination threads mask. The calling thread is suspended until the destination thread is ready to receive the message or the timeout specified by send->timeout expires. If send->buf_size or send->map_size are zero, the respective part of the message is ignored. The caller must ensure that the entire send buffer is mapped into its address space, otherwise the message transfer will be aborted by the kernel. If recv is not NULL and recv->uid is not an invalid UID, an IPC receive operation is performed for a copied and/or mapped message as described by the message descriptor recv. The message descriptor specifies the receive buffers and their maximum sizes. The copied message part is specified by recv->buf and recv->buf_size, the mapped message receive area by recv->map and recv->map_size and flags. The calling thread is suspended until the destination thread is ready to send a message, an event is received, or the timeout specified by recv->timeout expires. If the flag P4_IPC_EV_RECV is set in flags, the calling thread will also wait for event reception in the P4_STAGE_RECV_WAIT stage, but only if there is no available IPC partner thread. Event consumption is con- trolled by P4_IPC_EV_CONSUME_ONE and P4_IPC_EV_CONSUME_ALL flags, respectively consuming one or all events, or consuming no events when no flag is set. Setting the flag P4_IPC_EV_RESET instructs the IPC system call to clear the event counter after successful IPC reception, i.e. when no events where received. If recv->uid is a wildcard UID, messages can be received from threads in tasks with the appropriate communication rights matching the wildcard and the IPC mask. The caller must ensure that the entire receive data buffer is mapped into its address space, otherwise the message transfer will be aborted by the kernel. Any previous mappings of the receive memory area will be overwritten by a successful IPC. If recv->buf_size or recv->map_size are zero, the respective part of the message is ignored. If the flag P4_IPC_SHIFT_MAP is set by the receiver, the receivers mapping memory area is used as a window where to finally place the mapping. The mapping will be properly aligned within the window to meet architecture requirements like cache aliasing effects. The final mapping then will have an offset of result->map_offs bytes from the start of the mapping area. The function returns the size, in bytes, of the copied message in result->buf_size and of the mapped message in result->map_size. The IPC sender is returned in result->sender. Parameter recv->access is ignored on message reception.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

IPC API 129

result->status contains flags for additional information on the received message:

• P4_IPC_STATUS_EXCEPTION The received IPC message contains an exception context if this flag is set. • P4_IPC_STATUS_MAP_WRITE The received IPC message contains a completely writeable mapping. Only valid when IPC finished without errors.

  If an error is reported at stage P4_STAGE_DONE, the values returned in result are undefined.

Returns: Upon success, a call to this function returns P4_CC_OK, i.e. error P4_E_OK at stage P4_STAGE_DONE. Use P4_CC_E() (see section 1.12.5) and P4_CC_STAGE() (see section 1.12.5) macros to extract error code and IPC stage. If an error is detected at any stage except P4_STAGE_DONE, the call is aborted and the following stages will not be executed. However, any previous stage was successfully completed before. In case of an error in P4_STAGE_DONE, information on completed stages as well as the original stage and error code is lost. If the completion code indicates an error in the P4_STAGE_PREP stage, no part of any message will have been transferred and no other thread will have been affected. The following error codes will be returned in this stage: P4_E_INVAL at P4_STAGE_PREP if an invalid IPC system call flag is set in flags, or if one of send or recv does not point to a valid address in the callers virtual address space, or if send->buf and send->buf_size do not describe a valid memory area, or if send->map and send->map_size do not describe a valid memory area, or if an invalid combination of access permissions is passed in send->access, or if recv->buf and recv->buf_size do not describe a valid memory area, or if recv->map and recv->map_size do not describe a valid memory area. P4_E_PAGEFAULT at P4_STAGE_PREP if send is not NULL and is not fully mapped in the callers virtual address space, or if recv is not NULL and is not fully mapped in the callers virtual address space. P4_E_BADUID at P4_STAGE_PREP if recv->uid is a valid, but not fully qualified UID or P4_UID_ALL. P4_E_NOABILITY at P4_STAGE_PREP if the mappings cache attributes are to be changed (P4_M_C_UPDATE set in send->access), but the task of the calling thread does not have the ability P4_AB_CACHE_CHANGE enabled. If the completion code indicates an error in the P4_STAGE_SEND_WAIT stage, no part of any message will have been transferred. The following error codes will be returned in this stage: P4_E_BADUID at P4_STAGE_SEND_WAIT if the thread described by send->uid does not exist, or

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

130 The PikeOS Kernel API

     if the calling threads task does not have the right to communicate with this thread, or
     if the IPC mask of the thread described by send->uid does not match the calling threads UID, or
     if the thread identified by send->uid is the callers thread itself, or
     if the task identified by send->uid is terminated.

P4_E_BADTIMEOUT at P4_STAGE_SEND_WAIT if the timeout send->timeout is invalid or in the past. P4_E_TIMEOUT at P4_STAGE_SEND_WAIT if the timeout send->timeout expires. P4_E_CANCEL at P4_STAGE_SEND_WAIT if the IPC was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU. If the completion code indicates an error in the P4_STAGE_SEND_BUF stage, part of the copied message may have been transferred. The following error codes will be returned in this stage: P4_E_SIZE at P4_STAGE_SEND_BUF if the senders send->buf_size is larger than the size of the receive buffer of the destination thread. P4_E_INVAL at P4_STAGE_SEND_BUF if sender and receiver data buffer are in the same task and overlap. P4_E_PAGEFAULT at P4_STAGE_SEND_BUF if a page fault occurred in the senders address space while copying the data buffer. P4_E_STATE at P4_STAGE_SEND_BUF if a page fault occurred in the receivers address space while copying the data buffer. If the completion code indicates an error in the P4_STAGE_SEND_MAP stage, the copied message will have been transferred completely, and part of the mapped message may have been transferred. The following error codes will be returned in this stage: P4_E_SIZE at P4_STAGE_SEND_MAP if the senders send->map_size is larger than the size of the receive mapping area of the destination thread. P4_E_INVAL at P4_STAGE_SEND_MAP if sender and receiver mapping are in the same task and overlap. P4_E_PERM at P4_STAGE_SEND_MAP if the source mapping send->map in the senders address space does not fulfill the requested send- >access permissions. P4_E_BADMAP at P4_STAGE_SEND_MAP if the source mapping area is not completely mapped. P4_E_STATE at P4_STAGE_SEND_MAP if an error occurred in the receivers address space while mapping. If the completion code indicates an error in the P4_STAGE_RECV_WAIT stage, the send part of IPC finished successfully and no part of the receive message will have been transferred. The following error codes will be returned in this stage: P4_E_BADTIMEOUT at P4_STAGE_RECV_WAIT

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

IPC API 131

      if the timeout recv->timeout is invalid or in the past.

P4_E_TIMEOUT at P4_STAGE_RECV_WAIT if the timeout recv->timeout expires. P4_E_CANCEL at P4_STAGE_RECV_WAIT if the IPC was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU. P4_E_EVENT at P4_STAGE_RECV_WAIT if an event was received by the calling thread and event reception was enabled. Events will be consumed depending on the settings in flags. If the completion code indicates an error in the P4_STAGE_RECV_BUF stage, the send part of IPC finished successfully and part of the copied receive message may have been transferred. The following error codes will be returned in this stage: P4_E_SIZE at P4_STAGE_RECV_BUF if the receivers recv->buf_size is smaller than the size of the message that was sent. P4_E_INVAL at P4_STAGE_RECV_BUF if sender and receiver mapping are in the same task and overlap. P4_E_STATE at P4_STAGE_RECV_BUF if a page fault occurred in the senders address space while copying the data buffer. P4_E_PAGEFAULT at P4_STAGE_RECV_BUF if a page fault occurred in the receivers address space while copying the data buffer. If the completion code indicates an error in the P4_STAGE_RECV_MAP stage, the send part of IPC finished successfully and the copied receive message will have been transferred completely, and part of the mapped receive message may have been transferred. The following error codes will be returned in this stage: P4_E_SIZE at P4_STAGE_RECV_MAP if the receivers recv->map_size is smaller than the size of the source memory area. P4_E_INVAL at P4_STAGE_RECV_MAP if sender and receiver mapping are in the same task and overlap. P4_E_ALIGN at P4_STAGE_RECV_MAP if the alignment requirements of the source mapping does not match the receive mapping area and P4_IPC_SHIFT_MAP is not enabled in flags. P4_E_STATE at P4_STAGE_RECV_MAP if an error occurred in the senders address space while mapping. P4_E_NOKMEM at P4_STAGE_RECV_MAP if there is not enough kernel memory available in the receivers resource partition to perform the map- ping. If the completion code indicates an error in the P4_STAGE_DONE stage, the original stage information and error code is lost because of an error during copy back of result to the callers virtual address space. The following error codes will be returned in this stage: P4_E_INVAL at P4_STAGE_DONE if result is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT at P4_STAGE_DONE

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

132 The PikeOS Kernel API

      if result is not NULL and is not fully mapped in the callers virtual address space.

Note: Internally in the kernel, IPC uses priority boosting to prevent priority inversions during IPC message transfers. An IPC message transfer is always executed with the maximum scheduling priority of both the sending and the receiving thread. If one of the threads runs in time partition 0, the IPC message transfer will also execute in time partition 0.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

IPC API 133

1.12.7.2 p4_ipc_send

Send an IPC message to another thread.

Synopsis:

P4_cc_t p4_ipc_send(const P4_message_t *send)

Parameters: send IN: Message descriptor of messages to send. If NULL, no message will be sent.

Description: This call represents a simplified version of p4_ipc() (see section 1.12.7.1) call for sending purpose only. p4_ipc() (see section 1.12.7.1)s flags argument is always set to zero, both recv and result are NULL.

Returns: Upon success, a call to this function returns P4_CC_OK, otherwise the completion codes described in p4_ipc() (see section 1.12.7.1) will be returned.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

134 The PikeOS Kernel API

1.12.7.3 p4_ipc_recv

Receive an IPC message from another thread.

Synopsis:

P4_cc_t p4_ipc_recv(const P4_message_t *recv, P4_uid_t *sender, P4_size_t *buf_size_recv, P4_size_t *map_size_recv)

Parameters: recv IN: Message descriptor of messages to receive. If NULL, no message will be received. sender OUT: Fully qualified UID of sending thread. If NULL, no value will be returned. buf_size_recv OUT: Size of received data buffer in bytes. If NULL, no value will be returned. map_size_recv OUT: Size of received mapping in bytes. If NULL, no value will be returned.

Description: This call represents a simplified version of p4_ipc() (see section 1.12.7.1) call for receive purpose only. p4_ipc() (see section 1.12.7.1)s send argument is NULL and flags is always set to zero, event reception and map shifting is not possible with this call. This call also does not return an IPC status. Arguments sender, buf_size_recv and map_size_recv have the same meaning as the according elements of p4_ipc() (see section 1.12.7.1)s result structure. If an output argument is NULL, the output argument is ignored. Invalid pointers for these output arguments may result in a page fault in the callers address space.

Returns: Upon success, a call to this function returns P4_CC_OK, otherwise the completion codes described in p4_ipc() (see section 1.12.7.1) will be returned.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

IPC API 135

1.12.7.4 p4_ipc_buf_send

Send an IPC message to a thread using data copy.

Synopsis:

P4_cc_t p4_ipc_buf_send(P4_uid_t dest, P4_timeout_t timeout, void *buf, P4_size_t buf_size)

Parameters: dest IN: Fully qualified UID of thread that shall receive the message. timeout IN: timeout specifies the maximum time the calling thread shall wait for the IPC operation to start. buf IN: Base address of the data buffer to send. buf_size IN: Data buffer size in bytes, describes the size of the data buffer to send.

Description: A successful call to this function sends the message described by buf and buf_size to thread dest using data copy. The thread will wait the time specified in timeout. This provides a simpler version p4_ipc() (see section 1.12.7.1) functionality, without the possibility to transfer mapped messages in the IPC. For further details, see the description of p4_ipc() (see section 1.12.7.1).

Returns: Upon success, a call to this function returns P4_CC_OK, otherwise the completion codes described in p4_ipc() (see section 1.12.7.1) will be returned.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

136 The PikeOS Kernel API

1.12.7.5 p4_ipc_buf_recv

Receive an IPC message from a thread using data copy.

Synopsis:

P4_cc_t p4_ipc_buf_recv(P4_uid_t *sender, P4_timeout_t timeout, void *buf, P4_size_t *buf_size)

Parameters: sender INOUT: In: Wildcard UID of thread from which message can be received. Out: Fully qualified UID of the sending thread. timeout IN: timeout specifies the maximum time the calling thread shall wait for the IPC operation to start. buf IN: Base address of the buffer for received message. buf_size INOUT: In: Data buffer size in bytes, describes the maximum size of a received message. Out: Size in bytes of the message actually received.

Description: A successful call to this function receives a message in the receive data buffer described by buf and buf_size from thread sender. The thread will wait the time specified in timeout. The sending thread and the size of the received buffer is returned in sender and buf_size. This provides a simpler version of p4_ipc() (see section 1.12.7.1), without the possibility to transfer mapped messages in the IPC. For further details, see the description of p4_ipc() (see section 1.12.7.1).

Returns: Upon success, a call to this function returns P4_CC_OK, otherwise the completion codes described in p4_ipc() (see section 1.12.7.1) will be returned.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

IPC API 137

1.12.7.6 p4_ipc_buf

Send an IPC message to one thread using data copy and then receive a message from another thread using data copy.

Synopsis:

P4_cc_t p4_ipc_buf(P4_uid_t dest, P4_timeout_t send_timeout, void *send_buf, P4_size_t send_buf_size, P4_uid_t *sender, P4_timeout_t recv_timeout, void *recv_buf, P4_size_t *recv_buf_size)

Parameters: dest IN: Fully qualified UID of thread that shall receive the message. send_timeout IN: timeout specifies the maximum time the calling thread shall wait for the send IPC operation to start. send_buf IN: Base address of the data buffer to send. send_buf_size IN: Data buffer size in bytes, describes the size of the data to send. sender INOUT: In: Wildcard UID of thread from which a message can be received. Out: Fully qualified UID of the sending thread. recv_timeout IN: timeout specifies the maximum time the calling thread shall wait for the receive IPC opera- tion to start. The receive timeout starts when the send IPC operation has successfully finished. recv_buf IN: Base address of the buffer for received message. recv_buf_size INOUT: In: Data buffer size in bytes, describes the maximum size of a received message. Out: Size in bytes of the message actually received.

Description: A successful call to this function sends the message described by send_buf and send_buf_size to thread dest using data copy and receives a message in the receive buffer described by recv_buf and recv_buf_size from thread sender using data copy. Timeouts for send and receive operation are supplied in send_timeout and recv_timeout. The sending thread and the size of the received buffer is returned in sender and rcv_buf_size. This provides a simpler version of p4_ipc() (see section 1.12.7.1), without the possibility to transfer mapped messages in the IPC. For further details, see the description of p4_ipc() (see section 1.12.7.1).

Returns: Upon success, a call to this function returns P4_CC_OK, otherwise the completion codes described in p4_ipc() (see section 1.12.7.1) will be returned.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

138 The PikeOS Kernel API

1.12.7.7 p4_ipc_buf_call

Send an IPC message to a thread using data copy and then receive a message from the same thread using data copy.

Synopsis:

P4_cc_t p4_ipc_buf_call(P4_uid_t dest, P4_timeout_t send_timeout, void *send_buf, P4_size_t send_buf_size, P4_timeout_t recv_timeout, void *recv_buf, P4_size_t *recv_buf_size)

Parameters: dest IN: Fully qualified UID of thread to send a message to and receive a message from. send_timeout IN: timeout specifies the maximum time the calling thread shall wait for the send IPC operation to start. send_buf IN: Base address of the data buffer to send. send_buf_size IN: Data buffer size in bytes, describes the size of the data to send. recv_timeout IN: timeout specifies the maximum time the calling thread shall wait for the receive IPC opera- tion to start. The receive timeout starts when the send IPC operation has successfully finished. recv_buf IN: Base address of the buffer for received message. recv_buf_size INOUT: In: Data buffer size in bytes, describes the maximum size of a received message. Out: Size in bytes of the message actually received.

Description: A successful call to this function sends the message described by send_buf and send_buf_size to thread dest using data copy and then receives a message in the receive buffer described by recv_buf and recv_buf_size from the same thread using data copy. Timeouts for send and receive operation are supplied in send_timeout and recv_timeout. The caller must specifiy a fully qualified UID for dest. The size of the received buffer is returned in recv_buf_size. This provides a simpler version of p4_ipc() (see section 1.12.7.1), without the possibility to transfer mapped messages in the IPC. For further details, see the description of p4_ipc() (see section 1.12.7.1).

Returns: Upon success, a call to this function returns P4_CC_OK, otherwise the completion codes described in p4_ipc() (see section 1.12.7.1) will be returned.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

IPC API 139

1.12.7.8 p4_ipc_mask

Set IPC mask of the calling thread.

Synopsis:

void p4_ipc_mask(P4_uid_t uid)

Parameters: uid IN: UID of the thread(s) allowed to send an IPC to the calling thread. Wildcards may be used for resource partition, task, and thread information. If P4_UID_INVALID is specified, IPC reception will be disabled.

Description: A call to this function sets the IPC mask of the calling thread. The parameter uid specifies the thread(s) allowed to send an IPC to the calling thread. Parameter uid may be a wildcard UID and the specified thread need not to exist at the time of this call.

Note: Previous PikeOS versions also filtered the current queue of pending send IPC operations to the calling thread and all senders not matching the new IPC mask uid were canceled from their blocking state. This is no longer the case, pending send IPC operations remain queued.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

140 The PikeOS Kernel API

1.13 Interrupt API

This section describes constants, data types, access macros, and service calls related to the PikeOS interrupt handling.

1.13.1 Structure Definitions

1.13.1.1 struct P4_interrupt_bitmap_str

Interrupt bitmap structure. The interrupt bitmap is used to store and communicate the set of interrupts granted to a task. The bitmap contains one bit for every interrupt number (0 ... P4_NUM_INTERRUPT-1) where the interrupt number is reflected in the bit position within the bitmap and the attribute value is given by the bit value. The interrupt bitmap structure is to be treated as an opaque data type and should only be accessed by the macros P4_INT_GET_BIT() (see section 1.13.2) and P4_INT_SET_BIT() (see section 1.13.2).

Synopsis: struct P4_interrupt_bitmap_str { unsigned long m[...]; };

Structure Element Description: m Storage for bitmap.

Associated Data Type

P4_interrupt_bitmap_t Interrupt bitmap structure.

1.13.2 Defines

P4_INT_CHAIN Chain interrupt to other waiting threads (deprecated). Description: The flag is deprecated and always implicitly set in all p4_int_wait() (see section 1.13.4.4) system calls to forward an unanswered interrupt request to the next waiting thread in the chain. This flag is set by the receiving thread.

P4_NUM_INTERRUPT Number of interrupts handled by the kernel. Description: The kernel is able to handle a maximum number of P4_NUM_INTERRUPT interrupts. The maximum number of supported interrupt is architecture dependent.

P4_MAX_SHARED_INTERRUPTS Maximum number of shared interrupts.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Interrupt API 141

      Description:
      The kernel is able to handle up to P4_MAX_SHARED_INTERRUPTS threads waiting for the same
      interrupt. Any further attempt to attach to this interrupt causes the error code P4_E_LIMIT to be
      returned.

P4_INT_MODE_ANY Requested interrupt mode: MODE_ANY. Description: No specific mode requested

P4_INT_MODE_LEVEL_LOW Requested interrupt mode: MODE_LOW. Description: Level-triggered interrupt (level low).

P4_INT_MODE_LEVEL_HIGH Requested interrupt mode: MODE_HIGH. Description: Level-triggered interrupt (level high).

P4_INT_MODE_EDGE_FALL Requested interrupt mode: MODE_EDGE_FALL. Description: Edge-triggered interrupt (fall front).

P4_INT_MODE_EDGE_RISE Requested interrupt mode: MODE_EDGE_RISE. Description: Edge-triggered interrupt (rise front).

P4_INT_MODE_EDGE_BOTH Requested interrupt mode: MODE_EDGE_BOTH. Description: Edge-triggered interrupt (both fronts).

P4_INT_MODE_FORWARD Requested interrupt mode: MODE_FORWARD. Description: Forwarded interrupt: might be OR-ed with another mode to request the interrupt to be forwarded (e.g., to allow decoupled management of virtual interrupts).

P4_INT_GET_BIT (ibm_p, num) This macro tests, whether the bit for interrupt num is set in the interrupt bitmap pointed to by ibm_p.

      Parameters:
            ibm_p Pointer to the interrupt bitmap to be tested.
            num Interrupt number (0 ... P4_NUM_INTERRUPT-1).


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

142 The PikeOS Kernel API

      Returns:
      TRUE if the bit is set, FALSE otherwise.

      Note:
      If num is not a valid interrupt number the return value is undefined.

P4_INT_SET_BIT (ibm_p, num) This macro sets the bit for the interrupt number given by num in the interrupt bitmap pointed to by ibm_p.

      Parameters:
          ibm_p Pointer to the interrupt bitmap.
          num Interrupt number (0 ... P4_NUM_INTERRUPT-1).
      Note:
      If num is not a valid interrupt number the effects of this macro are undefined.

P4_INT_FILL_SET (ibm_p) Initialise interrupt bitmap with all bits set. Description: This macro fills the interrupt bitmap pointed to by ibm_p, i.e. all interrupt rights will be set (enabled).

      Parameters:
          ibm_p Pointer to the interrupt bitmap.

P4_INT_CLEAR_SET (ibm_p) Initialise interrupt bitmap with all bits cleared. Description: This macro clears the interrupt bitmap pointed to by ibm_p, i.e. all interrupt rights will be cleared (disabled).

      Parameters:
          ibm_p Pointer to the interrupt bitmap.

1.13.3 Data Type Definitions

P4_int_mode_t Requested interrupt mode flag data type. This data type contains a P4_INT_MODE flag that can be specified in the p4_int_attach_syscall() (see section 1.13.4.1) to request the PSP to setup specific interrupt modes for the interrupt line. P4_interrupt_bitmap_t Interrupt bitmap structure. The interrupt bitmap is used to store and communicate the set of interrupts granted to a task. The bitmap contains one bit for every interrupt number (0 ... P4_NUM_INTERRUPT-1) where the interrupt number is reflected in the bit position within the bitmap and the attribute value is given by the bit value. The interrupt bitmap structure is to be treated as an opaque data type and should only be accessed by the macros P4_INT_GET_BIT() (see section 1.13.2) and P4_INT_SET_BIT() (see section 1.13.2).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Interrupt API 143

1.13.4 Functions

1.13.4.1 p4_int_attach_syscall

Attach the calling thread to an interrupt (extended version).

Synopsis:

P4_e_t p4_int_attach_syscall(P4_intid_t intid, P4_int_mode_t mode)

Parameters: intid IN: ID of the interrupt to which the calling thread shall be attached. If P4_INT_DETACH is specified, the thread will be detached from the any previously attached interrupt source. mode IN: Requested interrupt-mode-level for intid.

Description: This function attaches the calling thread to an interrupt. If the calling thread is already attached to another interrupt, it is first detached from this interrupt. The parameter intid specifies the interrupt number. If more than one thread attaches to the same interrupt, the thread priority at the time of calling this function is used to determine the order of thread execution when the interrupt occurs. The same order determines the interrupt affinity on SMP systems. The interrupt is bound to the processor where the first of the attached threads runs. The parameter mode specifies the requested interrupt mode type (e.g., level triggered, edge triggered) requested for the intid. P4_INT_MODE_ANY indicates that no specific mode is requested. Depending on the PSP, binding interrupts to specific processors (interrupt affinity), interrupt sharing and interrupt modes except P4_INT_MODE_ANY may not be supported. Refer to your platform manual for PSP limitations.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if intid does not refer to a valid interrupt number. P4_E_INVAL if mode does not refer to a valid P4_int_mode_t mode. P4_E_PERM if the calling threads task has not been granted the right to attach to interrupt number intid. P4_E_NOENT if the interrupt is not available on the platform. P4_E_MISMATCH if the mode is not supported for intid P4_E_LIMIT if the maximum number of threads are already attached to a shared interrupt.

Note: Calling p4_int_attach() (see section 1.13.4.2) with intid set to P4_INT_DETACH has the same effect as calling p4_int_detach() (see section 1.13.4.3). If a thread detaches from a shared interrupt and there are other threads waiting, then, similarly to wait, the interrupt is chained to the other waiters before unmasking the interrupt line again.

Note: Regardless of the error code, the thread is always detached from any previous interrupt attachment.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

144 The PikeOS Kernel API

1.13.4.2 p4_int_attach

Attach the calling thread to an interrupt.

Synopsis:

__forceinline P4_e_t p4_int_attach(P4_intid_t intid)

Parameters: intid IN: ID of the interrupt to which the calling thread shall be attached. If P4_INT_DETACH is specified, the thread will be detached from the any previously attached interrupt source.

Description: This function attaches the calling thread to an interrupt. If the calling thread is already attached to another interrupt, it is first detached from this interrupt. The parameter intid specifies the interrupt number. If more than one thread attaches to the same interrupt, the thread priority at the time of calling this function is used to determine the order of thread execution when the interrupt occurs.

Note: This function calls p4_int_attach_syscall() (see section 1.13.4.1) internally, with the mode parameter set to P4_INT_MODE_ANY. See p4_int_attach_syscall() (see section 1.13.4.1) for a description of the functions be- havior.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Interrupt API 145

1.13.4.3 p4_int_detach

Detach the calling thread from an interrupt.

Synopsis:

__forceinline void p4_int_detach(void)

Description: A call to this function detaches the calling thread from any previously attached interrupt source. If no interrupt is attached, a call to this function has no effect. If a thread detaches from a shared interrupt and there are other threads waiting, then, similarly to wait, the interrupt is chained to the other waiters before unmasking the interrupt line again.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

146 The PikeOS Kernel API

1.13.4.4 p4_int_wait

Chain interrupts to other waiting threads and wait for the next interrupt.

Synopsis:

P4_e_t p4_int_wait(P4_timeout_t timeout, P4_uint32_t flags)

Parameters: timeout IN: Maximum timeout to wait for an interrupt to occur flags IN: Set of bits used to further control interrupt handling. Currently ignored and always implicitly set to P4_INT_CHAIN.

Description: The interrupt is chained to the next waiting thread (if any exist). Then the calling thread is suspended until its attached interrupt occurs or the specified timeout expires. The flags field is ignored, and implicitly the (deprecated) P4_INT_CHAIN flag is always set.

Pre-Conditions: The calling thread must have attached itself to an interrupt by a call to p4_int_attach() (see section 1.13.4.2).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_NOENT if the calling thread is not attached to an interrupt. P4_E_CANCEL if the function was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU. P4_E_BADTIMEOUT if the specified timeout is invalid or in the past. P4_E_TIMEOUT if the specified timeout has expired before an interrupt occurred.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Interrupt API 147

1.13.4.5 p4_int_grant

Grant the right to attach to a set of interrupts to another task.

Synopsis:

P4_e_t p4_int_grant(P4_task_t task, const P4_interrupt_bitmap_t *int_map_p)

Parameters: task IN: Number of the task which shall receive the interrupt attach permission. int_map_p IN: Pointer to interrupt bitmap.

Description: A call to this function grants the right to attach to an interrupt to another task. The parameter int_map_p points to an interrupt bitmap, and the parameter task specifies the destination task number, which must be an active child task of the calling task. A set bit in the bitmap indicated that the corresponding interrupt attach permission shall be granted. The calling thread must have the permission to attach to this interrupt. The permission still remains in the calling task. The permission cannot be revoked, except by killing the receiving child task.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if int_map_p is NULL, or if int_map_p is invalid or exceeds the virtual address space, or if int_map_p does not point to a valid address in the callers address space, or if task does not refer to a valid task number. P4_E_PAGEFAULT if int_map_p is not fully mapped in the callers address space. P4_E_BADTASK if task is not a child task of the calling task. P4_E_STATE if task is not active. P4_E_PERM if int_map_p has bits set of interrupts not being granted to the calling task.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

148 The PikeOS Kernel API

1.13.4.6 p4_int_link

Grant a single interrupt attach permission to another task.

Synopsis:

P4_e_t p4_int_link(P4_task_t task, P4_intid_t intid)

Parameters: task IN: Number of the task that shall receive the interrupt attach right. intid IN: Number of the interrupt that shall be granted.

Description: A call to this function passes the permission to attach to an interrupt to another task. The parameter intid must specify a valid interrupt, and the task of the calling thread must have the permission to attach to this interrupt. The parameter task specifies the destination task number, which must be an active child task of the calling task. The permission still remains in the calling task. The permission cannot be revoked, except by killing the receiving child task.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if intid does not refer to a valid interrupt number, or if task does not refer to a valid task number. P4_E_BADTASK if task is not a child task of the calling task. P4_E_STATE if task does not exist. P4_E_PERM if the calling threads task does not have the right to attach to interrupt intid.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 149

1.14 Exception Handling

This section describes constants, data types, and access macros related to the generic part of the PikeOS exception handling.

1.14.1 Structure Definitions

1.14.1.1 struct P4_short_ex_str

Short exception message. Format of a short exception message as used by the PikeOS short exception mechanism. The kernel sends and receives messages in this format.

Synopsis:

struct P4_short_ex_str { P4_ex_code_t status; P4_address_t addr; P4_cpureg_t epc; P4_cpureg_t sp; P4_cpureg_t arch1; P4_cpureg_t arch2; };

Structure Element Description: status [RECEIVED by user] status contains the exception message status code. This status code contains the trapcode and, in the case of a page fault, some flags describing the cause of the page fault. [SEND by user] The exception handler signals the kernel what to do next with the faulting thread. Set status to one of the codes described below:

            • P4_EX_CONTINUE: Continue execution.
            • P4_EX_NEXT_EXCEPTION: Chain exception to next exception handler.

addr [RECEIVED by user] addr contains the fault address if a page fault exception was detected, otherwise this value is undefined. [SEND by user] This value is ignored. epc epc contains the saved program counter of the faulting thread. The short exception message handler is allowed to change the program counter, for example to set it to a fault recovery procedure. The kernel accepts the modification only if P4_EX_CONTINUE is sent as the reply code. sp sp contains the saved stack pointer of the faulting thread. The short exception message handler is allowed to change the stack pointer, for example to set it to a fault recovery stack. The kernel accepts the modification only if P4_EX_CONTINUE is sent as the reply code. arch1 arch1 contains an architecture dependent cpu register of the faulting thread. The short exception mes- sage handler is allowed to change the register. The kernel accepts the modification only if P4_EX_CON- TINUE is sent as the reply code. arch2 arch2 contains an architecture dependent cpu register of the faulting thread. The short exception mes- sage handler is allowed to change the register. The kernel accepts the modification only if P4_EX_CON- TINUE is sent as the reply code.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

150 The PikeOS Kernel API

Associated Data Type

P4_short_ex_t Short exception message.

1.14.2 Page Fault and Exception Types

The following constants describe the different types of page faults and exceptions. All flags can be OR-ed together.

Defines

P4_PF_NOMAP Fault was caused by an unmapped memory access in faulters address space. Description: This value indicates that the faulting thread accessed a memory area that has no mapping associated. This flag is only valid for exceptions of type P4_TRAP_SEG.

P4_PF_READ Fault was caused due to a data read access. Description: For an exception of type P4_TRAP_SEG, this value indicates that the faulting thread accessed a memory area with improper access permissions, i.e. tried to read but does not have read permission. For an exception of type P4_TRAP_BUS, this value indicates that the faulting thread tried to read from a memory area in an inappropriate way. For an exception of type P4_TRAP_BRK, this value indicates a hardware watchpoint exception. This flag is only valid for exceptions of types P4_TRAP_SEG, P4_TRAP_BUS, and P4_TRAP_BRK.

P4_PF_WRITE Fault was caused due to a data write access. Description: For an exception of type P4_TRAP_SEG, this value indicates that the faulting thread accessed a memory area with improper access permissions, i.e. tried to write but does not have write permission. For an exception of type P4_TRAP_BUS, this value indicates that the faulting thread tried to write to a memory area in an inappropriate way. For an exception of type P4_TRAP_BRK, this value indicates a hardware watchpoint exception. This flag is only valid for exceptions of types P4_TRAP_SEG, P4_TRAP_BUS, and P4_TRAP_BRK.

P4_PF_EXEC Fault was caused due to code execution. Description: For an exception of type P4_TRAP_SEG, this value indicates that the faulting thread accessed a memory area with improper access permissions, i.e. tried to execute code but does not have permission to execute code from that memory area. For an exception of type P4_TRAP_BUS, this value indicates that the faulting thread tried to execute code from a memory area in an inappropriate way. For an exception of type P4_TRAP_BRK, this value indicates a hardware breakpoint exception.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 151

       This flag is only valid for exceptions of types P4_TRAP_SEG, P4_TRAP_BUS, and P4_TRAP_BRK.

P4_PF_ALIGN Fault was caused due to incorrect alignment. Description: This value indicates that the faulting thread accessed memory with improper alignment. This flag is only valid for exceptions of type P4_TRAP_BUS.

P4_PF_SSTEP Fault was caused due to single step exception. Description: This value indicates that the faulting thread has single stepping enabled and caused a single step exception. This flag is only valid for exceptions of type P4_TRAP_BRK.

P4_PF_TRAP Fault was caused due to trap instruction exception. Description: This value indicates that the faulting thread executed a trap instruction and caused an exception. This flag is only valid for exceptions of type P4_TRAP_BRK.

1.14.3 Exception Reply Codes

The following constants describe the possible reply codes which can be used to reply to an exception message.

Defines

P4_EX_CONTINUE Continue execution. Description: This value indicates that the faulting thread should continue execution.

P4_EX_NEXT_EXCEPTION Chain exception to next exception handler. Description: This value indicates that the faulting thread should chain the exception to the next exception handler in exception processing. If this was the last exception handler in exception procesing, the task of the faulting thread is killed.

1.14.4 Defines

P4_TRAP_NUM

       Description:
       Total number of defined trap codes


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

152 The PikeOS Kernel API

P4_EX (t, ff) Build an exception message status code. Description: This macro builds an exception message status code from a trapcode t and some page fault or health monitoring flags ff.

    Parameters:
            t Specifies the trapcode.
           ff Specifies the page fault or health monitoring flags.

P4_EX_TRAP_CODE (x) Extract trapcode. Description: This macro extracts the trapcode from an exception message status code.

P4_EX_TRAP_INFO (x) Extract additional trapcode-related information on the exception. Description: This macro extracts the page fault or health monitoring flags from an exception message status code.

P4_TRAP_NOT 0

    Description:
    No exception, caught in user space: The exception register frame shows the thread while running in
    user space. The thread is ready to continue immediately.

P4_TRAP_ILL 1

    Description:
    Illegal instruction: The thread tried to execute an instruction undefined on the target platform. The
    thread is not ready to continue, but the exception handler can try to emulate the effects of the faulting
    instruction.

P4_TRAP_BRK 2

    Description:
    Breakpoint: The thread executed a breakpoint instruction. The thread is ready to continue immediately,
    however the exception handler should replace the breakpoint instruction and rewind the registers to
    restart the original instruction.

P4_TRAP_ARI 3

    Description:
    Arithmetic overflow: An arithmetic overflow such as division by zero was detected. The thread may not
    be ready to continue, the exception handler should handle this.

P4_TRAP_FP 4

                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 153

     Description:
     FPU exception: An FPU exception such as overflow, underflow, or using NaN as operand was detected.
     The thread may not be ready to continue, the exception handler should handle this.

P4_TRAP_BUS 5

     Description:
     Bus error: A bus error was detected. The thread may not be ready to continue, the exception handler
     should handle this.

P4_TRAP_SEG 6

     Description:
     Segment violation: The faulting thread triggered a page fault exception. The thread is usually ready to
     continue immediately after the proper mapping has been applied.

P4_TRAP_TRP 7

     Description:
     Trap exception: A trap exception was detected. The thread may not be ready to continue, the exception
     handler should handle this.

P4_TRAP_SYS 8

     Description:
     Non-P4 system call: A non-P4 system call was executed. This usually happens when executing native
     binaries of a foreign OS. The execption handler should emulate the proper system call.

P4_TRAP_FP_UNAVAIL 9

     Description:
     FPU unavailable: This exception is caused by a thread that tries to utilize the FPU but does not have
     FPU support enabled. The thread may not be ready to continue, the exception handler should handle
     this.

P4_TRAP_CTXT 10

     Description:
     Broken register context: The register context is in an undefined state. The exception handler must setup
     a new register context before the thread may be ready to continue.

P4_TRAP_TASK_DEAD 11

     Description:
     Task death notification. This ID is signaled as part of a health-monitoring notification to the partition
     level handler (normally the SSW).


                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

154 The PikeOS Kernel API

__P4_TRAP_TASK_RESERVED1 12

      Description:
      This value is reserved and shall not be used.

P4_TRAP_DEADLINE 13

      Description:
      Deadline missed notification: A thread that registered a deadline via the p4_thread_alarm() (see section
      1.16.5.7) system call did not remove that deadline before it expired.

P4_TRAP_DOUBLE 14

      Description:
      Double exception notification: An exception happened or was triggered in the context of a user-level
      exception handler while it was already managing an exception.

P4_trap_code_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

P4_trap_code_MAX 14

      Description:
      Maximum value of the enum type

1.14.5 Data Type Definitions

P4_regs_t User mode context. The user mode context is a data structure of CPU registers which stores the user mode execution state of a thread. Refer to the architecture manual for more information. P4_short_ex_t Short exception message. Format of a short exception message as used by the PikeOS short exception mechanism. The kernel sends and receives messages in this format. P4_trap_code_t Trapcode: Common trap conditions. This data type contains a trapcode. The trapcode is an architecture independent flag describing the error that caused the exception. For the exact mapping of different architecture dependent exceptions and traps, see architecture refer- ence manual.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 155

1.14.6 Functions

1.14.6.1 p4_regs_get_fault

Retrieve fault information from user mode context structure.

Synopsis:

P4_cpureg_t p4_regs_get_fault(const P4_regs_t *regs)

Parameters: regs IN: User mode context, must not be NULL.

Returns: This function returns the fault information included in the architecture specific user mode context structure regs.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

156 The PikeOS Kernel API

1.14.6.2 p4_regs_set_fault

Set fault address register in user mode context.

Synopsis:

void p4_regs_set_fault(P4_regs_t *regs, P4_cpureg_t reg)

Parameters: regs OUT: User mode context, must not be NULL. reg IN: New value for fault register

Description: This function sets the fault register in the architecture- specific user mode context structure regs.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 157

1.14.6.3 p4_regs_get_epc

Retrieve instruction pointer from user mode context structure.

Synopsis:

P4_cpureg_t p4_regs_get_epc(const P4_regs_t *regs)

Parameters: regs IN: User mode context, must not be NULL.

Returns: This function returns the instruction pointer included in the architecture specific user mode context structure regs.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

158 The PikeOS Kernel API

1.14.6.4 p4_regs_set_epc

Set program counter register in user mode context.

Synopsis:

void p4_regs_set_epc(P4_regs_t *regs, P4_cpureg_t reg)

Parameters: regs OUT: User mode context, must not be NULL. reg IN: New value for program counter

Description: This function sets the program counter in the architecture- specific user mode context structure regs.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 159

1.14.6.5 p4_regs_get_fp

Retrieve frame pointer from user mode context structure.

Synopsis:

P4_cpureg_t p4_regs_get_fp(const P4_regs_t *regs)

Parameters: regs IN: User mode context, must not be NULL.

Returns: This function returns the frame pointer included in the architecture specific user mode context structure regs.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

160 The PikeOS Kernel API

1.14.6.6 p4_regs_set_fp

Set frame pointer in user mode context structure.

Synopsis:

void p4_regs_set_fp(P4_regs_t *regs, P4_cpureg_t fp)

Parameters: regs OUT: User mode context, must not be NULL. fp IN: Frame pointer.

Description: This function sets the frame pointer to fp in the architecture specific user mode context structure regs.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 161

1.14.6.7 p4_regs_get_sp

Retrieve stack pointer from user mode context structure.

Synopsis:

P4_cpureg_t p4_regs_get_sp(const P4_regs_t *regs)

Parameters: regs IN: User mode context, must not be NULL.

Returns: This function returns the stack pointer included in the architecture specific user mode context structure regs.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

162 The PikeOS Kernel API

1.14.6.8 p4_regs_set_sp

Set stack pointer in user mode context.

Synopsis:

void p4_regs_set_sp(P4_regs_t *regs, P4_cpureg_t reg)

Parameters: regs OUT: User mode context, must not be NULL. reg IN: New value for stack pointer

Description: This function sets the stack pointer in the architecture- specific user mode context structure regs.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 163

1.14.6.9 p4_regs_get_arch1

Retrieve first architecture specific register from user mode context structure.

Synopsis:

P4_cpureg_t p4_regs_get_arch1(const P4_regs_t *regs)

Parameters: regs IN: User mode context, must not be NULL.

Returns: This function returns the first architecture specific register included in the architecture specific user mode context structure regs.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

164 The PikeOS Kernel API

1.14.6.10 p4_regs_set_arch1

Set first architecture-specific register in user mode context.

Synopsis:

void p4_regs_set_arch1(P4_regs_t *regs, P4_cpureg_t reg)

Parameters: regs OUT: User mode context, must not be NULL. reg IN: New value for first architecture-specific register.

Description: This function sets the first architecture-specific register in the architecture-specific user mode context structure regs.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 165

1.14.6.11 p4_regs_get_arch2

Retrieve second architecture specific register from user mode context structure.

Synopsis:

P4_cpureg_t p4_regs_get_arch2(const P4_regs_t *regs)

Parameters: regs IN: User mode context, must not be NULL.

Returns: This function returns the second architecture specific register included in the architecture specific user mode context structure regs.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

166 The PikeOS Kernel API

1.14.6.12 p4_regs_set_arch2

Set second architecture-specific register in user mode context.

Synopsis:

void p4_regs_set_arch2(P4_regs_t *regs, P4_cpureg_t reg)

Parameters: regs OUT: User mode context, must not be NULL. reg IN: New value for second architecture-specific register.

Description: This function sets the second architecture-specific register in the architecture-specific user mode context structure regs.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 167

1.14.6.13 p4_regs_get_ex_code

Retrieve exception code from user mode context structure.

Synopsis:

P4_ex_code_t p4_regs_get_ex_code(const P4_regs_t *regs)

Parameters: regs IN: User mode context, must not be NULL.

Returns: This function returns the exception code included in the architecture specific user mode context structure regs.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

168 The PikeOS Kernel API

1.14.6.14 p4_regs_set_ex_code

Set exception code in user mode context structure.

Synopsis:

void p4_regs_set_ex_code(P4_regs_t *regs, P4_ex_code_t code)

Parameters: regs OUT: User mode context, must not be NULL. code IN: Exception answer code.

Description: This function sets the exception answer code code in the architecture specific user mode context structure regs.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Exception Handling 169

1.14.6.15 p4_regs_get_syscall

Retrieve number of last system call from user mode context structure.

Synopsis:

P4_cpureg_t p4_regs_get_syscall(const P4_regs_t *regs)

Parameters: regs IN: User mode context, must not be NULL.

Returns: This function returns the number of the last system call included in the architecture specific user mode context structure regs.

Note: The function is a debugging aid. The returned system call number is only valid when a thread is performing a system call in the kernel.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

170 The PikeOS Kernel API

1.15 Mapping API

This section describes constants, data types, access macros, and service functions related to the PikeOS memory mapping API.

1.15.1 Structure Definitions

1.15.1.1 struct P4_sglist_str

Scatter-Gather list entry. Format of a scatter-gather list entry used by p4_mem_build_sglist() (see section 1.15.6.5).

Synopsis:

struct P4_sglist_str { P4_phys_addr_t phys; P4_address_t virt; P4_size_t size; P4_access_t attrib; P4_uint32_t unused; };

Structure Element Description: phys Physical address of memory area. virt Virtual address of memory area. size Size of the area in bytes. attrib Access permissions and cache attributes. unused Padding

Associated Data Type

P4_sglist_t Scatter-Gather list entry.

1.15.2 Mapping Flags

The following constants describe the flags used to specify the access permissions and cache attributes of a mapping. The data type P4_access_t (see section 1.2.2) is designated to store them. Unless otherwise noticed, all flags can be OR-ed together.

Defines

P4_M_REPLACE (1U << 11) Mapping flag: replace previous mappings for destination memory area. Description:

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 171

     Setting this flag indicates that any previous mappings for the designated virtual memory area shall be
     overwritten. If this flag is not set and a mapping operation detects an existing mapping, an error is raised
     and P4_E_OVERMAP is returned.

P4_M_UPDATE (1U << 0) Mapping flag for access permissions: update access permissions. Description: Setting this value indicates that the access permissions P4_M_READ, P4_M_WRITE and P4_M_EXEC shall be updated for the designated virtual memory area. Note that architecture specific rules ap- ply here, i.e. both P4_M_WRITE and P4_M_EXEC access permissions imply P4_M_READ, and the P4_M_READ access permission implies P4_M_EXEC on architectures without support for non- executable mappings. P4_M_EXEC can be removed or added freely, if supported by the architecture. If this flag is not set, access permissions are inherited.

P4_M_READ (1U << 1) Mapping flag for access permissions: memory area is readable. Description: Setting this value indicates that read permission shall be enabled on the designated virtual memory area. Setting or clearing this flag is only effective if P4_M_UPDATE is set. If this value is set, the virtual memory area is readable.

P4_M_WRITE (1U << 2) Mapping flag for access permissions: memory area is writable. Description: Setting this value indicates that write permission shall be enabled on the designated virtual memory area. Setting or clearing this flag is only effective if P4_M_UPDATE is set. If this value is set, the virtual memory area is writable.

P4_M_EXEC (1U << 3) Mapping flag for access permissions: memory area is executable. Description: Setting this value indicates that execute permission shall be enabled on the designated virtual memory area. Setting or clearing this flag is only effective if P4_M_UPDATE is set. If this value is set, the virtual memory area is executable.

P4_M_C_UPDATE (1U << 10) Mapping flag for cache attributes: update cache settings. Description: Setting this value indicates that the cache attributes P4_M_C_ENABLE, P4_M_C_WRITEBACK, P4_M_C_PREFETCH, P4_M_C_COHERENCY, P4_M_C_PLATFORM1, and P4_M_C_PLATFORM2 shall be updated for the designated virtual memory area. If this flag is not set, no cache attributes will be changed.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

172 The PikeOS Kernel API

P4_M_C_ENABLE (1U << 4) Mapping flag for cache attributes: enable caching. Description: If this flag is set, caching will be enabled on the designated virtual memory area. Clearing this flag disables caching. Setting or clearing this flag is only effective if P4_M_C_UPDATE is set. If this value is set, the virtual memory area is cacheable.

P4_M_C_WRITEBACK (1U << 5) Mapping flag for cache attributes: enable "write back" caching. Description: Setting this flag indicates that the usually faster "write back" caching strategy shall be used. If the flag is not set, a "write through" caching strategy will be used. Setting or clearing this flag is only effective if P4_M_C_UPDATE and P4_M_C_ENABLE are set. If this value is set, the virtual memory area uses "write back" caching.

P4_M_C_PREFETCH (1U << 6) Mapping flag for cache attributes: allow prefetches. Description: Setting this flag indicates that the CPU might use "speculative reads" or "prefetches" to access the memory. Setting or clearing this flag is only effective if P4_M_C_UPDATE and P4_M_C_ENABLE are set. Setting this value when P4_M_C_ENABLE is cleared has no effect. If this value is set, prefetches and speculative reads are allowed in the virtual memory area.

P4_M_C_COHERENCY (1U << 7) Mapping flag for cache attributes: enforce memory coherency. Description: Setting this flag indicates that the CPU shall enforce memory coherency when accessing the memory. Coherency is needed for platforms where two or more components access the same area of memory without previous negotiation. Setting or clearing this flag is only effective if P4_M_C_UPDATE is set. If this value is set, memory coherency is enforced in the virtual memory area.

P4_M_C_PLATFORM1 (1U << 8) Mapping flag for cache attributes: platform specific attribute. Description: Setting or clearing this flag indicates that a platform specific feature should be enabled or disabled. Setting or clearing this flag is only effective if P4_M_C_UPDATE is set.

P4_M_C_PLATFORM2 (1U << 9) Mapping flag for cache attributes: platform specific attribute. Description: Setting or clearing this flag indicates that a platform specific feature should be enabled or disabled. Setting or clearing this flag is only effective if P4_M_C_UPDATE is set.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 173

P4_M_C_UC Convenience value: uncached strongly-ordered memory access. Description: Setting this value indicates that caching should be disabled, and memory accesses should be strongly- ordered. This value can be used as a convenience and consists of just the P4_M_C_UPDATE and P4_M_C_CO- HERENCY flags. The VMIT cache mode VM_MEM_CACHE_INHIBIT maps to this.

P4_M_C_DEV Convenience value: ARM memory type "device" or uncached memory access. Description: Setting this value on ARM processors indicates that the memory type "shared device" shall be used. On other architectures, this value indicates that caching should be disabled, and memory accesses should be strongly-ordered. This value can be used as a convenience and consists of just the P4_M_C_UPDATE, P4_M_C_WRITE- BACK, and P4_M_C_COHERENCY flags. The VMIT cache mode VM_MEM_CACHE_DEV maps to this.

P4_M_C_WC Convenience value: uncached write-combining memory access. Description: Setting this value indicates that caching should be disabled, but memory accesses should use write- combining. This value can be used as a convenience and consists of just the P4_M_C_UPDATE, P4_M_C_PREFETCH, and P4_M_C_COHERENCY flags. The VMIT cache mode VM_MEM_CACHE_WC maps to this.

P4_M_C_WT Convenience value: cached write-through memory access. Description: Setting this value indicates that "write through" caching and speculative read and prefetches should be turned on. This value is a compound of the OR-ed P4_M_C_UPDATE, P4_M_C_ENABLE, P4_M_C_CO- HERENCY, and P4_M_C_PREFETCH flags and can be used as a convenience. The VMIT cache mode VM_MEM_CACHE_WT maps to this.

P4_M_C_WB Convenience value: cached write-back memory access. Description: Setting this value indicates that "write back" caching and speculative read and prefetches should be turned on. This value is a compound of the OR-ed P4_M_C_UPDATE, P4_M_C_ENABLE, P4_M_C_CO- HERENCY, P4_M_C_WRITEBACK, and P4_M_C_PREFETCH flags and can be used as a conve- nience. The VMIT cache mode VM_MEM_CACHE_CB maps to this.

                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

174 The PikeOS Kernel API

1.15.3 Cache Synchronization Flags

The following constants describe the flags used to specify the cache synchronization operations in cross address space memory transfers. Unless otherwise noticed, all flags can be OR-ed together.

Defines

P4_ICACHE_COHERENCY Cache synchronization flag: synchronize instruction and data caches. Description: Setting this flag indicates that data content of data and instruction caches shall be synchronized. Con- tents of the data cache of the specified memory range shall be written to memory and the corresponding instruction cache contents shall be invalidated. The feature flag P4_NEED_ICACHE_COHERENCY in- dicates if an architecture requires manual coherency between data and instruction caches.

1.15.4 Defines

P4_PAGESIZE Page size. Description: Size of the smallest mapping entity on the platform

P4_PAGEMASK Page mask for virtual addresses (P4_address_t) Description: Value to mask out the address offset within a page

P4_PHYS_PAGEMASK Page mask for physical addresses (P4_phys_addr_t) Description: Value to mask out the address offset within a page

P4_LOG2_PAGESIZE Page size shift. Description: Value an address must be shifted to the right to extract the page frame number from an address

P4_KINFO_BASE KINFO Page base address.

P4_MEM_USR_BASE Base address of virtual user space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 175

P4_MEM_USR_END End address of virtual user space.

P4_MEM_KERN_BASE Base address of virtual kernel space.

P4_MEM_KERN_RSVD Start address of reserved part of the virtual kernel space.

P4_MEM_KERN_END End address of virtual kernel space.

P4_PAGE_BASE (addr) Page align virtual address. Description: This macro aligns a virtual address to its page.

      Parameters:
          addr Virtual address
      Returns:
      Returns the page aligned virtual address.

P4_PHYS_PAGE_BASE (addr) Page align physical address. Description: This macro aligns a physical address to its page.

      Parameters:
          addr Physical address
      Returns:
      Returns the page aligned physical address.

P4_PAGE_OFFS (addr) Get page offset of an address. Description: This macro extracts the offset within a page of an address.

      Parameters:
          addr Physical or virtual address
      Returns:
      Returns the page offset.

1.15.5 Data Type Definitions

P4_sglist_t Scatter-Gather list entry. Format of a scatter-gather list entry used by p4_mem_build_sglist() (see section 1.15.6.5).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

176 The PikeOS Kernel API

1.15.6 Functions

1.15.6.1 p4_mem_map

Map a number of pages from one tasks address space to another.

Synopsis:

P4_e_t p4_mem_map(P4_task_t target, P4_address_t dest, P4_size_t length, P4_address_t source, P4_access_t access, P4_address_t *error_addr)

Parameters: target IN: ID of the child task that shall receive the mapping. If target is P4_TASK_MYSELF, the mapping will be applied to the callers address space. dest IN: Destination address in target tasks address space. The value must be a multiple of P4_PAGESIZE. length IN: Size of the source and destination memory area. The value must be non-zero and a multiple of P4_PAGESIZE. source IN: Address of source area in callers address space. The value must be a multiple of P4_PAGESIZE. access IN: Set of bits to control access permissions and cache attributes of the destination area. If zero, access permissions and cache attributes are inherited. If P4_M_REPLACE is set, any existings mappings for the destination area are replaced. error_addr OUT: error_addr contains the first address in the destination memory area that was not mapped. In the case of an error, error_addr contains the address in the memory area where the error occurred or the start address of the memory area if mapping was not started. In the case of other error codes than P4_E_NOKMEM, P4_E_PERM, P4_E_BADMAP, and P4_E_OVERMAP, error_addr is undefined. If NULL, no error address will be returned.

Description: This function maps pages described by source and length (the source area) from the callers address space to address dest (the destination area) with access permissions access in the address space of task target. The target address space may be the callers task or one of its child tasks. The source and destination areas must be valid user space regions. Each page in the source area must be mapped in the callers address space and must have the same or greater access permissions than described by access. If P4_M_C_UPDATE is set in access, the cache attributes in the destination area will be be changed. Overlapping source and destination areas in the same address space are not allowed. Existing mappings for the destination area will only be overwritten if P4_M_REPLACE is set in access, otherwise error P4_E_OVERMAP is returned. In the case of error codes P4_E_NOKMEM, P4_E_PERM, P4_E_BADMAP or P4_E_OVERMAP, error_addr is valid and only a partial mapping of size error_addr - dest is installed in the destination area. error_addr contains

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 177

the first address in the destination area where the new mapping could not be created. In the case of error codes P4_E_NOABILITY, P4_E_INVAL, P4_E_ALIGN, P4_E_BADTASK, or P4_E_STATE, any existing mappings for the destination area will be unchanged.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if dest, source, or length are not multiples of P4_PAGESIZE, or if length is zero, or if source and length do not describe a valid memory area in the callers virtual address space, or if dest and length do not describe a valid memory area in the destination tasks virtual address space, or if target is not a valid task id, or if target is the callers task and the source and destination areas overlap, or if an invalid combination of access permissions is passed (P4_M_UPDATE set, but none of P4_M_READ, P4_M_WRITE, or P4_M_EXEC). P4_E_ALIGN if dest does not match the alignment requirements of the specified memory area. P4_E_BADTASK if target is neither the callers task nor a child task of the callers task. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_NOKMEM if there is not enough kernel memory available in the resource partition of task target to perform the mapping. P4_E_PERM if the access permissions on the source area are fewer than the requested access permissions. P4_E_BADMAP if the source area is not completely mapped. P4_E_OVERMAP if the destination area contains a mapping and P4_M_REPLACE is not set. P4_E_NOABILITY if the mappings cache attributes are to be changed (P4_M_C_UPDATE set in access), but the task of the calling thread does not have the ability P4_AB_CACHE_CHANGE enabled.

Note: When mapping a memory area with different cache attributes, the caller is responsible to flush the caches before mapping that memory area.

Note: Invalid pointers or unmapped memory areas for error_addr will not raise an error in this system call.

Note: Note that architecture specific rules apply for the access permissions, i.e. both P4_M_WRITE and P4_M_EXEC access permissions imply P4_M_READ, and the P4_M_READ access permission implies P4_M_EXEC on ar- chitectures without support for non-executable mappings. P4_M_EXEC can be enabled or disabled freely, if supported by the architecture. However, the kernel does not allow obtaining writable access permissions for a read-only memory area.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

178 The PikeOS Kernel API

1.15.6.2 p4_mem_unmap

Unmap a virtual memory area.

Synopsis:

P4_e_t p4_mem_unmap(P4_task_t target, P4_address_t addr, P4_size_t length)

Parameters: target IN: ID of the child task whose pages shall be unmapped. If target is P4_TASK_MYSELF, the memory area will be unmapped from the callers address space. addr IN: Address of virtual memory area to be unmapped from target address space. The value must be a multiple of P4_PAGESIZE. length IN: Size of the virtual memory area to unmap. The value must be non-zero and a multiple of P4_PA- GESIZE.

Description: This function unmaps the area described by addr and length in the address space of task target. Any existing mappings are removed and kernel resources are freed if possible. On a successful return from this function, the entire memory area is unmapped, there is no partial unmapping.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if addr or length are not multiples of P4_PAGESIZE, or if length is zero, or if addr and length do not describe a valid memory area in the target virtual address space, or if target is not a valid task id. P4_E_BADTASK if target is neither the callers task nor a child task of the callers task. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state).

Note: When unmapping a memory area which will be mapped again with different cache attributes, the caller is respon- sible to flush the caches before unmapping that memory area.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 179

1.15.6.3 p4_mem_set_attr

Change access permissions and cache attributes of a virtual memory area.

Synopsis:

P4_e_t p4_mem_set_attr(P4_task_t target, P4_address_t addr, P4_size_t length, P4_access_t access, P4_address_t *error_addr)

Parameters: target IN: ID of the child task whose page access permissions and cache attributes shall be changed. If target is P4_TASK_MYSELF, the callers address space will be modified. addr IN: Address of the virtual memory area in target address space. The value must be a multiple of P4_PAGESIZE. length IN: Size of the virtual memory area. The value must be non-zero and a multiple of P4_PAGESIZE. access IN: Set of bits to control access permissions and cache attributes. If zero, access permissions and cache attributes are not changed. error_addr OUT: error_addr contains the first address in the destination memory area that could not be modified. In case of an P4_E_PERM error, this contains the address in the memory area where the error occurred. If NULL, no error address will be returned.

Description: This function changes access permissions and cache attributes of the area described by addr and length in the address space of task target. The target address space may be the callers task or one of its child tasks. The memory area must be a valid user space region. This function gracefully ignores unmapped memory areas in the specified range and does not raise an error. All mapped pages in the memory area must have at least the access permissions specified in access, i.e. it is not possible to turn a read-only mapping into a read-write one. P4_M_EXEC can be enabled or disabled freely, if supported by the architecture. If P4_M_C_UPDATE is set in access, the cache attributes in the destination area will be be changed. On a successful return from this function, all mapped pages in the memory area will have the new access permissions and cache attributes. In the case of error code P4_E_PERM, error_addr is valid and only an area of size error_addr - addr will have been changed and error_addr will contain the address where the new access permissions and cache attributes could not be set. In the case of error codes P4_E_NOABILITY, P4_E_INVAL, P4_E_BADTASK, or P4_E_STATE, the memory area will be unchanged.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if addr or length are not multiples of P4_PAGESIZE, or if length is zero, or

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

180 The PikeOS Kernel API

      if addr and length do not describe a valid memory area in the target virtual address space, or
      if target is not a valid task id, or
      if an invalid combination of access permissions is passed (P4_M_UPDATE set, but none of
      P4_M_READ, P4_M_WRITE or P4_M_EXEC).

P4_E_BADTASK if target is neither the callers task nor a child task of the callers task. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_PERM if the existing access permissions on any page in the memory area are fewer than the requested access permissions. P4_E_NOABILITY if the mappings cache attributes are to be changed (P4_M_C_UPDATE set in access), but the task of the calling thread does not have the ability P4_AB_CACHE_CHANGE enabled.

Note: When changing cache attributes, the caller is responsible to flush the caches before.

Note: Invalid pointers or unmapped memory areas for error_addr will not raise an error in this system call.

Note: Note that architecture specific rules apply for the access permissions, i.e. both P4_M_WRITE and P4_M_EXEC access permissions imply P4_M_READ, and the P4_M_READ access permission implies P4_M_EXEC on ar- chitectures without support for non-executable mappings. P4_M_EXEC can be enabled or disabled freely, if supported by the architecture. However, the kernel does not allow obtaining writable access permissions for a read-only memory area.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 181

1.15.6.4 p4_mem_list

Get a list of mappings for a virtual memory area. This function gracefully handles unmapped areas in the virtual address space.

Synopsis:

__forceinline P4_e_t p4_mem_list(P4_task_t target, P4_address_t addr, P4_size_t length, P4_sglist_t *sglist, P4_uint32_t *entries)

Parameters: target IN: ID of the child task whose address space will be referenced. If target is P4_TASK_MYSELF, the callers address space will be referenced. addr IN: Address of the virtual memory area in target address space. The value must be a multiple of P4_PAGESIZE. length IN: Size of the virtual memory area. The value must be non-zero and a multiple of P4_PAGESIZE. sglist OUT: Pointer to a memory area where the mapping list shall be created. entries IN: Maximum allowed number of entries in mapping list. OUT: Number of entries in list actually written.

Description: This function builds a list with memory attributes of the memory area described by addr and length in the address space of task target. For each block of physical continuous memory pages having the same attributes, a new entry of type P4_sglist_t will be created. The maximum space needed for the list is:

                      size = (length/P 4_P AGESIZE)  sizeof (P 4_sglist_t)

The user must specify the maximum number of entries the list can hold. The number of entries actually used for the list is returned in entries. If the supplied list space is too small to hold all the entries needed to descibe the memory area, P4_E_TRUNC is returned. In the case of error code P4_E_TRUNC, only a partial mapping list may have been created. The address where the error occurred can be calculated from the last valid entry in the mapping list. In the case of error code P4_E_PAGEFAULT, a partial mapping list may have been created, but the mapping may be corrupted. In the case of error codes P4_E_INVAL, P4_E_BADTASK, or P4_E_STATE, no mapping list will have been built.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if addr or length are not multiples of P4_PAGESIZE, or if length is zero, or if addr and length do not describe a valid memory area in the target virtual address space, or if sglist is NULL, or if sglist does not point to a valid address or exceeds the callers virtual address space, or

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

182 The PikeOS Kernel API

      if entries is NULL, or
      if entries does not point to a valid address or exceeds the callers virtual address space, or
      if target is not a valid task id.

P4_E_BADTASK if target is neither the callers task nor a child task of the callers task. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_TRUNC if there is no more space to store entries into the mapping list. P4_E_PAGEFAULT if entries does not point to a fully mapped memory area in the callers virtual address space, or if sglist does not point to a fully mapped memory area in the callers virtual address space.

Note: A non-writeable memory area for entries will not raise an error in this system call.

Note: Unlike p4_mem_build_sglist() (see section 1.15.6.5), p4_mem_list() (see section 1.15.6.4) gracefully handles unmapped areas in the virtual address space and will never return the error code P4_E_BADMAP. Thus the returned list may contain virtually non-contiguous entries. entries is set to zero if no mappings were found in the specified memory area.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 183

1.15.6.5 p4_mem_build_sglist

Build a scatter-gather list for a virtual memory area. This function will not ignore unmapped memory areas in the specified range and raises an error.

Synopsis:

__forceinline P4_e_t p4_mem_build_sglist(P4_task_t target, P4_address_t addr, P4_size_t length, P4_sglist_t *sglist, P4_uint32_t *entries)

Parameters: target IN: ID of the child task whose address space will be referenced. If target is P4_TASK_MYSELF, the callers address space will be referenced. addr IN: Address of the virtual memory area in target address space. The value must be a multiple of P4_PAGESIZE. length IN: Size of the virtual memory area. The value must be non-zero and a multiple of P4_PAGESIZE. sglist OUT: Pointer to a memory area where the scatter-gather list shall be created. entries IN: Maximum allowed number of entries in scatter-gather list. OUT: Number of entries in list actually written.

Description: This function builds a list with memory attributes of the memory area described by addr and length in the address space of task target. For each block of physical continuous memory pages having the same attributes, a new entry of type P4_sglist_t will be created. Each page in this area must be mapped. The maximum space needed for the list is:

                      size = (length/P 4_P AGESIZE)  sizeof (P 4_sglist_t)

The user must specify the maximum number of entries the list can hold. The number of entries actually used for the list is returned in entries. If the supplied list space is too small to hold all the entries needed to descibe the memory area, P4_E_TRUNC is returned. In the case of error codes P4_E_BADMAP and P4_E_TRUNC, only a partial scatter-gather list may have been created. The address where the error occurred can be calculated from the last valid entry in the scatter-gather list. In the case of error code P4_E_PAGEFAULT, a partial scatter-gather list may have been created, but the scatter-gather may be corrupted. In the case of error codes P4_E_INVAL, P4_E_BADTASK, or P4_E_STATE, no scatter-gather list will have been built.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if addr or length are not multiples of P4_PAGESIZE, or if length is zero, or if addr and length do not describe a valid memory area in the target virtual address space, or

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

184 The PikeOS Kernel API

      if sglist is NULL, or
      if sglist does not point to a valid address or exceeds the callers virtual address space, or
      if entries is NULL, or
      if entries does not point to a valid address or exceeds the callers virtual address space, or
      if target is not a valid task id.

P4_E_BADTASK if target is neither the callers task nor a child task of the callers task. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_TRUNC if there is no more space to store entries into the scatter-gather list. P4_E_PAGEFAULT if entries does not point to a fully mapped memory area in the callers virtual address space, or if sglist does not point to a fully mapped memory area in the callers virtual address space. P4_E_BADMAP if the memory area is not completely mapped.

Note: A non-writeable memory area for entries will not raise an error in this system call.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 185

1.15.6.6 p4_mem_create

Create a mapping to a physical memory area.

Synopsis:

__forceinline P4_e_t p4_mem_create(P4_task_t target, P4_address_t dest, P4_size_t length, P4_phys_addr_t phys, P4_access_t access, P4_address_t *error_addr)

Parameters: target IN: ID of the child task which shall receive the mapping. If target is P4_TASK_MYSELF, the callers address space will be modified. dest IN: Address of destination memory area in target address space. The value must be a multiple of P4_PAGESIZE. length IN: Size of the source and destination memory area. The value must be non-zero and a multiple of P4_PAGESIZE. phys IN: Address of physical resource to be mapped. The value must be a multiple of P4_PAGESIZE. access IN: Set of bits to control access permissions and cache attributes of the destination memory area. error_addr OUT: error_addr contains the first address in the destination memory area that was not mapped. In the case of an error, this contains the address in the memory area where the error occurred or the start address of the memory area if mapping was not started. In the case of other error codes than P4_E_NOKMEM and P4_E_OVERMAP, error_addr is undefined. If NULL, no error address will be returned.

Description: This function creates a mapping to a physical memory area. The physical resource, described by phys and length, may be memory or a bus resource. The destination area starting at address dest must be a valid user space region in the address space of task target. Existing mappings for the destination area will only be overwritten if P4_M_REPLACE is set in access, otherwise error P4_E_OVERMAP will be returned. At least one of the access permissions P4_M_READ, P4_M_WRITE, or P4_M_EXEC must be set, the P4_M_UP- DATE flag is ignored. If P4_M_C_UPDATE is not set, caching attributes default to P4_M_C_WB. In the case of error codes P4_E_NOKMEM and P4_E_OVERMAP, error_addr is valid and only a partial mapping of size error_addr - dest is created in the destination area. error_addr contains the address in the destination area where the new mapping could not be created. In the case of error codes P4_E_NOABILITY, P4_E_INVAL, P4_E_ALIGN, P4_E_BADTASK, or P4_E_STATE, any existing mappings for the destination area will be unchanged.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if dest, phys or length are not multiples of P4_PAGESIZE, or

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

186 The PikeOS Kernel API

      if length is zero, or
      if phys and length exceed the physical address space, or
      if dest and length do not describe a valid memory area in the destination virtual address space, or
      if target is not a valid task id, or
      if an invalid combination of access permissions is passed (none of P4_M_READ, P4_M_WRITE, or
      P4_M_EXEC is set).

P4_E_ALIGN if dest does not match the alignment requirements of the specified memory area. P4_E_BADTASK if target is neither the callers task nor a child task of the callers task. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_NOKMEM if there is not enough kernel memory available in the resource partition of the task target to perform the mapping. P4_E_OVERMAP if the destination area contains a mapping and P4_M_REPLACE is not set. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_MEM_CREATE enabled.

Note: For application loading, creating mappings directly in child address spaces may not produce the intended result, as the instruction cache is not guaranteed to be in a coherent state with the data cache. Instead, create a temporary mapping in the callers address space, prepare the new applications code and data, synchronize instruction cache content with data cache content, and then map the temporary mapping into the targets address space.

Note: This call is used internally by PikeOS and usually restricted to system software.

Note: Invalid pointers or unmapped memory areas for error_addr will not raise an error in this system call.

Note: Note that architecture specific rules apply for the access permissions, i.e. both P4_M_WRITE and P4_M_EXEC access permissions imply P4_M_READ, and the P4_M_READ access permission implies P4_M_EXEC on ar- chitectures without support for non-executable mappings. P4_M_EXEC can be enabled or disabled freely, if supported by the architecture. However, the kernel does not allow obtaining writable access permissions for a read-only memory area.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 187

1.15.6.7 p4_ioport_map

Map a number of IO ports from one task to another.

Synopsis:

P4_e_t p4_ioport_map(P4_task_t target, P4_uint32_t port, P4_uint32_t count)

Parameters: target IN: ID of the child task that shall receive the mapping. Because IO ports are mapped idempotently, mapping to the callers task results in a NOP-operation and is hence prohibited. port IN: Base IO port. count IN: Number of IO ports.

Description: This function transfers the access permission for count 8-bit IO ports starting at IO port port from the callers task to target task. IO port addresses are idempotent, i.e. they are not translated, so no source or destination addresses need to be passed. Mapping to the callers task is prohibited. The ports to be mapped must be already mapped in the callers task.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if port and count exceeds the valid port range, or if count is zero, or if target is not a valid task number. P4_E_BADTASK if target is not a child task of the callers task. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_BADMAP if the ports are not fully mapped in the callers task. P4_E_NOTIMPL if the platform does not support IO ports.

Note: This system call is not supported on all platforms.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

188 The PikeOS Kernel API

1.15.6.8 p4_ioport_unmap

Unmap a number of IO ports from a task.

Synopsis:

P4_e_t p4_ioport_unmap(P4_task_t target, P4_uint32_t port, P4_uint32_t count)

Parameters: target IN: ID of the child task where IO ports shall be unmapped. If target is P4_TASK_MYSELF, the callers address space will be modified. port IN: Base IO port. count IN: Number of IO ports.

Description: This function removes the access permission for count IO ports starting at port from task target. Any existing access permissions to IO ports are removed and kernel resources are freed if possible. On a successful return from this function, access permissions to the entire IO port range is removed, there is no partial removal.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if port and count exceeds the valid port range, or if count is zero, or if target is not a valid task number. P4_E_BADTASK if target is neither the callers task nor a child task of the callers task. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_NOTIMPL if the platform does not support IO ports.

Note: This system call is not supported on all platforms.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 189

1.15.6.9 p4_ioport_create

Create an IO port mapping in the callers or another task.

Synopsis:

P4_e_t p4_ioport_create(P4_task_t target, P4_uint32_t port, P4_uint32_t count)

Parameters: target IN: ID of the child task that shall receive the mapping. If target is P4_TASK_MYSELF, the callers address space will be modified. port IN: Base IO port. count IN: Number of IO ports.

Description: This function installs the access permission for count 8-bit IO ports starting at IO port port in the target task. IO port addresses are idempotent, i.e. they are not translated, so no source or destination addresses need to be passed.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if port and count exceeds the valid port range, or if count is zero, or if target is not a valid task number. P4_E_BADTASK if target is neither the callers task nor a child task of the callers task. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_MEM_CREATE enabled. P4_E_NOTIMPL if the platform does not support IO ports.

Note: This call is used internally by PikeOS and usually restricted to system software.

Note: This system call is not supported on all platforms.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

190 The PikeOS Kernel API

1.15.6.10 p4_mem_read

Copy data from another tasks virtual address space.

Synopsis:

P4_e_t p4_mem_read(P4_task_t task, void *dest, const void *source, P4_size_t length, P4_uint32_t flags)

Parameters: task IN: ID of the child task where the data shall be copied from. If task is P4_TASK_MYSELF, the callers address space will be used as source area. dest IN: Destination address in the callers address space. source IN: Address of source area in task tasks address space. length IN: Size of the source and destination memory area. flags IN: Set of bits used to affect the cache state of the destination memory area:

           • P4_ICACHE_COHERENCY
              Synchronize data and instruction caches to ensure coherent instruction caches.

        If not defined as mutually exclusive, several flag bits can be OR-ed together to form a set of flag bits.

Description: This function copies data from another tasks virtual address space to the callers one. The memory area described by source and length in the task denoted by task is copied to the memory area described by dest and length in the callers address space. Both source and destination areas must be valid user space regions. Each page in the source area must be mapped at least read-accessible, and each page in the destination area must be write-accessible. task must be a child task of the caller or the callers task itself. Overlapping source and destination areas in the same address space are not allowed. The flags argument is used to affect the cache state of the destination memory area after the copy operation.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if length is zero, or if source and length do not describe a valid memory area in the callers virtual address space, or if dest and length do not describe a valid memory area in task task virtual address space, or if task is the callers task and the source and destination areas overlap, or if task is not a valid task id, or if an invalid flag is set in flags. P4_E_BADTASK if task is not a child task of the callers task or the callers task itself. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_PAGEFAULT if the copy operation fails due to unmapped or otherwise inappropiate memory mappings.

                                 c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 191

Note: Depending on the hardware architecture, the copy operation may fail with P4_E_PAGEFAULT, if source and/or target memory areas are not mapped with caches enabled, and source and/or target memory addresses are unaligned and/or the size is not aligned to the CPUs native word size (32-bit or 64-bit).

                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

192 The PikeOS Kernel API

1.15.6.11 p4_mem_write

Copy data to another tasks virtual address space.

Synopsis:

P4_e_t p4_mem_write(P4_task_t task, void *dest, const void *source, P4_size_t length, P4_uint32_t flags)

Parameters: task IN: ID of the child task where the data shall be copied to. If task is P4_TASK_MYSELF, the callers address space will be used as destination area. dest IN: Destination address in task tasks address space. source IN: Address of source area in the callers address space. length IN: Size of the source and destination memory area. flags IN: Set of bits used to affect the cache state of the destination memory area:

           • P4_ICACHE_COHERENCY
              Synchronize data and instruction caches to ensure coherent instruction caches.

        If not defined as mutually exclusive, several flag bits can be OR-ed together to form a set of flag bits.

Description: This function copies data from the callers to another tasks virtual address space. The memory area described by source and length in the callers task is copied to the memory area described by dest and length in task tasks address space. Both source and destination areas must be valid user space regions. Each page in the source area must be mapped at least read-accessible, and each page in the destination area must be write-accessible. task must be a child task of the caller or the callers task itself. Overlapping source and destination areas in the same address space are not allowed. The flags argument is used to affect the cache state of the destination memory area after the copy operation.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if length is zero, or if source and length do not describe a valid memory area in task task virtual address space, or if dest and length do not describe a valid memory area in the callers virtual address space, or if task is the callers task and the source and destination areas overlap, or if task is not a valid task id, or if an invalid flag is set in flags. P4_E_BADTASK if task is not a child task of the callers task or the callers task itself. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_PAGEFAULT if the copy operation fails due to unmapped or otherwise inappropiate memory mappings.

                                 c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mapping API 193

Note: Depending on the hardware architecture, the copy operation may fail with P4_E_PAGEFAULT, if source and/or target memory areas are not mapped with caches enabled, and source and/or target memory addresses are unaligned and/or the size is not aligned to the CPUs native word size (32-bit or 64-bit).

                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

194 The PikeOS Kernel API

1.15.6.12 p4_mem_clear

Clear memory in another tasks virtual address space.

Synopsis:

P4_e_t p4_mem_clear(P4_task_t task, void *dest, P4_size_t length, P4_uint32_t flags)

Parameters: task IN: ID of the child task where the memory shall be cleared. If task is P4_TASK_MYSELF, the callers address space will be affected. dest IN: Target address in task tasks address space. length IN: Size of the target memory area. flags IN: Set of bits used to affect the cache state of the target memory area:

           • P4_ICACHE_COHERENCY
              Synchronize data and instruction caches to ensure coherent instruction caches.

        If not defined as mutually exclusive, several flag bits can be OR-ed together to form a set of flag bits.

Description: This function clears memory in another tasks virtual address space. The memory area described by dest and length in the task denoted by task is cleared (overwritten by zeros). The destination areas must be a valid user space region. Each page in the destination area must be write-accessible. task must be a child task of the caller or the callers task itself. The flags argument is used to affect the cache state of the target memory area after clearing the memory.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if length is zero, or if dest and length do not describe a valid memory area in task task virtual address space, or if task is not a valid task id, or if an invalid flag is set in flags. P4_E_BADTASK if task is not a child task of the callers task or the callers task itself. P4_E_STATE if target does not exist or is terminating (in P4_TASK_STATE_ZOMBIE state). P4_E_PAGEFAULT if the clear operation fails due to unmapped or otherwise inappropiate memory mappings.

Note: Depending on the hardware architecture, the clear operation may fail with P4_E_PAGEFAULT, if the target memory area is not mapped with caches enabled, and the target memory address is unaligned and/or the size is not aligned to the CPUs native word size (32-bit or 64-bit).

                                 c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 195

1.16 Thread API

The section describes constants, data types, access macros, and service calls related to the PikeOS thread management API.

1.16.1 Structure Definitions

1.16.1.1 struct P4_thread_attr_str

Thread attribute structure. The function p4_thread_get_attr() (see section 1.16.5.27) uses this structure to describe the attributes of a thread.

Synopsis:

struct P4_thread_attr_str { P4_uid_t uid; P4_uid_t shortexh; P4_uid_t fullexh; P4_uint32_t timepart; P4_uint32_t boost_tp; char name[P4_NAMELEN]; P4_thread_state_t state; P4_bool_t stopping; P4_bool_t overdue; P4_prio_t priority; P4_prio_t boost_prio; P4_uint32_t ev_ctr; P4_intid_t intid; P4_uid_t ipc_mask; P4_uid_t ev_mask; P4_cpuid_t cpuid; P4_uint32_t unused_padding; P4_cpumask_t affinity_mask; void * tls; P4_time_t deadline; P4_time_t overall_exec_time; };

Structure Element Description: uid Thread UID of the thread this structure describes. shortexh Thread UID of the short exception handler or P4_UID_INVALID if no handler is installed. fullexh Thread UID of the full exception handler or P4_UID_INVALID if no handler is installed. timepart Time partition number boost_tp Boosted time partition number name Thread name. The name is always a valid C string terminated with a NUL character. state Thread state. stopping Thread stopping flag. This field is TRUE if the thread has been stopped using p4_thread_stop_syscall() (see section 1.16.5.4) but has not yet reached the P4_THREAD_STOPPED state.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

196 The PikeOS Kernel API

overdue Overdue deadline flag. This field is TRUE if the thread has an overdue (expired) deadline and is pending process from its deadline handler. priority Thread priority. boost_prio Thread boost priority. ev_ctr Thread event counter value. intid Attached interrupt ID or P4_INT_DETACH if the thread has not attached to an interrupt. ipc_mask Thread IPC mask. ev_mask Thread event mask. cpuid Current assigned processor of the thread. unused_padding affinity_mask Thread processor affinity mask. tls Associated TLS area in user space, or NULL is no TLS was set. deadline Absolute deadline expiration time, the value P4_TIME_MAX indicates infinity. overall_exec_time Accumulated execution time of the thread since thread creation.

Associated Data Type

P4_thread_attr_t Thread attribute structure.

1.16.1.2 struct P4_thread_create_str

Thread create structure. The functions p4_task_start() (see section 1.17.5.3) and p4_thread_create() (see section 1.16.5.2) use this struc- ture to describe the attributes of a thread.

Synopsis:

struct P4_thread_create_str { const char * name; const P4_regs_t * context; P4_prio_t prio; P4_uint32_t tp_id; P4_uid_t shortexh; P4_uid_t fullexh; P4_uid_t ipc_mask; P4_uid_t ev_mask; };

Structure Element Description: name If name is not NULL, the kernel will copy P4_NAMELEN bytes starting at name as the threads name. If the string is longer than or equal to P4_NAMELEN characters, it will be truncated to P4_NAMELEN characters with a NUL character at the end. context context points to a data buffer containing the initial CPU context for the newly created thread. The context structure can be initialised in a platform-independent way using the library function p4_thread_arg() (see section 1.16.5.29).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 197

prio The priority with which the newly created thread shall start running. If the value of prio is higher than
     the MCP of the callers task, then the priority of the newly created thread is set to the MCP of the callers
     task. If prio is P4_PRIO_INHERIT, the newly created thread will inherit its priority from the calling thread.

      Note:
      If invalid priority values (prio >= P4_NUM_PRIO) or P4_PRIO_KEEP are passed in, thread tnum will
      have the tasks MCP assigned as its starting priority.

tp_id Number of the time partition in which the newly created thread shall start running. If tp_id is set to P4_TIMEPART_INHERIT, the newly created thread will execute in the time partition of the calling thread. If a value other than P4_TIMEPART_INHERIT or the callers time partition is specified, the callers task must have the ability P4_AB_TIMEPART_CHANGE enabled and tp_id must refer to a valid time partition. shortexh UID of the thread that should act as short exception handler for the newly created thread. If shortexh is P4_UID_INVALID, no short exception handler will be installed. In this case, an exception in the context of the newly created thread will invoke the threads full exception handler. If shortexh is P4_UID_INHERIT, the newly created thread inherits its short exception handler from the calling thread. If the thread cannot communicate with its short exception handler, the next exception handler in order (full exception handler) is used. fullexh UID of the thread that should act as full exception handler for the newly created thread. If fullexh is P4_UID_INVALID, no full exception handler will be installed. In this case, an exception in the context of the newly created thread will terminate the entire task. If fullexh is P4_UID_INHERIT, the newly created thread inherits its full exception handler from the calling thread. If the thread cannot communicate with its full exception handler, the next exception handler in order (last exception monitoring handler) is used. ipc_mask UID of the thread(s) allowed to send an IPC to the newly created thread. Wildcards may be used for resource partition, task, and thread information. If P4_UID_INVALID is specified, IPC reception will be disabled. ev_mask UID of the thread(s) allowed to send an event to the newly created thread. Wildcards may be used for resource partition, task, and thread information. If P4_UID_INVALID is specified, event reception will be disabled.

Associated Data Type

P4_thread_create_t Thread create structure.

1.16.2 Defines

P4_PRIO_INHERIT Inherit priority. Description:

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

198 The PikeOS Kernel API

    Special priority number to indicate that the priority should be inherited from the calling thread.

P4_PRIO_KEEP Keep priority. Description: Special priority number to indicate that the priority should not be altered.

P4_THREAD_CREATE_STOPPED Value definition for p4_thread_create()flags parameter. Description: Setting this value instructs p4_thread_create() (see section 1.16.5.2) to create the thread in the STOPPED state.

P4_THREAD_EXREGS_DEBUG Value definition for p4_thread_ex_regs()flags parameter. Description: Return the context of a thread in any case, even if the thread is blocked in the WAITING state, without cancelling the operation. The returned user mode context may be corrupted.

P4_THREAD_PREEMPT_UNBLOCK Value definition for p4_thread_preempt()flags parameter. Description: When preempting a target thread, unblock this thread when it is blocked in the kernel.

P4_THREAD_ARG_FPU Value definition for p4_thread_arg()flags parameter. Description: Setting this value instructs p4_thread_arg() (see section 1.16.5.29) to enable FPU usage in the user mode context. Setting this value instructs TLS-based handlers to enable the FPU with default settings for the invoked handler.

P4_THREAD_ARG_DEBUG Value definition for p4_thread_arg()flags parameter. Description: Setting this value instructs p4_thread_arg() (see section 1.16.5.29) to setup an initial stack frame for debugger usage in the user mode context and on the user mode stack.

P4_THREAD_ARG_VEC Value definition for p4_thread_arg()flags parameter. Description: Setting this value instructs p4_thread_arg() (see section 1.16.5.29) to enable vector unit usage in the user mode context. Setting this value instructs TLS-based handlers to enable the vector unit with default settings for the invoked handler.

P4_THREAD_ARG_DIRECT Value definition for p4_thread_arg()flags parameter. Description:

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 199

     Setting this value instructs p4_thread_arg() (see section 1.16.5.29) to setup a direct call in the user
     mode context. I.e. the function pointer is a direct entry point and doesnt contain the TOC.

P4_THREAD_SCHED_FIRST Value definition for p4_thread_ex_sched_syscall()flags parameter. Description: Setting this value instructs p4_thread_ex_sched_syscall() (see section 1.16.5.14) to enqueue a thread at the beginning of its ready queue, as first thread.

P4_THREAD_SCHED_LAST Value definition for p4_thread_ex_sched_syscall()flags parameter. Description: Setting this value instructs p4_thread_ex_sched_syscall() (see section 1.16.5.14) to enqueue a thread at the end of its ready queue, as last thread.

P4_THREAD_CANCEL_DEADLINE Value definition for p4_thread_stop_syscall()flags parameter. Description: Setting this value instructs p4_thread_stop_syscall() (see section 1.16.5.4) to stop the thread and cancel the deadline currently associated with it.

P4_THREAD_ARG_MAX_ARGS Maximum number of arguments that can be passed to the new thread in p4_thread_arg(). Description: The maximum number of arguments that can be passed to a new thread, otherwise p4_thread_arg() (see section 1.16.5.29) return P4_E_INVAL.

P4_THREAD_MYSELF Thread number identifying current thread. Description: Using this value as the thread number in thread API calls will select the current thread as the target thread for the call.

P4_CPU_MYSELF CPU number identifying current processor. Description: Using this value as the processor number in thread API calls will select the current processor of the calling thread as target processor.

P4_STACK (base, size) Initialize stack pointer by pointing to the stack area. Description: Use this macro to get a suitable stack pointer (e.g. for p4_thread_arg() (see section 1.16.5.29)) on all architectures.

     Note:
     The size argument is specified in bytes. The stack pointer will be properly aligned to fulfill ABI require-
     ments.


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

200 The PikeOS Kernel API

1.16.3 Data Type Definitions

P4_thread_attr_t Thread attribute structure. The function p4_thread_get_attr() (see section 1.16.5.27) uses this structure to describe the attributes of a thread. P4_thread_create_t Thread create structure. The functions p4_task_start() (see section 1.17.5.3) and p4_thread_create() (see section 1.16.5.2) use this structure to describe the attributes of a thread.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 201

1.16.4 Enumerations

Enumeration type P4_thread_state_t

Thread state definitions. This enumeration type is used in P4_thread_attr_t to describe a threads state.

Name Description P4_THREAD_READY Thread is ready to run, but is not the current thread.

P4_THREAD_CURRENT Thread is running as the current thread.

P4_THREAD_STOPPED Thread is stopped.

P4_THREAD_SLEEPING Thread is blocked in the kernel waiting for a timeout.

P4_THREAD_WAIT_RX Thread is blocked in an IPC receive operation.

P4_THREAD_WAIT_RX_EV Thread is blocked in an IPC receive and event wait operation.

P4_THREAD_WAIT_TX Thread is blocked in an IPC send operation.

P4_THREAD_WAIT_EV Thread is blocked in an event wait operation.

P4_THREAD_WAIT_INT Thread is blocked waiting for an interrupt to occur.

P4_THREAD_WAIT_IPC Thread is waiting on IPC transfer.

P4_THREAD_WAIT_GLOCK Thread is blocked on a Glock in KDEV drivers.

P4_THREAD_WAIT_ULOCK Thread is blocked waiting for a user space lock to become unlocked.

P4_THREAD_WAIT_START Thread is blocked waiting its release timeout.

P4_THREAD_WAIT_HM Thread is blocked waiting for HM deadline events.

P4_THREAD_WAIT_WAITQ Thread is blocked waiting on a user space wait queue.

P4_THREAD_WAIT_KERNEL Thread is blocked waiting for another thread to finish a kernel operation.

P4_THREAD_WAIT_DELETE Thread is blocked waiting for a thread to delete itself.

P4_THREAD_WAIT_TERMINATE Thread is blocked waiting for a task to terminate.

P4_THREAD_WAIT_EXREGS Thread is waiting for the exregs-ed thread to become available.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

202 The PikeOS Kernel API

1.16.5 Functions

1.16.5.1 p4_thread_create_syscall

Create a new thread in the callers task with using a TLS (thread local storage) area.

Synopsis:

P4_e_t p4_thread_create_syscall(P4_thr_t tnum, const P4_thread_create_t *tc, P4_uint32_t flags, void *tls)

Parameters: tnum IN: tnum designates the number of the thread to be created. The parameter tnum must be a valid thread number for the configured task limits and must not refer to an already active thread. tc IN: tc describes the attributes of the thread to be created. The parameter tc must be fully mapped in the callers address space and all values must be initialized properly. flags IN: Set of bits used to further control thread creation. Currently, the following flag bit is defined:

              • P4_THREAD_CREATE_STOPPED
                 Create the thread in the STOPPED state.

           If not defined as mutually exclusive, several flag bits can be OR-ed together to form a set of flag bits.
           If flags is zero, the following default applies: The thread is created in READY state.
     tls IN: Memory area for thread local storage, assumed to be of type P4_tls_area_t.

Description: This function creates a new thread specified by the thread number tnum in the task of the caller. The structure tc describes the default attributes for the to be created thread. Upon successful completion, thread tnum is initialised with the CPU register settings given by tc->context. Thread tnums exception handlers are set to the threads identified by tc->shortexh and tc->fullexh. The priority of the thread is set to the minimum of tc->prio and the MCP of the callers task. The thread will eventually be scheduled in the time partition given by tc->tp_id. The thread will have its IPC and event mask initialized with the values provided in tc->ipc_mask and tc->ev_mask. The new threads affinity mask is inherited from the caller and the new thread is assigned to the processor represented by the lowest set bit in its affinity mask. Parameter flags is a set of bits used to further control thread creation. Setting P4_THREAD_CREATE_STOPPED will put the thread in STOPPED state instead of READY state after creation. The new threads registered thread local storage area is set to tls. If tls is not NULL, this call overrides any value previously defined in the user mode context referring to the thread local storage area set by p4_thread_tls_register() (see section 1.20.3.1), and the kernel initializes the following fields of the thread local storage area, assuming a P4_tls_area_t type:

  • uid,


                                 c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 203

• uprio,
• kprio, and
• cpuid.

Note: The initial function of the created thread as specified in tc->context must not return, nor must it expect a valid return address. Instead, the newly created thread must delete its own thread explicitly by calling p4_thread_delete() (see section 1.16.5.3) or by terminating its task by calling p4_task_terminate() (see section 1.17.5.4).

Note: Refer to PikeOS User Manual (Initialization of Thread Local Storage) for additional information about the initializa- tion and extension of the TLS area.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_INVAL tp_id is not a valid time partition number. P4_E_INVAL if tc or tc->context are NULL. P4_E_INVAL tc, tc->context, or tc->name do not point to a valid address or exceed the callers virtual address space. P4_E_INVAL if tls does not point to a valid address or exceeds the callers virtual address space. P4_E_INVAL if an invalid flag is set in flags. P4_E_STATE tnum refers to an already active thread. P4_E_NOKMEM There is not enough kernel memory available in the resource partition of the callers task to create the thread. P4_E_ALIGN if tls is not properly aligned. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel does not point to a valid address in the callers virtual address space. P4_E_NOABILITY The caller is attempting to assign the newly created thread to a time partition different from that of the caller and the caller does not have the ability P4_AB_TIMEPART_CHANGE enabled.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

204 The PikeOS Kernel API

1.16.5.2 p4_thread_create

Create a new thread in the callers task without using a TLS (thread local storage) area.

Synopsis:

__forceinline P4_e_t p4_thread_create(P4_thr_t tnum, const P4_thread_create_t *tc, P4_uint32_t flags)

Parameters: tnum IN: tnum designates the number of the thread to be created. The parameter tnum must be a valid thread number for the configured task limits and must not refer to an already active thread. tc IN: tc describes the attributes of the thread to be created. The parameter tc must be fully mapped in the callers address space and all values must be initialized properly. flags IN: Set of bits used to further control thread creation. Currently, the following flag bit is defined:

           • P4_THREAD_CREATE_STOPPED
             Create the thread in the STOPPED state.

       If not defined as mutually exclusive, several flag bits can be OR-ed together to form a set of flag bits.
       If flags is zero, the following default applies: The thread is created in READY state.

Description: This function creates a new thread specified by the thread number tnum in the task of the caller. The structure tc describes the default attributes for the to be created thread. Upon successful completion, thread tnum is initialised with the CPU register settings given by tc->context. Thread tnums exception handlers are set to the threads identified by tc->shortexh and tc->fullexh. The priority of the thread is set to the minimum of tc->prio and the MCP of the callers task. The thread will eventually be scheduled in the time partition given by tc->tp_id. The thread will have its IPC and event mask initialized with the values provided in tc->ipc_mask and tc->ev_mask. The new threads affinity mask is inherited from the caller and the new thread is assigned to the processor represented by the lowest set bit in its affinity mask. Parameter flags is a set of bits used to further control thread creation. Setting P4_THREAD_CREATE_STOPPED will put the thread in STOPPED state instead of READY state after creation. The new threads registered thread local storage area is set to NULL, effectively disabling the kernel to access variables in thread local storage, regardless of a thread local storage area set with p4_thread_tls_register() (see section 1.20.3.1).

Note: The initial function of the created thread as specified in tc->context must not return, nor must it expect a valid return address. Instead, the newly created thread must delete its own thread explicitly by calling p4_thread_delete() (see section 1.16.5.3) or by terminating its task by calling p4_task_terminate() (see section 1.17.5.4).

Note:

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 205

To register a thread local storage area, the new thread must call p4_tls_register() (see section 1.20.3.2).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_INVAL tp_id is not a valid time partition number. P4_E_INVAL if tc or tc->context are NULL. P4_E_INVAL tc, tc->context, or tc->name do not point to a valid address or exceed the callers virtual address space. P4_E_INVAL if an invalid flag is set in flags. P4_E_STATE tnum refers to an already active thread. P4_E_NOKMEM There is not enough kernel memory available in the resource partition of the callers task to create the thread. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel does not point to a valid address in the callers virtual address space. P4_E_NOABILITY The caller is attempting to assign the newly created thread to a time partition different from that of the caller and the caller does not have the ability P4_AB_TIMEPART_CHANGE enabled.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

206 The PikeOS Kernel API

1.16.5.3 p4_thread_delete

Delete an active thread.

Synopsis:

P4_e_t p4_thread_delete(P4_thr_t tnum)

Parameters: tnum IN: Number of the thread to be deleted. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread.

Description: This function deletes the thread specified by the thread number tnum in the task of the caller. If the thread tnum is in a WAITING state, the waiting state will be canceled. Upon successful completion, the thread tnum is no longer eligible for scheduling. All kernel resources required to manage the thread will be returned to the kernel memory pool in the callers task resource partition. If a thread deletes itself, the function does not return. If a thread deletes itself and it was the only thread in the task, the tasks state will be set to P4_TASK_ACTIVATED. While terminating, the calling thread forces the to-be-deleted thread to complete any outstanding kernel opera- tions. During this transient phase, the calling thread donates its priority and time partition to the to-be-deleted thread, and resumes its execution as long as tnum is fully deleted. If the to-be-deleted thread already executes in timepartition 0, it is not migrated to the callers time partition.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum does not refer to an active thread. P4_E_STATE tnum refers to a thread already being deleted by another thread. P4_E_CANCEL if the function was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU.

Note: On error code P4_E_CANCEL, the to-be-deleted thread remains in deletion with the donated scheduling priority and time partition.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 207

1.16.5.4 p4_thread_stop_syscall

Stop a thread, extended version.

Synopsis:

P4_e_t p4_thread_stop_syscall(P4_thr_t tnum, P4_uint32_t flags)

Parameters: tnum IN: Number of the thread to be stopped. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. flags IN: Set of bits used to further control thread stopping. Currently, the following flag bit is defined (addi- tional possibly set bits are ignored):

           • P4_THREAD_CANCEL_DEADLINE
             Possibly associated deadlines are removed from the thread on stop.

       If flags is zero, the following default applies: The threads current deadline is preserved.

Description: This function puts the target thread tnum in the STOPPED state. The thread will no longer be eligible for scheduling, until the time the thread is resumed using p4_thread_resume() (see section 1.16.5.6). Its current execution state (context, IPC/ULOCK waiting, deadline) is retained depending on the value of the flags parameter. Parameter flags is a set of bits used to further control thread stopping. Setting P4_THREAD_CANCEL_DEADLINE will cancel the deadline value associated with the thread tnum to be stopped. If flags is zero, the deadline parameter is preserved.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_INVAL if an invalid flag is set in flags. P4_E_STATE tnum does not refer to an active thread. P4_E_STATE tnum refers to an already stopped thread, or to a thread that has already been requested to stop but has not yet reached the stopped state.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

208 The PikeOS Kernel API

1.16.5.5 p4_thread_stop

Stop a thread.

Synopsis:

__forceinline P4_e_t p4_thread_stop(P4_thr_t tnum)

Parameters: tnum IN: Number of the thread to be stopped

Description: This function puts the target thread tnum in the STOPPED state. The thread will no longer be eligible for scheduling, but its current execution state (context, IPC/ULOCK waiting, deadline) is retained until the time the thread is resumed using p4_thread_resume() (see section 1.16.5.6).

Note: This function calls p4_thread_stop_syscall() (see section 1.16.5.4) internally, with the flags argument set to 0. See p4_thread_stop_syscall() (see section 1.16.5.4) for a description of the functions behavior.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 209

1.16.5.6 p4_thread_resume

Resume a stopped thread.

Synopsis:

P4_e_t p4_thread_resume(P4_thr_t tnum)

Parameters: tnum IN: Number of the thread to be resumed. The parameter tnum must be a valid thread number for the configured task limits and must refer to an active thread that has been stopped or has been requested to stop.

Description: This function resumes thread tnum which was previously stopped by a call to p4_thread_stop() (see section 1.16.5.5). Upon return from this function, thread tnum will again be eligible for scheduling.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum refers to an inactive thread. P4_E_STATE tnum does not refer to a stopped thread or does not refer to a thread that has been requested to stop.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

210 The PikeOS Kernel API

1.16.5.7 p4_thread_alarm

Manipulate current threads release and deadline-expiration times.

Synopsis:

P4_e_t p4_thread_alarm(P4_time_t release, P4_time_t deadline, P4_prio_t new_prio)

Parameters: release IN: release specifies the time the calling thread will be blocked in the kernel before being release as READY. Use P4_TIME_MIN for immediate release (without rescheduling). Use release <= NOW for immediate release with rescheduling. deadline IN: deadline specifies the expiration time of the alarm (deadline) associated with the calling thread. Use P4_TIME_MAX to set no deadline. new_prio IN: new_prio specifies the priority that the thread should have after being released, or being woken up as a consequence of the call of this function. If new_prio is set to P4_PRIO_INHERIT or to P4_PRIO_KEEP, the target threads priority remains unchanged. The new priority will be limited to the current tasks MCP.

Description: A successful call to this function setup an "alarm" (deadline) for the calling thread. If not P4_TIME_MAX, the alarm (deadline) is set to expire at time deadline. If release is not P4_TIME_MIN, the thread is suspended until the release time is reached. At release time, the thread becomes eligible for execution (threads that become runnable are placed at the end of their priority queue). Specifying a release time in the past makes the thread immediately eligible for execution. The release time must be before the deadline expiry time. new_prio specifies the priority that the thread should have after being released, or being woken up as a con- sequence of the call of this function. new_prio is enforced right before blocking the thread for later release, or immediately before the release (if immediate release is specified). The new priority will be limited to the current tasks MCP. A health-monitoring exception is triggered when the deadline time is reached. In this case, the action de- pends on the configuration in the health-monitoring tables for a userspace manageable hm-event of type P4_HM_TYPE_TRAP with id P4_TRAP_DEADLINE. If the action can be managed by a user-space handler, and a user-space handler was configured for the task of the calling thread, via a call to p4_task_hm_register() (see section 1.17.5.6), then, upon alarm expiration the deadline is marked as expired. When the registered handler enters with the kernel via the p4_task_hm_wait() (see section 1.17.5.7) syscall, then the UID of the thread with the oldest expired deadline is returned to the p4_task_hm_wait() (see section 1.17.5.7). An alarm is only valid on the CPU where the current thread requesting the alarm is running. If an alarm is set for a thread, it is not possible to migrate the thread to a different CPU (this has to be done before invoking this function). If a thread is eligible for execution on multiple CPUs (i.e., its CPU affinity mask contains more than one CPU), an error will be returned by this function.

Returns:

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 211

Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_CANCEL if the sleep was canceled while waiting for release time, or the calling thread was moved to another time partition. The deadline is not set in this case. P4_E_STATE The calling thread is preempted or subject to exception. P4_E_STATE A deadline is already pending for the calling thread. P4_E_STATE The calling thread is eligible to run on multiple CPUs (its CPU affinity mask does not contain only one CPU) or is being migrated to another CPU. P4_E_INVAL release is P4_TIME_MAX. P4_E_INVAL deadline is before release.

Note: An alarm is canceled when a thread is stopped via p4_thread_stop_syscall() (see section 1.16.5.4) with flag P4_THREAD_CANCEL_DEADLINE. The deadline is preserved when a thread is stopped via p4_thread_stop() (see section 1.16.5.5).

Note: deadline and release are 64 bit wide P4_time_t values, which specify an absolute time in nanoseconds.

Note: If P4_E_CANCEL is returned, any deadline possibly associated with thr is canceled.

Note: The current execution state of a thread when the alarm expires is not modified. If the calling thread is READY when the deadline expires, a deadline handler should have a strictly higher priority than the thread to detect the deadline notification event before the thread is resumed.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

212 The PikeOS Kernel API

1.16.5.8 p4_thread_ex_regs

Manipulate user mode context of a thread.

Synopsis:

P4_e_t p4_thread_ex_regs(P4_thr_t tnum, P4_regs_t *old_context, P4_prio_t *old_prio, const P4_regs_t *new_context, P4_prio_t new_prio, P4_uint32_t flags)

Parameters: tnum IN: Number of the thread whose context shall be manipulated. The parameter tnum must be a valid thread number for the configured task limits and must refer to an active thread. The callers thread number or P4_THREAD_MYSELF cannot be used as target thread. old_context OUT: Upon successful return of this function, old_context, if non-NULL, will contain the user mode context of tnum in effect before this function was called. old_prio OUT: Upon successful return of this function, old_prio, if non-NULL, will contain the priority of tnum in effect before this function was called. new_context IN: If non-NULL, new user mode context for tnum, which will come into effect when tnum continues execution. new_prio IN: New priority for tnum, which will come into effect when tnum continues execution. If new_prio is set to P4_PRIO_INHERIT, the target threads priority is set to the calling threads priority. If new_prio is set to P4_PRIO_KEEP, the target threads priority remains unchanged. The new priority will be limited to the current tasks MCP. The threads priority is only changed when a new context was successfully set. If new_context is NULL, new_prio is ignored. flags IN: Set of bits used to further control the context change operation. Currently, the following flag bits are defined:

           • P4_THREAD_EXREGS_DEBUG
             If the target thread is blocked in the WAITING state, do not cancel the operation at all and save the
             state in old_context (if non-NULL). However, the state reflects the thread somewhere in a system
             call and may be corrupted. Setting a new context is prohibited. Changes to the target threads
             priority are ignored.

       If not defined as mutually exclusive, several flag bits can be OR-ed together to form a set of flag bits.
       If flags is zero, the following defaults apply: the thread will be unblocked if it is blocked in the WAITING
       state, and the context will be returned when all kernel operations have finished.

Description: Deprecated interface for the manipulation of a user mode context. Please use p4_thread_preempt() (see section 1.16.5.12) and p4_thread_set_regs() (see section 1.16.5.10) instead. This function is used to unblock thread tnum, wait for the target thread to finish all ongoing operations and access the user mode context of the thread at a consistent state. This function will perform the action defined by the flags parameter:

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 213

If flags is zero, this function will cancel pending operations and push the target thread out of a WAITING state. If flags has P4_THREAD_EXREGS_DEBUG set, the threads user mode context shall be retrieved immediately for debug purposes, regardless of any ongoing operation. The target threads state is not altered in this case and the target threads user mode context may be in an inconsistent state, because the thread is still running in the kernel. After cancellation of blocking operations of the target thread, p4_thread_ex_regs() (see section 1.16.5.8) waits for any ongoing operation of the target thread to finish, before both user mode context and priority of the target thread can be exchanged: In case old_context and new_context are both NULL, p4_thread_ex_regs() (see section 1.16.5.8) shall unblock thread tnum and return immediately. If old_context is not NULL, the current context (prior to execution of this function) will be stored in the location pointed to by old_context. If not NULL, the priority before switching the register context is stored in old_prio. If new_context is not NULL, the context pointed to by new_context will be used as the new context for thread tnum. After successfully setting a new context by new_context, the priority of the thread will be set to new_prio. In case new_context is NULL, new_prio is ignored and the threads priority isnt changed. In case P4_THREAD_EXREGS_DEBUG is set in flags, new_context must be NULL and new_prio is ignored. The calling threads user mode context cannot be read or written by this call. On error codes other than P4_E_OK, the priority of tnum remains unchanged and the priority returned in old_prio is undefined. On error codes P4_E_INVAL or P4_E_PAGEFAULT and new_context not being NULL, the current user mode context of tnum may be corrupted. In this case an exception with a trap code of P4_TRAP_CTXT is raised.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_INVAL new_context is non-NULL and P4_THREAD_EXREGS_DEBUG is set in flags. P4_E_INVAL new_context, old_context, or old_prio does not point to a valid address or exceed the callers virtual address space. P4_E_INVAL if an invalid flag is set in flags. P4_E_STATE tnum does not refer to an active thread. P4_E_STATE Another p4_thread_ex_regs() (see section 1.16.5.8) call is already in progress affecting the target thread. P4_E_STATE Either old_context or new_context is not NULL and the target thread is not in the same time partition (and CPU) as the caller. P4_E_STATE The target thread is the calling thread itself. P4_E_CANCEL The target thread was deleted before the operation finished. P4_E_CANCEL The operation was canceled by another thread. P4_E_PAGEFAULT new_context, old_context, or old_prio is not NULL and is not fully mapped in the callers virtual address space.

Note: Changing the register(s) pointing to the TLS (thread local storage) area in new_context does not update the kernel internally registered address of the TLS area. Use p4_tls_register() (see section 1.20.3.2) for this.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

214 The PikeOS Kernel API

Note: Changing the registers of a thread also impacts its scheduling. After changing registers, the target thread is enqueued at the end of its priorities ready queue.

Note: Internally in the kernel, the calling thread applies a priority boost on the target thread to finish any ongoing operations in the kernel before the threads register context can be safely exchanged. The target thread will execute any ongoing kernel activity with the maximum scheduling priority of both its own and the callers priority. If the caller thread run in time partition 0, the target thread will also execute in time partition 0.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 215

1.16.5.9 p4_thread_get_regs

Retrieve user mode context of a thread in the current task.

Synopsis:

P4_e_t p4_thread_get_regs(P4_thr_t tnum, P4_regs_t *context, P4_prio_t *prio)

Parameters: tnum IN: Number of the thread whose context shall be retrieved. The parameter tnum must be a valid thread number for the configured task limits and must refer to an active thread. The callers thread number or P4_THREAD_MYSELF cannot be used as target thread. context OUT: Upon successful return of this function, context, if non-NULL, will contain the user mode context of tnum in effect before this function was called. prio OUT: Upon successful return of this function, prio, if non-NULL, will contain the priority of tnum in effect before this function was called.

Description: This function retrieves the user mode context and priority for thread tnum (in the current task) and stores them in the location pointed to by context and prio respectively (if non NULL). The returned user mode context reflects the state of the thread running either in user or in kernel mode and may be corrupted. Its purpose is for diagnostic use only. The target thread is not unblocked or otherwise modified. The calling threads user mode context cannot be read by this call.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_INVAL context or prio does not point to a valid address or exceeds the callers virtual address space. P4_E_STATE tnum does not refer to an active thread. P4_E_STATE The target thread is the calling thread itself. P4_E_PAGEFAULT context or prio is not NULL and is not fully mapped in the callers virtual address space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

216 The PikeOS Kernel API

1.16.5.10 p4_thread_set_regs

Manipulate user mode context of current thread.

Synopsis:

P4_e_t p4_thread_set_regs(const P4_regs_t *new_context, P4_prio_t new_prio)

Parameters: new_context IN: New user mode context for current thread. If new_context is NULL, the calling threads user mode context remains unchanged. new_prio IN: New priority for current thread. If new_prio is set to P4_PRIO_KEEP or P4_PRIO_INHERIT, the calling threads priority remains unchanged.

Description: This function is used to replace the user mode context of the current thread with the context pointed to by new_context. The thread also changes the priority to new_prio. Additionally, a currently executing preemption or exception handler operation is completed. For a nested exception during the execution of a preemption handler, only the exception is completed.

Returns: Upon success, this function does not return, otherwise one of the following error codes is returned to the caller: P4_E_INVAL new_context does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT new_context is not NULL and not fully mapped in the callers virtual address space. This error causes an exception.

Note: Regardless of a reported error code, a currently executing preemption or exception handler operation is always completed. To complete the preemption or exception handler operation without setting a new user mode context but a priority change only, call p4_thread_set_regs() (see section 1.16.5.10) with new_context set to NULL and new_prio set to the new scheduling priority or P4_PRIO_KEEP.

Note: The kernel always loads the integer part of new_context, but may skip loading any FPU or vector registers if the new register state indicates that the FPU or the vector unit are unused.

Note: If a page fault occurs when accessing new_context, the register context of the calling thread is in an undefied state, which also affects the error code. In this case, this function will raise an exception of type P4_TRAP_CTXT. Depending on the action taken by the exception handlers, p4_thread_set_regs() (see section 1.16.5.10) may never return.

Note: Changing the register(s) pointing to the TLS (thread local storage) area in new_context does not update the kernel internally registered address of the TLS area. Use p4_tls_register() (see section 1.20.3.2) for this.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 217

1.16.5.11 p4_thread_unblock

Unblock a thread from its in-kernel pending operations.

Synopsis:

__forceinline P4_e_t p4_thread_unblock(P4_thr_t tnum, P4_uint32_t flags)

Parameters: tnum IN: Number of the thread to unblock. The parameter tnum must be a valid thread number for the configured task limits and must refer to an active thread. The callers thread number or P4_THREAD_MYSELF cannot be used as target thread. flags IN: flags. Reserved for future use and must be set to 0.

Description: The function cancel blocking operations for the target thread and returns immediately.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_INVAL flags is not 0. P4_E_STATE tnum does not refer to an active thread. P4_E_STATE The target thread is the calling thread itself.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

218 The PikeOS Kernel API

1.16.5.12 p4_thread_preempt

Preempt a thread.

Synopsis:

P4_e_t p4_thread_preempt(P4_thr_t tnum, P4_prio_t threshold, P4_uint32_t flags)

Parameters: tnum IN: Number of the thread to be preempted. The parameter tnum must be a valid thread number for the configured task limits and must refer to an active thread. threshold IN: Priority level at which the thread shall be preempted. If the thread currently runs at or drops below the threshold priority, it will be preempted and its preemp- tion handler will be activated, otherwise the preemption request will be queued. Set to the highest pos- sible priority (e.g., tasks MCP, or P4_NUM_PRIO) for immediate preemption. Use of P4_PRIO_KEEP and P4_PRIO_INHERIT cause immediate preemption. flags IN: Set of bits used to further control the preemption operation. Currently, the following flag bit is defined:

           • P4_THREAD_PREEMPT_UNBLOCK
              Unblock thread if it is waiting in the kernel.

        If not defined as mutually exclusive, several flag bits can be OR-ed together to form a set of flag bits.
        If flags is zero, the following default applies:

           • the thread remains blocking in the kernel

Description: This function is used to preempt the thread tnum.

  • If the target thread tnum is currently executing in SYSEMU state, a call to this function let the target
    thread leave SYSEMU state. In this case, the registers are saved in P4_tls_area_t::sysemu_regs (see
    section 1.20.1.1), and the SYSEMU return handler P4_tls_area_t::sysemu_handler (see section 1.20.1.1)
    is invoked on its configured stack rather than the preemption handler. The threshold priority is ignored in
    this case.
  • Otherwise, if the target thread tnum does not currently run in SYSEMU state, this function preempts
    the target as follows: if tnum currently runs at or drops below the given threshold priority threshold,
    the target thread finishes all ongoing kernel operations, saves its own user mode context at the register
    save area defined in the target threads thread local storage area P4_tls_area_t::preempt_regs (see sec-
    tion 1.20.1.1), then rises its own priority to the threads task MCP, and invokes the preemption handler
    P4_tls_area_t::preempt_handler (see section 1.20.1.1), on the new stack P4_tls_area_t::preempt_stack
    (see section 1.20.1.1) in user mode.
    A pointer to the register context and the previous scheduling priority are passed as arguments to the invoked
    preemption handler.


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 219

    The call to this function returns immediately and the preemption operation is performed asynchronously
    when thread tnum is scheduled regularly next time (based on its current scheduling priority) and the
    preemption condition is met.

• If P4_tls_area_t::preempt_stack (see section 1.20.1.1) is NULL, the threads current stack is used instead of P4_tls_area_t::preempt_stack (see section 1.20.1.1) as new stack. • If P4_tls_area_t::preempt_regs (see section 1.20.1.1) is NULL, the threads registers are saved on the new stack. • If P4_THREAD_PREEMPT_UNBLOCK is set in flags, the target thread is unblocked if it is waiting in the kernel. • If a thread is already being preempted by another thread, but has not yet invoked its handler, this function succeeds and updates a previously set threshold priority to the new value, if higher. On error codes other than P4_E_OK, the priority of tnum remains unchanged and tnum is not preempted.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_INVAL if an invalid flag is set in flags. P4_E_STATE tnum does not refer to an active thread.

Note: If another p4_thread_preempt() (see section 1.16.5.12) call is already in progress affecting the target thread, the target threads threshold priority will be updated to the higher of the provided values for threshold. Setting P4_THREAD_PREEMPT_UNBLOCK more than once has no effect. The kernel will unblock the target thread on the first time the flag P4_THREAD_PREEMPT_UNBLOCK is set in flags.

Note: To prevent unbounded preemptions, the kernel queues further preemption requests while a thread is executing its preemption handler and records the last provided value for threshold. The preemption handler must complete its operation by a call to p4_thread_set_regs() (see section 1.16.5.10) before new preemption requests can be served.

Note: Preemption requests do not impact scheduling of threads. A pending preemption request will only be handled at the time a thread is scheduled according to the threads original scheduling order and the thread becomes the currently running thread on its processor. Then, after the conditions to preempt the thread are fulfilled, the thread rises its own priority when entering the preemption handler. Finally, the call to p4_thread_set_regs() (see section 1.16.5.10) restores the threads original pposition in the ready queue again.

Note: If a page fault occurs when accessing regs, the register context of thread tnum remains unchanged. In this case, thread tnum continue normal execution.

Note: A preemption handler function must not return, but rather complete its execution by restoring the previous user mode context and priority with a call to p4_thread_set_regs() (see section 1.16.5.10): void handler(P4_regs_t *regs, P4_prio_t oldprio)

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

220 The PikeOS Kernel API

{ ... p4_thread_set_regs(regs, oldprio); }

During execution of the preemption handler, critical system registers are set to default values and the thread local storage area is set to the target threads previously registered thread local storage area. See P4_tls_area_t::preempt_flags (see section 1.20.1.1) how to further control the execution state of the preemp- tion handler.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 221

1.16.5.13 p4_thread_except

Force a thread into exception handling.

Synopsis:

P4_e_t p4_thread_except(P4_thr_t tnum)

Parameters: tnum IN: Number of the thread to be forced into an exception. The parameter tnum must be a valid thread number for the configured task limits and must refer to an active thread.

Description: A call to this function signals the destination thread specified by tnum in the callers task to throw an exception when it is scheduled and leaves the kernel. Ongoing kernel activities are not affected. Multiple signaling on the same destination thread has no effect as long as the thread is not scheduled. The request to throw an exception is cleared before the destination thread enters exception handling. To prevent unbounded nesting of exceptions when using TLS-based exception handling, any exception request received while a thread is currently executing its TLS-based exception handler escalates the exception to the next higher error level, as defined in the corresponding health-monitoring tables.

Returns: Upon success, this function returns P4_E_OK, otherwise the following error code is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum does not refer to an active thread.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

222 The PikeOS Kernel API

1.16.5.14 p4_thread_ex_sched_syscall

Exchange thread priority and time partition, extended version.

Synopsis:

P4_e_t p4_thread_ex_sched_syscall(P4_thr_t tnum, P4_prio_t *old_prio, P4_uint32_t *old_tp, P4_prio_t new_prio, P4_uint32_t new_tp, P4_uint32_t flags)

Parameters: tnum IN: Number of the thread whose priority shall be retrieved and/or updated. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. old_prio OUT: Pointer to location where the target threads current priority (before the update) will be stored, if not NULL. old_tp OUT: Pointer to location where the target threads current time partition (before the update) will be stored, if not NULL. new_prio IN: New priority to be assigned to target thread. If new_prio is set to P4_PRIO_INHERIT, the target threads priority will be set to the calling threads priority. If new_prio is set to P4_PRIO_KEEP, the threads priority remains unchanged.

        Note:
        If an invalid priority value (new_prio >= P4_NUM_PRIO) is passed in, thread tnum will have the tasks
        MCP assigned as its new priority.

new_tp IN: New time partition to be assigned to target thread. If new_tp is set to P4_TIMEPART_INHERIT, the target threads time partition will be set to the calling threads time partition. If new_tp is set to P4_TIMEPART_KEEP, the threads time partition remains unchanged.

        Note:
        To change a threads time partition                 the   callers     task   needs   to   have   the   ability
        P4_AB_TIMEPART_CHANGE enabled.

flags IN: Set of bits used to further control the operation. Currently, the following flag bits are defined:

           • P4_THREAD_SCHED_FIRST
             If set, the thread will be enqueued at the beginning of its ready queue. This flag is mutually
             exclusive with P4_THREAD_SCHED_LAST.
           • P4_THREAD_SCHED_LAST
                If set, the thread will be enqueued at the end of its ready queue. This flag is mutually exclusive
                with P4_THREAD_SCHED_FIRST.

        If neither of the above flags is set, the following default applies:

           • A currently running thread is enqueued at the beginning of its ready queue.
           • A ready thread is enqueued as the end of its ready queue.


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 223

Description: This function returns the current priority and time partition of thread tnum in the location pointed to by old_prio and old_tp (if non-NULL) and sets the new priority of tnum to new_prio (if not P4_PRIO_KEEP) and the new time partition to new_tp (if not P4_TIMEPART_KEEP). If new_prio is higher than the callers task MCP, then thread tnum will be assigned the MCP as its new priority value. On a time partition change, the target thread will be unblocked with error code P4_E_CANCEL when it is currently blocked in the kernel. If both old_prio and old_tp are NULL and new_prio is set to P4_PRIO_KEEP and new_tp is set to P4_TIMEPART_KEEP, the only action of this function will be to validate tnum. On error codes other than P4_E_OK, thread attributes remain unchanged.

Note: If tnum refers to a thread currently running on another processor, the priority returned in old_prio reflects a transient snapshot of the current kernel priority, not the threads current user priority. The current user priority may be higher. Therefore it is not recommended to change the priority of threads currently running on other processors.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL both P4_THREAD_SCHED_FIRST and P4_THREAD_SCHED_LAST are set in flags, or tnum is not a valid thread number, or new_tp does not refer to a valid time partition, or if an invalid flag is set in flags. P4_E_STATE tnum does not refer to an active thread. P4_E_INVAL old_prio or old_tp are not NULL and do not point to a valid address or exceed the callers virtual address space. P4_E_PAGEFAULT old_prio or old_tp are not NULL and are not fully mapped in the callers virtual address space. P4_E_NOABILITY new_tp is not P4_TIMEPART_KEEP or P4_TIMEPART_INHERIT and the callers task does not have the ability P4_AB_TIMEPART_CHANGE enabled.

                                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

224 The PikeOS Kernel API

1.16.5.15 p4_thread_ex_sched

Exchange thread priority and time partition.

Synopsis:

__forceinline P4_e_t p4_thread_ex_sched(P4_thr_t tnum, P4_prio_t *old_prio, P4_uint32_t *old_tp, P4_prio_t new_prio, P4_uint32_t new_tp)

Parameters: tnum IN: Number of the thread whose priority shall be retrieved and/or updated. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. old_prio OUT: Pointer to location where the target threads current priority (before the update) will be stored, if not NULL. old_tp OUT: Pointer to location where the target threads current time partition (before the update) will be stored, if not NULL. new_prio IN: New priority to be assigned to target thread. If new_prio is set to P4_PRIO_INHERIT, the target threads priority will be set to the calling threads priority. If new_prio is set to P4_PRIO_KEEP, the threads priority remains unchanged.

        Note:
        If an invalid priority value (new_prio >= P4_NUM_PRIO) is passed in, thread tnum will have the tasks
        MCP assigned as its new priority.

new_tp IN: New time partition to be assigned to target thread. If new_tp is set to P4_TIMEPART_INHERIT, the target threads time partition will be set to the calling threads time partition. If new_tp is set to P4_TIMEPART_KEEP, the threads time partition remains unchanged.

        Note:
        To change a threads time partition               the   callers   task    needs   to   have   the   ability
        P4_AB_TIMEPART_CHANGE enabled.

Description: This function returns the current priority and time partition of thread tnum in the location pointed to by old_prio and old_tp and sets the new priority of tnum to new_prio and the new time partition to new_tp.

Note: This function calls p4_thread_ex_sched_syscall() (see section 1.16.5.14) internally, with the flags argument set to 0. See p4_thread_ex_sched_syscall() (see section 1.16.5.14) for a description of the functions behavior.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 225

1.16.5.16 p4_thread_get_sched

Retrieve thread priority and time partition.

Synopsis:

__forceinline P4_e_t p4_thread_get_sched(P4_thr_t tnum, P4_prio_t *prio, P4_uint32_t *tp)

Parameters: tnum IN: Number of the thread whose priority shall be retrieved. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. prio OUT: Pointer to location where the target threads priority will be stored. If prio is NULL, the priority will not be retrieved. tp OUT: Pointer to location where the target threads time partition will be stored. If tp is NULL, the time partition will not be retrieved.

Description: This function returns the current priority of thread tnum in the location pointed to by prio and the current time partition of thread tnum in the location pointed to by tp. This function is a convenience function implemented using p4_thread_ex_sched_syscall() (see section 1.16.5.14).

Note: If tnum refers to a thread currently running on another processor, the priority returned in prio reflects a transient snapshot of the current kernel priority, not the threads current user priority. The current user priority may be higher.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum does not refer to an active thread. P4_E_INVAL prio or tp are not NULL and do not point to a valid address or exceed the callers virtual address space. P4_E_PAGEFAULT prio or tp are not NULL and are not fully mapped in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

226 The PikeOS Kernel API

1.16.5.17 p4_thread_set_sched

Set thread priority and time partition.

Synopsis:

__forceinline P4_e_t p4_thread_set_sched(P4_thr_t tnum, P4_prio_t prio, P4_uint32_t tp)

Parameters: tnum IN: Number of the thread whose priority shall be set. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. prio IN: New priority to be assigned to target thread. If new_prio is set to P4_PRIO_INHERIT, the target threads priority will be set to the calling threads priority. If prio is set to P4_PRIO_KEEP, the priority remains unchanged.

        Note:
        If an invalid priority value (prio >= P4_NUM_PRIO) is passed in, thread tnum will have the tasks MCP
        assigned as its new priority.
    tp IN: New time partition to be assigned to target thread. If new_tp is set to P4_TIMEPART_INHERIT,
       the target threads time partition will be set to the calling threads time partition. If new_tp is set to
       P4_TIMEPART_KEEP, the threads time partition remains unchanged.

        Note:
        To change a threads time partition                 the   callers   task    needs   to   have   the   ability
        P4_AB_TIMEPART_CHANGE enabled.

Description: This function assigns prio as the scheduling priority and tp as time partition of thread tnum. If prio is higher than the callers task MCP, then thread tnum will be assigned the MCP as its new priority value. This function is a convenience function implemented using p4_thread_ex_sched_syscall() (see section 1.16.5.14). On error codes other than P4_E_OK, thread attributes remain unchanged.

Note: If tnum refers to a thread currently running on another processor, the priority set via prio reflects the kernels view of the threads priority, not the threads current user priority. The current user priority may be higher. Therefore it is not recommended to change the priority of threads currently running on other processors.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number, or tp does not refer to a valid time partition. P4_E_STATE tnum does not refer to an active thread.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 227

P4_E_NOABILITY tp is not P4_TIMEPART_KEEP and the callers task does not have the ability P4_AB_TIMEPART_CHANGE enabled.

                     c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

228 The PikeOS Kernel API

1.16.5.18 p4_thread_ex_priority

Exchange thread priority.

Synopsis:

__forceinline P4_e_t p4_thread_ex_priority(P4_thr_t tnum, P4_prio_t *old_prio, P4_prio_t new_prio)

Parameters: tnum IN: Number of the thread whose priority shall be retrieved and/or updated. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. old_prio OUT: Pointer to location where the target threads current priority (before the update) will be stored, if not NULL. new_prio IN: New priority to be assigned to target thread. If new_prio is set to P4_PRIO_INHERIT, the target threads priority will be set to the calling threads priority. If new_prio is set to P4_PRIO_KEEP, the threads priority remains unchanged.

        Note:
        If an invalid priority value (new_prio >= P4_NUM_PRIO) is passed in, thread tnum will have the tasks
        MCP assigned as its new priority.

Description: This function returns the current priority of thread tnum in the location pointed to by old_prio (if non-NULL) and sets the new priority of tnum to new_prio (if not P4_PRIO_KEEP). If new_prio is higher than the callers task MCP, then thread tnum will be assigned the MCP as its new priority value. If old_prio is NULL and new_prio is set to P4_PRIO_KEEP, the only action of this function will be to validate tnum. This function is a convenience function implemented using p4_thread_ex_sched_syscall() (see section 1.16.5.14). On error codes other than P4_E_OK, thread attributes remain unchanged.

Note: If tnum refers to a thread currently running on another processor, the priority returned in old_prio reflects a transient snapshot of the current kernel priority, not the threads current user priority. The current user priority may be higher. Therefore it is not recommended to change the priority of threads currently running on other processors.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum does not refer to an active thread or tnum. P4_E_INVAL old_prio is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT old_prio is not NULL and is not fully mapped in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 229

1.16.5.19 p4_thread_get_priority

Retrieve thread priority.

Synopsis:

__forceinline P4_e_t p4_thread_get_priority(P4_thr_t tnum, P4_prio_t *prio)

Parameters: tnum IN: Number of the thread whose priority shall be retrieved. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. prio OUT: Pointer to location where the target threads priority will be stored. If prio is NULL, the priority will not be retrieved.

Description: This function returns the current priority of thread tnum in the location pointed to by prio. This function is a convenience function implemented using p4_thread_ex_sched_syscall() (see section 1.16.5.14).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum does not refer to an active thread. P4_E_INVAL prio is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT prio is not NULL and is not fully mapped in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

230 The PikeOS Kernel API

1.16.5.20 p4_thread_set_priority

Set thread priority.

Synopsis:

__forceinline P4_e_t p4_thread_set_priority(P4_thr_t tnum, P4_prio_t prio)

Parameters: tnum IN: Number of the thread whose priority shall be set. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. prio IN: New priority to be assigned to target thread. If new_prio is set to P4_PRIO_INHERIT, the target threads priority will be set to the calling threads priority. If prio is set to P4_PRIO_KEEP, the priority remains unchanged.

        Note:
        If an invalid priority value (prio >= P4_NUM_PRIO) is passed in, thread tnum will have the tasks MCP
        assigned as its new priority.

Description: This function assigns prio as the scheduling priority of thread tnum. If prio is higher than the callers task MCP, then thread tnum will be assigned the MCP as its new priority value. This function is a convenience function implemented using p4_thread_ex_sched_syscall() (see section 1.16.5.14). On error codes other than P4_E_OK, thread attributes remain unchanged.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum does not refer to an active thread.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 231

1.16.5.21 p4_thread_ex_exh

Exchange threads exception handlers.

Synopsis:

P4_e_t p4_thread_ex_exh(P4_thr_t tnum, P4_uid_t *old_shortexh, P4_uid_t *old_fullexh, P4_uid_t new_shortexh, P4_uid_t new_fullexh)

Parameters: tnum IN: Number of the thread whose exception handlers shall be retrieved and/or updated. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. old_shortexh OUT: Pointer to location where the target threads current short exception handler (before the update) will be stored, if not NULL. old_fullexh OUT: Pointer to location where the target threads current exception handler (before the update) will be stored, if not NULL. new_shortexh IN: New short exception handler to be assigned to target thread. If new_shortexh is set to P4_UID_INHERIT, the target threads short exception handler will be set to the calling threads short exception handler. If new_shortexh is set to P4_UID_KEEP, the threads short exception handler remains unchanged. If an invalid UID is passed in new_shortexh, no short exception handler will be installed. If the thread cannot communicate with its short exception, the next exception handler in order (full exception handler) is used. new_fullexh IN: New exception handler to be assigned to target thread. If new_fullexh is set to P4_UID_IN- HERIT, the target threads exception handler will be set to the calling threads exception handler. If new_fullexh is set to P4_UID_KEEP, the threads exception handler remains unchanged. If an invalid UID is passed in new_fullexh, no exception handler will be installed. If the thread cannot communicate with its full exception handler, TLS-based exception handling is used.

Description: This function returns the current exception handlers of thread tnum in the location pointed to by old_shortexh and old_fullexh and sets the exception handlers to new_shortexh and new_fullexh. The short exception handler is returned in *old_shortexh (if non-NULL) and new_shortexh is taken as new one if not set to P4_UID_KEEP. If it is set to P4_UID_INHERIT, the short exception handler of the calling thread will be set as short exception handler for thread tnum. If it is set to an invalid UID, no short exception handler will be installed. The exception handler is returned in *old_fullexh (if non-NULL) and new_fullexh is taken as new one if not set to P4_UID_KEEP. If it is set to P4_UID_INHERIT, the exception handler of the calling thread will be set as exception handler for thread tnum. If it is set to an invalid UID, no exception handler will be installed. If both old_shortexh and old_fullexh are NULL and new_shortexh and new_fullexh are both set to P4_UID_KEEP, the only action of this function will be to validate tnum. On error codes other than P4_E_OK, thread attributes remain unchanged.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

232 The PikeOS Kernel API

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum does not refer to an active thread. P4_E_INVAL old_shortexh or old_fullexh are not NULL and do not point to a valid address or exceed the callers virtual address space. P4_E_PAGEFAULT old_shortexh or old_fullexh are not NULL and are not fully mapped in the callers virtual address space.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 233

1.16.5.22 p4_thread_get_exh

Retrieve threads exception handlers.

Synopsis:

__forceinline P4_e_t p4_thread_get_exh(P4_thr_t tnum, P4_uid_t *old_shortexh, P4_uid_t *old_fullexh)

Parameters: tnum IN: Number of the thread whose exception handlers shall be retrieved. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. old_shortexh OUT: Pointer to location where the target threads current short exception handler (before the update) will be stored, if not NULL. old_fullexh OUT: Pointer to location where the target threads current exception handler (before the update) will be stored, if not NULL.

Description: This function returns the current exception handlers of thread tnum in the location pointed to by old_shortexh and old_fullexh. The short exception handler is returned in *old_shortexh (if non-NULL) and the exception handler is returned in *old_fullexh (if non-NULL). This function is a convenience function implemented using p4_thread_ex_exh() (see section 1.16.5.21).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum does not refer to an active thread. P4_E_INVAL old_shortexh or old_fullexh are not NULL and do not point to a valid address or exceed the callers virtual address space. P4_E_PAGEFAULT old_shortexh or old_fullexh are not NULL and are not fully mapped in the callers virtual address space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

234 The PikeOS Kernel API

1.16.5.23 p4_thread_set_exh

Set threads exception handlers.

Synopsis:

__forceinline P4_e_t p4_thread_set_exh(P4_thr_t tnum, P4_uid_t new_shortexh, P4_uid_t new_fullexh)

Parameters: tnum IN: Number of the thread whose exception handlers shall be updated. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. new_shortexh IN: New short exception handler to be assigned to target thread. If new_shortexh is set to P4_UID_INHERIT, the target threads short exception handler will be set to the calling threads short exception handler. If new_shortexh is set to P4_UID_KEEP, the threads short exception handler remains unchanged. If an invalid UID is passed in new_shortexh, no short exception handler will be installed. new_fullexh IN: New exception handler to be assigned to target thread. If new_fullexh is set to P4_UID_IN- HERIT, the target threads exception handler will be set to the calling threads exception handler. If new_fullexh is set to P4_UID_KEEP, the threads exception handler remains unchanged. If an invalid UID is passed in new_fullexh, no exception handler will be installed.

Description: This function sets the exception handlers of thread tnum to new_shortexh and new_fullexh. The short exception handler is set by new_shortexh if not P4_UID_KEEP. If it is set to P4_UID_INHERIT, the short exception handler of the calling thread will be set as short exception handler for thread tnum. If it is set to an invalid UID, no short exception handler will be installed. The exception handler is set by new_fullexh if not P4_UID_KEEP. If it is set to P4_UID_INHERIT, the exception handler of the calling thread will be set as exception handler for thread tnum. If it is set to an invalid UID, no exception handler will be installed. This function is a convenience function implemented using p4_thread_ex_exh() (see section 1.16.5.21). On error codes other than P4_E_OK, thread attributes remain unchanged.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum does not refer to an active thread.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 235

1.16.5.24 p4_thread_ex_affinity

Exchange thread processor affinity mask.

Synopsis:

P4_e_t p4_thread_ex_affinity(P4_thr_t tnum, P4_cpumask_t *old_affinity, P4_cpumask_t new_affinity)

Parameters: tnum IN: Number of the thread whose processor affinity mask shall be retrieved and/or updated. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. old_affinity OUT: Pointer to location where the target threads current processor affinity mask (before the update) will be stored, if not NULL. new_affinity IN: New processor affinity mask to be assigned to target thread. If new_affinity is set to zero, the threads processor affinity mask remains unchanged.

Description: This function returns the current processor affinity mask of thread tnum in the location pointed to by old_affinity (if non-NULL) and sets the processor affinity mask of tnum to new_affinity (if not zero). The new mask in new_affinity is AND-ed together with the tasks CPU mask, only the remaining processors are available for scheduling of the thread. If the resulting mask has no processor enabled, an error is raised. If the threads current processor is no longer included in the new processor affinity mask, the thread will be migrated to the first set processor in the affinity mask then. Depending on the current thread state, the migration may take place at a later point in time:

• if the target tnum is currently executing on a CPU, a rescheduling is requested, and the migration will occur
   when tnum is rescheduled.
• if tnum is ready, but not scheduled, it will be enqueued for execution on the destination CPU.
• if tnum is in a waiting-with-timeout state, the wait is canceled (more information are provided in each function
   subject to this behavior typically P4_E_CANCEL is received by the woken up tnum), and tnum will be
   rescheduled on the destination CPU.
• if tnum is not ready for execution nor waiting with a timeout, its scheduling parameters are simply updated
   with the new destination CPU.

If old_affinity is NULL and new_affinity is zero, the only action of this function will be to validate tnum. The function only allows migration of threads without pending deadlines. On error codes other than P4_E_OK, thread attributes remain unchanged.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number, or new_affinity results in no valid processor for the mask.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

236 The PikeOS Kernel API

P4_E_INVAL new_affinity is not zero and tnum refers to a thread that is registered as one of the parent tasks alarm-notification handler or as partition level handler. P4_E_STATE tnum does not refer to an active thread. P4_E_STATE tnum has an active deadline pending. P4_E_INVAL old_affinity is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT old_affinity is not NULL and is not fully mapped in the callers virtual address space.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 237

1.16.5.25 p4_thread_get_affinity

Retrieve thread processor affinity mask.

Synopsis:

__forceinline P4_e_t p4_thread_get_affinity(P4_thr_t tnum, P4_cpumask_t *affinity)

Parameters: tnum IN: Number of the thread whose processor affinity mask shall be retrieved. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. affinity OUT: Pointer to location where the target threads current processor affinity mask will be stored, if not NULL.

Description: This function returns the current processor affinity mask of thread tnum in the location pointed to by affinity (if non-NULL). This function is a convenience function implemented using p4_thread_ex_affinity() (see section 1.16.5.24).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_STATE tnum does not refer to an active thread. P4_E_INVAL affinity is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT affinity is not NULL and is not fully mapped in the callers virtual address space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

238 The PikeOS Kernel API

1.16.5.26 p4_thread_set_affinity

Set thread processor affinity mask.

Synopsis:

__forceinline P4_e_t p4_thread_set_affinity(P4_thr_t tnum, P4_cpumask_t new_affinity)

Parameters: tnum IN: Number of the thread whose processor affinity mask shall be updated. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MY- SELF and must refer to an active thread. new_affinity IN: New processor affinity mask to be assigned to target thread. If new_affinity is set to zero, the threads processor affinity mask remains unchanged.

Description: This function sets the processor affinity mask of tnum to new_affinity (if not zero). The new mask in new_affinity is AND-ed together with the tasks CPU mask, only the remaining processors are available for scheduling of the thread. If the resulting mask has no processor enabled, an error is raised. If the threads current processor is no longer included in the new processor affinity mask, the thread will be migrated to the first set processor in the affinity mask then. This function is a convenience function implemented using p4_thread_ex_affinity() (see section 1.16.5.24) (see this function for additional information). On error codes other than P4_E_OK, thread attributes remain unchanged.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number, or new_affinity results in no valid processor for the mask. P4_E_INVAL new_affinity is not zero and tnum refers to a thread that is registered as one of the parent tasks alarm-notification handler. P4_E_STATE tnum does not refer to an active thread.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 239

1.16.5.27 p4_thread_get_attr

Retrieve thread attributes.

Synopsis:

P4_e_t p4_thread_get_attr(P4_thr_t tnum, P4_thread_attr_t *attr)

Parameters: tnum IN: Number of the thread whose attributes shall be retrieved. The parameter tnum must be a valid thread number for the configured task limits or P4_THREAD_MYSELF. attr OUT: Location of attribute structure for storing result.

Description: This function retrieves the thread attributes for thread tnum and stores them in the thread attribute structure pointed to by attr (if non NULL).

Note: If tnum refers to a thread currently running on another processor, the returned thread attributes provide a transient snapshot of the threads state only.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL tnum is not a valid thread number. P4_E_INVAL attr is an invalid user space address or exceeds the callers virtual address space. P4_E_STATE tnum does not refer to an active thread. P4_E_PAGEFAULT attr is not NULL and is not fully mapped in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

240 The PikeOS Kernel API

1.16.5.28 p4_thread_yield

Yield processor.

Synopsis:

void p4_thread_yield(void)

Description: This function forces the running thread to relinquish the processor. The thread is placed at the tail of its ready queue and will be scheduled again on reaching the head of the queue. The function takes no arguments.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 241

1.16.5.29 p4_thread_arg

Initialise user mode context.

Synopsis:

P4_e_t p4_thread_arg(P4_regs_t *context, void *entry, void *stack, P4_uint32_t flags, unsigned int numargs, void *args[])

Parameters: context OUT: User mode context. entry IN: Thread entry point. stack IN: Initial thread stack pointer. flags IN: Set of bits used to further control the context creation. Currently, the following flag bits are defined:

           • P4_THREAD_ARG_FPU
             If set, the FPU part of context will be initialised and the use of the FPU will be enabled for threads
             created with this context.
           • P4_THREAD_ARG_DEBUG
             If set, an initial stack frame for debugger usage will be created. This demands a mapping of the
             user mode stack at stack.
           • P4_THREAD_ARG_VEC
             If set, the vector unit part of context will be initialised and the use of the vector unit will be enabled
             for threads created with this context.
           • P4_THREAD_ARG_DIRECT
             If set, a direct call in the user mode context entry is performed. I.e. the function pointer is a direct
             entry point and doesnt contain the TOC.

numargs IN: Number of parameters to pass to thread entry point. args IN: Parameters to pass to thread entry point.

Description: This function initialises the user mode context pointed to by context, overwriting the previous contents of context. A thread created with the initialised context will begin execution in the function entry, with numargs function parameters taken from args passed to the entry, and the threads initial stack pointer will be set to stack. flags is used to further control the context initialisation.

Note: The function specified in entry must not return, nor must it expect a valid return address. Instead, the newly created thread must delete its own thread explicitly by calling p4_thread_delete() (see section 1.16.5.3) or by terminating its task by calling p4_task_terminate() (see section 1.17.5.4).

Note:

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

242 The PikeOS Kernel API

Contexts to be used by p4_task_start() (see section 1.17.5.3) calls should have numargs set to zero, as different CPU architectures may pass parameters on the stack. Since the stack for a new task may not be mapped for the caller of p4_thread_arg() (see section 1.16.5.29), the function may cause a page fault when inserting the function parameters. On platforms where function parameters are passed in CPU registers, a limited number of parameters may be passed to thread 0 of a newly created task. Refer to the ASP documentation for further details. Code that is required to be portable across different CPU architectures should use numargs with a zero value.

Returns: Upon success, this function returns P4_E_OK, otherwise the following error code is returned to the caller: P4_E_INVAL numargs exceeds an architecture limitation for the number of arguments that can be transferred to the new thread (P4_THREAD_ARG_MAX_ARGS). P4_E_INVAL if an invalid flag is set in flags.

Note: This call is implemented as a user library function and involves no system call.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 243

1.16.5.30 p4_thread_fpu_on

Initialise and enable FPU use in a user mode context.

Synopsis:

void p4_thread_fpu_on(P4_regs_t *context)

Parameters: context IN: User mode context.

Description: This function initialises the FPU part of the user mode context pointed to by context and enables FPU usage. The initialisation values are platform dependent. When context becomes active (i.e. it is being used by an active thread), the FPU state will be restored when the scheduler switches to this thread and saved when the scheduler switches from this thread to another thread.

Note: This call is implemented as a user library function and involves no kernel activity.

Note: Since this call works on a saved user mode context, it can not be used by a thread to enable FPU usage for itself.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

244 The PikeOS Kernel API

1.16.5.31 p4_thread_fpu_off

Disable FPU use in a user mode context.

Synopsis:

void p4_thread_fpu_off(P4_regs_t *context)

Parameters: context IN: User mode context.

Description: This function disables FPU usage in the user mode context pointed to by context. The FPU state will no longer be restored from context when the scheduler switches to a thread using this context, or saved in context when the scheduler switches from this thread to another thread.

Note: Disabling FPU usage when a context has already been used by a thread should be done with care. Once disabled, the kernel will no longer save and restore the FPU state when the thread (context) gets scheduled. If the thread later tries to access the FPU, it will probably execute with the wrong FPU state. The exception handler, if installed, will then be responsible for providing the thread context with the correct FPU state expected by the faulting thread.

Note: This call is implemented as a user library function and involves no kernel activity.

Note: Since this call works on a user mode context it can not be used by a thread to disable FPU usage for itself.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread API 245

1.16.5.32 p4_thread_vec_on

Initialise and enable vector unit use in a user mode context.

Synopsis:

void p4_thread_vec_on(P4_regs_t *context)

Parameters: context IN: User mode context.

Description: This function initialises the vector unit part of the user mode context pointed to by context and enables vector unit usage. The initialisation values are platform dependent. When context becomes active (i.e. it is being used by an active thread), the vector unit state will be restored when the scheduler switches to this thread and saved when the scheduler switches from this thread to another thread.

Note: This call is implemented as a user library function and involves no kernel activity.

Note: Since this call works on a saved user mode context, it can not be used by a thread to enable vector unit usage for itself.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

246 The PikeOS Kernel API

1.16.5.33 p4_thread_vec_off

Disable vector unit use in a user mode context.

Synopsis:

void p4_thread_vec_off(P4_regs_t *context)

Parameters: context IN: User mode context.

Description: This function disables vector unit usage in the user mode context pointed to by context. The vector unit state will no longer be restored from context when the scheduler switches to a thread using this context, or saved in context when the scheduler switches from this thread to another thread.

Note: Disabling vector unit usage when a context has already been used by a thread should be done with care. Once disabled, the kernel will no longer save and restore the vector unit state when the thread (context) gets scheduled. If the thread later tries to access the vector unit, it will probably execute with the wrong vector unit state. The exception handler, if installed, will then be responsible for providing the thread context with the correct vector unit state expected by the faulting thread.

Note: This call is implemented as a user library function and involves no kernel activity.

Note: Since this call works on a user mode context it can not be used by a thread to disable vector unit usage for itself.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Task API 247

1.17 Task API

The section describes constants, data types, access macros, and service calls related to the PikeOS task man- agement API.

1.17.1 Structure Definitions

1.17.1.1 struct P4_task_bitmap_str

Task bitmap structure. The task bitmap is used to store and communicate task attributes that are related to the whole set of tasks, such as passive tasks or task communication rights. The task bitmap contains one bit for every task (0 ... P4_NUM_TASK-1) where each task number corresponds to a bit position within the bitmap and the attribute value is given by the bit value. The task bitmap structure is to be treated as an opaque data type and should only be accessed using the macros P4_TASK_GET_BIT() (see section 1.17.2) and P4_TASK_SET_BIT() (see section 1.17.2).

Synopsis: struct P4_task_bitmap_str { unsigned long m[...]; };

Structure Element Description: m Storage for bitmap.

Associated Data Type

P4_task_bitmap_t Task bitmap structure.

1.17.1.2 struct P4_task_attr_str

Task attribute structure. The function p4_task_get_attr() (see section 1.17.5.5) returns the task attributes in a data structure of type P4_task_attr_t. For tasks in the PASSIVE and ZOMBIE state, the only structure element with valid data is state, all other elements contain undefined data.

Synopsis: struct P4_task_attr_str { P4_cpumask_t cpu_mask; P4_task_state_t state; P4_prio_t mcp; P4_uint32_t respart; P4_task_t parent; P4_ability_mask_t ability_bitmap; P4_thr_t max_threads; char name[P4_NAMELEN];

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

248 The PikeOS Kernel API

};

Structure Element Description: cpu_mask Mask of available processors. state Current state of the task mcp MCP of the task respart Resource partition to which this task belongs parent Parent task number or P4_NUM_TASK if task has no parent. ability_bitmap Bitmap of abilities that are enabled for the task max_threads Maximum number of threads in this task. name Task name. The name is always a valid C string terminated with a NUL character.

Associated Data Type

 P4_task_attr_t Task attribute structure.

1.17.1.3 struct P4_task_activate_str

Task activation structure. The functions p4_task_activate() (see section 1.17.5.2) use this structure to describe the attributes of a task.

Synopsis:

struct P4_task_activate_str { const char * name; P4_cpumask_t cpu_mask; P4_thr_t max_threads; P4_prio_t mcp; P4_uint32_t rp_id; P4_ability_mask_t ability_mask; };

Structure Element Description: name If name is not NULL, the kernel will copy P4_NAMELEN bytes starting at name as the tasks name. If the string is longer than or equal to P4_NAMELEN characters, it will be truncated to P4_NAMELEN characters with a NUL character at the end. cpu_mask Mask representing the processors where threads of the task are allowed to run. If cpu_mask is zero, the mask of the activated task will be inherited from the caller. max_threads Number of possible threads in task.

       Note:
       If an invalid thread number (max_thread > kinfo.num_thread) or zero is passed in, max_thread will have
       the systems maximum number of threads assigned. No errors are generated in this case.
  mcp MCP (Maximum Controlled Priority) of the activated task. The MCP of the activated task will be the
      minimum of the value given by mcp and the callers MCP.
 rp_id Resource partition of the activated task.


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Task API 249

       The value of rp_id must be the ID of an existing partition or P4_RESPART_INHERIT, in which case the
       activated task inherits the resource partition from the caller.
       If the calling task wants to activate a child task in a resource partition other than its own one, it must have
       the ability P4_AB_RESPART_CHANGE enabled, otherwise p4_task_activate() (see section 1.17.5.2)
       will return an error.

ability_mask Bit mask containing the abilities that shall be removed from the parents abilities to form the abilities of the activated task. If a cleared bitmap is passed in, the abilities of the activated task will be inherited from the caller.

Associated Data Type

P4_task_activate_t Task activation structure.

1.17.2 Defines

P4_TASK_MYSELF Task number identifying the calling threads task. Description: Using this identifier as the task number in API calls will select the calling threads task as target task for the call.

P4_MAX_TASK_DEPTH Maximum path length of task tree. Description: Specifies the maximum task hierarchy tree depth with task 0 as root of the task tree having a path length of 1. The depth limit is tested in p4_task_donate() (see section 1.17.5.1).

P4_TASK_GET_BIT (tbm_p, tnum) This macro tests whether the bit for task tnum is set in the task bitmap pointed to by tbm_p.

       Parameters:
           tbm_p Pointer to the task bitmap to be tested.
           tnum Task number (0 ... P4_NUM_TASK-1).
       Returns:
       TRUE if the bit is set, FALSE otherwise.

       Note:
       If tnum is not a valid task number, the return value is undefined.

P4_TASK_SET_BIT (tbm_p, tnum) This macro sets the bit for task tnum in the task bitmap pointed to by tbm_p.

       Parameters:
           tbm_p Pointer to the task bitmap.
           tnum Task number (0 ... P4_NUM_TASK-1).


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

250 The PikeOS Kernel API

      Note:
      If tnum is not a valid task number, the effects of this macro are undefined.

P4_TASK_FILL_SET (tbm_p) Initialise task bitmap with all bits set. Description: This macro fills the task bitmap pointed to by tbm_p.

      Parameters:
          tbm_p Pointer to the task bitmap.

P4_TASK_CLEAR_SET (tbm_p) Initialise task bitmap with all bits cleared. Description: This macro clears the task bitmap pointed to by tbm_p.

      Parameters:
          tbm_p Pointer to the task bitmap.

P4_DECLARE_STACK (count) Declare the standard stack for the initial thread of a task. Description: When a thread is entered via the __p4_start function, it initialises the stack pointer to use a stack from the executable file, declared by this macro. The linker command file is responsible for setting up symbols pointing to this stack so that the __p4_start function finds the stack. The minimum amount of stack needed is application dependent. The application developer needs to do an analysis about the stack usage of the application (e.g. by using techniques like stack watermarking).

1.17.3 Data Type Definitions

P4_task_bitmap_t Task bitmap structure. The task bitmap is used to store and communicate task attributes that are related to the whole set of tasks, such as passive tasks or task communication rights. The task bitmap contains one bit for every task (0 ... P4_NUM_TASK-1) where each task number corresponds to a bit position within the bitmap and the attribute value is given by the bit value. The task bitmap structure is to be treated as an opaque data type and should only be accessed using the macros P4_TASK_GET_BIT() (see section 1.17.2) and P4_TASK_SET_BIT() (see section 1.17.2). P4_task_attr_t Task attribute structure. The function p4_task_get_attr() (see section 1.17.5.5) returns the task attributes in a data structure of type P4_task_attr_t. For tasks in the PASSIVE and ZOMBIE state, the only structure element with valid data is state, all other elements contain undefined data. P4_task_activate_t Task activation structure. The functions p4_task_activate() (see section 1.17.5.2) use this structure to describe the attributes of a task.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Task API 251

1.17.4 Enumerations

Enumeration type P4_task_state_t

Task state definitions.

Name Description P4_TASK_STATE_PASSIVE The task is passive.

P4_TASK_STATE_ACTIVATED The task has been activated but not yet started.

P4_TASK_STATE_STARTED The task has been started.

P4_TASK_STATE_ZOMBIE The task is about to be terminated.

                        c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

252 The PikeOS Kernel API

1.17.5 Functions

1.17.5.1 p4_task_donate

Donate a task.

Synopsis:

P4_e_t p4_task_donate(P4_task_t dest, P4_task_t which)

Parameters: dest IN: Task ID of the child task that shall receive the passive task. which IN: Task ID of the passive task that shall be donated.

Description: This function donates the passive task which to task dest. The destination task dest must be an active child task of the caller. If the function executes successfully, task which is moved from the callers passive task pool to the destination tasks passive task pool.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if dest or which is not a valid task ID. P4_E_BADTASK if task which is not a child task of the caller. P4_E_STATE if which is an active child task of the caller. P4_E_BADTASK if task dest is not a child task of the caller. P4_E_STATE if dest is a passive task of the caller. P4_E_LIMIT if the maximum path length P4_MAX_TASK_DEPTH of the task tree would be exceeded by donating additional tasks to dest.

Note: When checking the validity of task dest and which, the function will first test for correct ownership and then for correct state.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Task API 253

1.17.5.2 p4_task_activate

Activate a task.

Synopsis:

P4_e_t p4_task_activate(P4_task_t which, const P4_task_activate_t *ta, P4_uint32_t flags)

Parameters: which IN: Task ID of the passive task that shall be activated. ta IN: ta describes the attributes of the task to be activated. The parameter ta must be fully mapped in the callers address space and all values must be initialized properly. flags IN: Flags: Flags reserved for future use (must be zero).

Description: This function activates the passive task which. The task which must belong to the callers pool of passive tasks. The structure ta describes the default attributes for the to be activated task. During activation, the following attributes of task which will be initialized:

• An empty address space will be created.
• The MCP of the task will be set to the value given by ta->mcp.
• The abilities given by ta->ability_mask will be removed from the tasks list of abilities.
• The task will be assigned to the resource partition identified by ta->rp_id.
• The processors available to the task are represented by ta->cpu_mask. Only processors available to the
  parent can can be enabled for the new task. If ta->cpu_mask is 0, the processor mask of the parent tasks
  is inherited.

The flags argument is currently unused and must be set to zero. Activating a task does not create any thread in that task. An active task can:

• Receive mappings from its parent task
• Receive passive tasks from its parent task
• Receive additional communication rights from its parent task via p4_comm_grant() (see section 1.10.3.1).
  See p4_comm_grant() (see section 1.10.3.1) for a description of the function behavior.
• Receive interrupt attachment permissions from its parent task via p4_int_grant() (see section 1.13.4.5). See
  p4_int_grant() (see section 1.13.4.5) for a description of the function behavior.
• Receive kernel level device access permissions from its parent task via p4_dev_grant() (see section
  1.21.4.1). See p4_dev_grant() (see section 1.21.4.1) for a description of the function behavior.
• Be started and terminated by its parent task

If the function executes successfully, the inactive task which becomes an active child task of the caller.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

254 The PikeOS Kernel API

The number of possible threads will be limited to ta->max_threads. Valid thread numbers for the task will be in the range [0 ... (ta->max_threads -1)]. The number of threads only affects the task to be activated, not any possible child tasks of that task.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_STATE if which is an active child task of the caller. P4_E_BADTASK if which is not a child task of the caller. P4_E_INVAL if which is not a valid task ID. P4_E_INVAL if ta is NULL. P4_E_INVAL if ta or ta->name do not point to a valid address or exceeds the callers virtual address space. P4_E_INVAL if ta->cpu_mask is not contained in the cpu_mask of the parent. P4_E_INVAL if an invalid flag is set in flags. P4_E_NOKMEM if there is not enough kernel memory available in the resource partition ta->rp_id to activate the task. P4_E_NOABILITY if the caller attempts to activate the task which in a different resource partition ta->rp_id than its own and the caller does not have the ability P4_AB_RESPART_CHANGE enabled. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel does not point to a valid address in the callers virtual address space. P4_E_NOENT If the resource partition ta->rp_id does not exist. The error code P4_E_NOABILITY has precedence over P4_E_NOENT.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Task API 255

1.17.5.3 p4_task_start

Start an active child task.

Synopsis:

P4_e_t p4_task_start(P4_task_t which, const P4_thread_create_t *tc)

Parameters: which IN: Task ID of the active task that shall be started tc IN: tc describes the attributes of the thread to be created. The parameter tc must be fully mapped in the callers address space and all values must be initialized properly.

Description: This function starts the task which. Task which must be an active child task of the caller. If the function executes successfully, thread 0 of task which is started with the settings provided in tc. The following settings can be made:

• The threads name is supplied in tc->name.
• The initial CPU register contents are given by tc->context.
• The initial priority is set to the minimum of tc->prio and the tasks MCP (set at task activation).
• The time partition is set to tc->tp_id.
• The short exception handler is set to the thread given by tc->shortexh.
• The full exception handler is set to the thread given by tc->fullexh.
• The IPC mask is set according to tc->ipc_mask.
• The event masks is set according to tc->ev_mask.

The new threads affinity mask is limited to the processor represented by the lowest set bit in the tasks CPU mask and the new thread is assigned to this processor. The new threads registered thread local storage area is set to NULL, effectively disabling the kernel to access variables in thread local storage, regardless of a thread local storage area set with p4_thread_tls_register() (see section 1.20.3.1).

Note: The initial function of the created thread as specified in tc->context must not return, nor must it expect a valid return address. Instead, the newly created thread must delete its own thread explicitly by calling p4_thread_delete() (see section 1.16.5.3) or by terminating its task by calling p4_task_terminate() (see section 1.17.5.4).

Note: To register a thread local storage area, the new thread must call p4_tls_register() (see section 1.20.3.2).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if which is not a valid task ID. P4_E_BADTASK if task which is not a child task of the caller.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

256 The PikeOS Kernel API

P4_E_STATE if task which is a passive task of the caller. P4_E_STATE if task which has already been started. P4_E_INVAL if the time partition tc->tp_id is invalid. P4_E_INVAL if tc or tc->context are NULL. P4_E_INVAL if tc, tc->context, or tc->name do not point to a valid address or exceed the callers virtual address space. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel does not point to a valid address in the callers virtual address space. P4_E_NOKMEM if there is not enough kernel memory available in the resource partition of task which to complete the operation. P4_E_NOABILITY if the caller attempts to start thread 0 of task which in a time partition that doesnt refer to the callers time partition and the callers task does not have the ability P4_AB_TIMEPART_CHANGE enabled.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Task API 257

1.17.5.4 p4_task_terminate

Terminate a child task.

Synopsis:

P4_e_t p4_task_terminate(P4_task_t which)

Parameters: which IN: ID of the active task that shall be terminated. P4_TASK_MYSELF refers to the callers task.

Description: This function terminates task which and all of its sub-tasks. All terminated tasks and all their passive tasks will become passive tasks of the callers task or, if a task terminates itself, of the callers parent task. A task can only terminate itself or one of its (activated or started) child tasks. While terminating, the calling thread donates its own priority and time partition to the to be deleted threads and forces them to finish any ongoing kernel operations. If a to-be-deleted thread in the terminated task or its sub-tasks already executes in timepartition 0, it is not migrated to the callers time partition. If task which refers to a child task which already terminates itself, the caller of this function effectively becomes the terminating thread of the target task.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_BADTASK if task which is not a child task of the callers task and is not the callers own task. P4_E_STATE if task which is a passive task of the caller. P4_E_STATE which refers to a task already being terminated by another thread of the calling task. P4_E_INVAL if which is not a valid task ID.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

258 The PikeOS Kernel API

1.17.5.5 p4_task_get_attr

Retrieve task attributes.

Synopsis:

P4_e_t p4_task_get_attr(P4_task_t which, P4_task_attr_t *attr_p, P4_task_bitmap_t *pt_bitmap_p, P4_task_bitmap_t *comm_map_p, P4_interrupt_bitmap_t *int_map_p, P4_device_bitmap_t *dev_map_p)

Parameters: which IN: ID of the task whose task attributes shall be retrieved. P4_TASK_MYSELF refers to the callers task. attr_p OUT: Pointer to a task attribute structure Upon successful completion, the structure referenced by attr_p will contain the task attributes. A NULL pointer indicates that the task attributes should not be retrieved. pt_bitmap_p OUT: Bitmap of passive tasks. Each bit in this bitmap represents one task, the bit position corresponding to the task number. If a bit is set, the corresponding task is a passive task of the task to which this task bitmap belongs. A NULL pointer indicates that the bitmap of passive tasks should not be retrieved. comm_map_p OUT: Communication bitmap. Each bit in this bitmap represents one task, the bit position corresponding to the task number. If a bit is set, task which has the right to send IPC messages to the corresponding task. A NULL pointer indicates that the communication bitmap should not be retrieved. int_map_p OUT: Interrupt bitmap. Each bit in this bitmap represents an interrupt granted to this task with the bit position corresponding to the interrupt number. If a bit is set, task which has the right to attach to the corresponding interrupt. A NULL pointer indicates that the interrupt bitmap should not be retrieved. dev_map_p OUT: Device bitmap. Each bit in this bitmap represents a kernel level device with the bit position corresponding to the device number. If a bit is set, task which has the granted access right for this dedicated kernel level device. A NULL pointer indicates that the device bitmap should not be retrieved.

Description: This function retrieves the attributes of task which. Task id which may be any valid task number. For security reasons, access on information is limited to the callers task or one of its child tasks. For a detailed description of the task attribute structure, refer to the documentation of P4_task_attr_t.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if which is not a valid task ID.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Task API 259

P4_E_INVAL if either attr_p, pt_bitmap_p, comm_map_p, int_map_p, or dev_map_p are not valid addresses or exceed the callers virtual address space. P4_E_BADTASK if task which is not a child task of the callers task and is not the callers own task. P4_E_STATE if task which is a passive task of the caller. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel is not fully mapped in the callers virtual address space.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

260 The PikeOS Kernel API

1.17.5.6 p4_task_hm_register

Register per-CPU tasks health-monitor alarm-notification handler.

Synopsis:

P4_e_t p4_task_hm_register(P4_uint32_t flags)

Parameters: flags IN: Flags: Flags reserved for future use (must be zero).

Description: This function registers the current thread as alarm-notification handler for the current task on the current CPU. One HM-handler per CPU should be registered on all CPUs of the current task to be able to receive and manage deadline expiration HM-events. The affinity mask of the current thread should only contain the current CPU; after the registration, the affinity mask of the registered handler thread can no longer be modified. When a deadline (alarm) expiration event is received, the kernel wakes up the handler thread (registered via this system call), which may wait on deadline events using the p4_task_hm_wait() (see section 1.17.5.7) call.

Note: The flags parameter is reserved for future use and must be zero.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL If the current thread has a CPU affinity mask containing more CPUs than just the current one. P4_E_INVAL if an invalid flag is set in flags. P4_E_INVAL if a thread is already registered as partition-level error handler for the current CPU. P4_E_STATE If a thread is already registered as task HM handler on the current CPU.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Task API 261

1.17.5.7 p4_task_hm_wait

Wait for and notify health-monitor alarm-notifications.

Synopsis:

P4_e_t p4_task_hm_wait(P4_uid_t *overdue_p)

Parameters: overdue_p OUT: UID of the thread with the oldest expired deadline, or P4_UID_INVALID.

Description: A call to this function allows the caller to wait for and trigger the notification of expired deadlines on the current CPU. One "HM-handler" thread should be registered (see p4_task_hm_register() (see section 1.17.5.6)) on each CPU where deadlines could expire. When this function is called, if expired deadlines are present for the task, the UID of the thread with the oldest expired deadline is copied in overdue_p. If no expired deadlines are present, the caller is blocked waiting for expired deadlines or until p4_task_hm_wake() (see section 1.17.5.8) is called. When a deadline expires, the caller wakes up and the UID of the oldest expired deadline is copied in overdue_p. If the caller is woken up, but no deadlines have expired overdue_p is set to P4_UID_INVALID. The UIDs of threads with expired deadlines can be retrieved by repeatedly invoking this function. The function must be actively entered to detect whether deadlines have expired since the last call to the function. To be able to receive HM-deadline events and to block on this syscall, the calling thread must be the thread previously registered on this CPU via p4_task_hm_register() (see section 1.17.5.6).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL The calling thread is not the thread registered on the current CPU via p4_task_hm_register() (see section 1.17.5.6). P4_E_CANCEL If the waiting was canceled by another thread.

Note: On error code P4_E_CANCEL, the overdue_p may be set to indicate that a deadline have expired concurrently with the wakeup of the calling thread.

Note: Pagefaults while accessing overdue_p are ignored.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

262 The PikeOS Kernel API

1.17.5.8 p4_task_hm_wake

Wake previously registered HM-handlers for the current task.

Synopsis:

void p4_task_hm_wake(P4_cpumask_t cpu_mask)

Parameters: cpu_mask IN: Target CPUs where the handlers to wake up reside.

Description: This function wakes up the HM-handler previously registered (see p4_task_hm_register() (see section 1.17.5.6)) for the current task. Since the HM-handler are CPU-bound, the cpumask cpu_mask allows the specification which CPUs (and which handlers) need to be woken up. The cpu_mask is restricted to the CPUs assigned to the task before performing the wakeup. The function always succeed, but, in the case of concurrent deletion or wakeup of the registered handlers (e.g., due to deadline), the registered handlers may be already awake or may not be woken up at all.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Task API 263

1.17.5.9 p4_get_parent

Retrieve callers parent task number.

Synopsis:

P4_task_t p4_get_parent(void)

Description: This function returns the callers parent task number.

Returns: Upon success, this function returns the callers parent task number.

Note: p4_get_parent() (see section 1.17.5.9) is implemented as a convenience function using p4_task_get_attr() (see section 1.17.5.5).

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

264 The PikeOS Kernel API

1.18 Resource Partition API

The section describes constants, data types, access macros, and service calls related to the PikeOS resource partition management API.

1.18.1 Structure Definitions

1.18.1.1 struct P4_respart_attr_str

Resource partition attribute structure. The function p4_mon_respart_get_attr() (see section 1.23.4.1) returns the resource partition attributes in a data structure of type P4_respart_attr_str.

Synopsis: struct P4_respart_attr_str { P4_size_t numpages; P4_size_t freepages; P4_size_t mmpages; P4_size_t threadpages; P4_size_t taskpages; P4_size_t kdevpages; };

Structure Element Description: numpages Overall number of pages assigned to the resource partition freepages Number of free pages mmpages Number of pages used for memory management threadpages Number of pages used for thread descriptors taskpages Number of pages used for task descriptors kdevpages Number of pages used for KDEV driver resources

Associated Data Type

P4_respart_attr_t Resource partition attribute structure.

1.18.2 Defines

P4_RESPART_INHERIT Inherit resource partition. Description: Special resource partition number to indicate that the resource partition should be inherited from the parent task.

VM_PART_MODE_IDLE 0

        Description:


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Resource Partition API 265

     The partition is idle, i.e., not running.

VM_PART_MODE_COLD_START 1

     Description:
     The partition is running after being initially booted. This may also indicate that the partition is still
     initialising, as the post-init, normal run mode can be expressed by VM_PART_MODE_NORMAL.

VM_PART_MODE_WARM_START 2

     Description:
     The partition is running after having been warm booted at least once. This may also indicate that the par-
     tition is still initialising, as the post-init, normal run mode can be expressed by VM_PART_MODE_NOR-
     MAL.

VM_PART_MODE_NORMAL 3

     Description:
     The partition is in normal operation mode, i.e., the initialisation phase has ending.

vm_part_operating_mode_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

vm_part_operating_mode_MAX 3

     Description:
     Maximum value of the enum type

VM_SCHED_CHANGE_COLD_START 1

     Description:
     At a schedule scheme change, restart the partition in VM_PART_MODE_COLD_START, if possible.

VM_SCHED_CHANGE_WARM_START 2

     Description:
     At a schedule scheme change, restart the partition in VM_PART_MODE_WARM_START, if possible.

VM_SCHED_CHANGE_IGNORE 4

     Description:
     At a schedule scheme change, do not restart the partition.

vm_sched_change_action_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

266 The PikeOS Kernel API

vm_sched_change_action_MAX 4

      Description:
      Maximum value of the enum type

1.18.3 Data Type Definitions

P4_respart_attr_t Resource partition attribute structure. The function p4_mon_respart_get_attr() (see section 1.23.4.1) returns the resource partition attributes in a data structure of type P4_respart_attr_str. vm_part_operating_mode_t This enum is set up such that the enum values match the corresponding actions in P4_hm_pac_t. E.g. VM_PART_MODE_IDLE == P4_HM_PAC_IDLE, etc. These are different enums, because VM_PART_MODE_NORMAL is not an action and P4_HM_PAC_IGNORE is not an operating mode. But the overlapping modes/actions have the have the same value. This entities can be specified in the VMIT partition configuration information. vm_sched_change_action_t This enum is set up such that the enum values match the corresponding actions in P4_hm_pac_t. E.g. VM_PART_MODE_WARM_START == VM_SCHED_CHANGE_WARM_START, etc. Used by the PSSW when dealing with Time Parti- tion Switches.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Resource Partition API 267

1.18.4 Functions

1.18.4.1 p4_respart_get_kmem

Get callers resource partitions kernel memory attributes.

Synopsis:

P4_e_t p4_respart_get_kmem(P4_size_t *freepages_p, P4_size_t *numpages_p)

Parameters: freepages_p OUT: Pointer to location where the partitions number of currently free pages will be stored, if not NULL. numpages_p OUT: Pointer to location where the partitions number of overall pages will be stored, if not NULL.

Description: This function returns the number of free and overall pages assigned to the callers resource partition. The number of currently free pages is returned in *freepages_p (if non-NULL). The number of overall pages is returned in *numpages_p (if non-NULL).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL freepages_p or numpages_p are not NULL and do not point to a valid address or exceed the callers virtual address space. P4_E_PAGEFAULT freepages_p or numpages_p are not NULL and are not fully mapped in the callers virtual address space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

268 The PikeOS Kernel API

1.18.4.2 p4_respart_alloc_aligned

Allocate one memory block from the per-partition kernel memory pool. The size of a memory block depends on the thrinfo_size configuration parameter.

Synopsis:

P4_e_t p4_respart_alloc_aligned(P4_uint32_t respart, P4_phys_addr_t *phys_addr)

Parameters: respart IN: Number of the resource partition from which pages are to be allocated. The parameter respart must be a valid resource partition number within the configured resource partition limits. phys_addr OUT: phys_addr contains the base address of the allocated memory in physical address space. In the case of other error codes others than P4_E_OK, phys_addr is undefined.

Description: Allocate one memory block from the kernel memory pool of the given resource partition respart. The physical address of the beginning of the returned memory range is returned in phys_addr. The user should create a mapping of it with p4_mem_create() (see section 1.15.6.6). The size of a block depends on the thrinfo_size configuration parameter. Details are provided in the section "Kernel resources" of each PikeOS platform manuals.

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_NOABILITY if the task of the calling thread does not have the abilities P4_AB_KMEM_HANDLING and P4_AB_RESPART_SETUP enabled. P4_E_INVAL if phys_addr is NULL, or if respart is not a valid resource partition number. P4_E_NOKMEM if there is no sufficient memory left in the pool.

Note: Invalid pointers or unmapped memory areas for phys_addr will not raise an error in this system call.

Note: The call is not robust against architecture-dependent cache-aliasing effects. The caller must provide an alignment large enough to avoid such effects.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Time Partition API 269

1.19 Time Partition API

This section describes constants, data structures, access macros and service functions related to the kernel part of the PikeOS time partition scheduling.

1.19.1 Structure Definitions

1.19.1.1 struct P4_tptable_str

Time partition window.

Synopsis: struct P4_tptable_str { P4_uint32_t timepart; P4_uint32_t duration; P4_uint32_t min_duration; P4_uint16_t flags; P4_uint16_t userdata; P4_uint32_t window_id; };

Structure Element Description: timepart Time partition to activate in this window. This corresponds to "TimePartitionID" in the VMIT Window configuration. duration Duration of the window (including estimated switch time). This corresponds to "Duration" in the VMIT Window configuration. min_duration Duration of the window (exluding estimated switch time). This corresponds to "MinDuration" in the VMIT Window configuration. flags Window flags. This corresponds to "Flags" in the VMIT Window configuration. userdata User window data: not interpreted by PikeOS. This corresponds to "UserData" in the VMIT Window configuration. window_id User-defined window ID: not interpreted by PikeOS. This corresponds to "Identifier" in the VMIT Window configuration.

Associated Data Type

P4_tptable_t Time partition window.

1.19.1.2 struct P4_timepart_wtable_str

Time partition window table. Within a time partition schema, a window table identifies (via first and last indexes) all the windows with the same cpu_mask and synchronization cpu sync_cpu. The PSSW (or privileged software with P4_AB_TIMEPART_SETUP ability) uses an array of window tables to describe a time partition schema upon time partition switch (start or switch).

Synopsis:

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

270 The PikeOS Kernel API

struct P4_timepart_wtable_str { P4_cpumask_t cpu_mask; P4_uint32_t first; P4_uint32_t last; };

Structure Element Description: cpu_mask CPU mask for the window table first First index (first window) in the table, the same window sequence is activated on all the cpumask. Must be in range [0 .. (MAX_ENTRIES-1)] last Last index (last window) in the table. Must be in range [0 .. (MAX_ENTRIES-1)] and must be equal to or larger than first.

Associated Data Type

P4_timepart_wtable_t Time partition window table.

1.19.1.3 struct P4_timepart_window_attr_str

Current time partition window attribute structure. The function p4_timepart_window_get_attr() (see section 1.19.6.5) returns the attributes of the currently active time partition window in a data structure of type P4_timepart_window_attr_t. All attributes are specific to on the processor for which the attributes were retrieved.

Note: In periodic ticker mode only, immediately after a time partition switch, the time stored in last_switch may differ by at most one tick from the time reported by the PSP-based, high resolution time base (e.g., accessed via p4_get_time() (see section 1.6.2.3)). This is due to the way employed by the kernel to compute the last_switch time to prevent drifting of the time partition switching mechanism.

Synopsis: struct P4_timepart_window_attr_str { P4_time_t last_switch; P4_uint32_t timepart; P4_uint32_t window_id; P4_uint16_t flags; P4_uint16_t userdata; P4_bool_t window_overrun; P4_uint32_t duration; P4_uint32_t min_duration; P4_uint32_t overall_switches; P4_uint32_t padding; };

Structure Element Description: last_switch Time of the last time partition window switch. timepart Currently active time domain. window_id Current time partition window ID.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Time Partition API 271

flags Current time partition window flags. userdata Current time partition window user data. window_overrun Current time partition window is overrun. duration Current window duration including switch time (in TP-resolution units). min_duration Current window duration excluding switch time (in TP-resolution units). overall_switches Number of overall time partition window switches on the processor since system start. padding Explicit padding to align the structure

Associated Data Type

P4_timepart_window_attr_t Current time partition window attribute structure.

1.19.2 Time partition switch flags

The following constants represent flags that modify the behaviour of p4_timepart_switch() (see section 1.19.6.2).

Defines

P4_TIMEPART_SWITCH_IMMEDIATE Time partition switch flag: Request immediate schema switch. Description: When used in p4_timepart_switch() (see section 1.19.6.2), this flag specifies that the time partitioning should be immediately (at the next possible tick) switched.

P4_TIMEPART_SWITCH_MAJOR Time partition switch flag: Request deferred switch at next major frame. Description: When used in p4_timepart_switch() (see section 1.19.6.2), this flag specifies that the time partitioning schema should be changed (i.e., a new set of windows should be activated) at the next major frame.

1.19.3 Time partition window flags

The following constants represent flags that represent actions invoked on a switch to the time partition window. All flags can be OR-ed together.

Defines

P4_TPTABLE_FLAG_PERIOD Time partition window flag: window represents beginning of a period. Description: Setting this flag instructs the time partition switcher to wake up threads waiting for the P4_TIME- OUT_TP_PERIOD condition to become true.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

272 The PikeOS Kernel API

P4_TPTABLE_FLAG_MAJOR Time partition window flag: window represents beginning of a major time frame. Description: Setting this flag instructs the time partition switcher to wake up threads waiting for the P4_TIME- OUT_TP_MAJOR condition to become true.

P4_TPTABLE_FLAG_FLUSH_TLB Time partition window flag: flush TLBs before switching to current window. Description: Setting this flag instructs the time partition switcher to flush the CPUs TLBs (translation look aside buffers) before switching to the current window.

P4_TPTABLE_FLAG_INVAL_ICACHE Time partition window flag: flush CPUs instruction caches before switching to current window. Description: Setting this flag instructs the time partition switcher to flush the CPUs instruction caches before switch- ing to the current window.

P4_TPTABLE_FLAG_FLUSH_DCACHE Time partition window flag: flush CPUs data caches before switching to current window. Description: Setting this flag instructs the time partition switcher to flush the CPUs data caches before switching to the current window.

P4_TPTABLE_FLAG_SYNC_SWITCH_OUT Time partition window flag: synchronize the window switching on all CPUs of the window table before switching out the previous window. Description: Setting this flag instructs the time partition switcher to synchronize (via barrier busy waiting) the time partition switching on all CPUs of the window table. This flag controls the switch-out synchronization of the previous window. The synchronization is per- formed before invoking KDEV drivers registered on the alert_timepart callback. Setting the flag ensures that no callback will be invoked before all CPUs in the window table have reached the same switch-out point in kernel. Setting the flag is only recommended if alert_timepart drivers callbacks are registered and synchroniza- tion before their invocation is required.

P4_TPTABLE_FLAG_SYNC_PRE_FLUSH Time partition window flag: synchronize the window switching on all CPUs of the window table before flushing and invalidation operations start. Description: Setting this flag instructs the time partition switcher to synchronize (via barrier busy waiting) the time partition switching on all CPUs of the window table. This flag is currently reserverd for future use.

P4_TPTABLE_FLAG_SYNC_POST_FLUSH Time partition window flag: synchronize the window switching on all CPUs of the window table after all flushing and invalidation operations have been performed.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Time Partition API 273

      Description:
      Setting this flag instructs the time partition switcher to synchronize (via barrier busy waiting) the time
      partition switching on all CPUs of the window table.
      This flag controls the synchronization after all the flushing and invalidation operations (possi-
      bly set with P4_TPTABLE_FLAG_FLUSH_TLB, P4_TPTABLE_FLAG_FLUSH_DCACHE, P4_TPT-
      ABLE_FLAG_INVAL_ICACHE) have been performed. Setting the flag ensures that no userspace code
      on the CPU of the window table may execute in parallel with still pending cache/TLB operation.
      Setting the flag is recommended as default on all multicore setups that require cache/TLB flushing
      operations across window switching.
      The flag should be set if P4_TPTABLE_FLAG_SYNC_SWITCH_IN is required.
      NOTE: the flag is also inserted implicitly across time partition schema change by the kernel to ensure
      serialization of consecutive time partition scheme changes.

P4_TPTABLE_FLAG_SYNC_SWITCH_IN Time partition window flag: synchronize the window switching on all CPUs of the window table before switching in the current window. Description: Setting this flag instructs the time partition switcher to synchronize (via barrier busy waiting) the time partition switching on all CPUs of the window table. This flag controls the switch-in synchronization of the current window. The synchronization is performed after invoking KDEV drivers registered on the alert_timepart callback. Setting the flag ensures that no userspace code on the CPU of the window table may execute in parallel with still pending TPS driver operations. Setting the flag is only recommended if alert_timepart drivers callbacks are registered and synchroniza- tion after their invocation is required.

P4_TPTABLE_FLAG_CHANGE Time partition window flag: indicate change of the tptable sub range. Description: This flag is set by the kernel upon window changes in the time partition table subranges.

P4_TPTABLE_FLAG_FIRST Time partition window flag: indicate first window. Description: This flag is set by the kernel if the window is the first window in the active sub range in the time partition table.

1.19.4 Defines

P4_TIMEPART_INHERIT Inherit time partition. Description: Special time partition value to indicate that the time partition shall be inherited from the calling thread when creating a new thread or updating a threads attributes.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

274 The PikeOS Kernel API

P4_TIMEPART_KEEP Keep time partition. Description: Special time partition value to indicate that the time partition shall remain unchanged when updating a threads attributes.

VM_SCF_PERIOD 1

    Description:
    Setting this flag instructs the time partition switcher to wake up threads waiting for the P4_TIME-
    OUT_TP_PERIOD condition to become true.

VM_SCF_FLUSH_TLB 4

    Description:
    Setting this flag instructs the time partition switcher to flush the CPUs TLBs (translation look aside
    buffers) before switching to the current window.

VM_SCF_INVAL_ICACHE 8

    Description:
    Setting this flag instructs the time partition switcher to flush the CPUs instruction caches before switch-
    ing to the current window.

VM_SCF_FLUSH_DCACHE 16

    Description:
    Setting this flag instructs the time partition switcher to flush the CPUs data caches before switching to
    the current window.

VM_SCF_SYNC_SWITCH_OUT 32

    Description:
    Setting this flag instructs the time partition switcher to synchronize (via barrier busy waiting) the time
    partition switching on all CPUs of the window table. This flag controls the switch-out synchronization of
    the previous window. The synchronization is performed before invoking KDEV drivers registered on the
    alert_timepart callback. Setting the flag ensures that no callback will be invoked before all CPUs in the
    window table have reached the same switch-out point in kernel. Setting the flag is only recommended if
    alert_timepart drivers calbacks are registered and synchronization before their invocation is required.

VM_SCF_SYNC_PRE_FLUSH 64

    Description:
    Setting this flag instructs the time partition switcher to synchronize (via barrier busy waiting) the time
    partition switching on all CPUs of the window table. This flag is currently reserved for future use.


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Time Partition API 275

VM_SCF_SYNC_POST_FLUSH 128

      Description:
      Setting this flag instructs the time partition switcher to synchronize (via barrier busy waiting) the time
      partition switching on all CPUs of the window table. This flag controls the synchronization after all
      the flushing and invalidation operations (possibly set with P4_TPTABLE_FLAG_FLUSH_TLB, P4_TPT-
      ABLE_FLAG_FLUSH_DCACHE, P4_TPTABLE_FLAG_INVAL_ICACHE) have been performed. Setting
      the flag ensures that no userspace code on the CPU of the window table may execute in parallel with
      still pending cache/TLB operation. Setting the flag is recommended as default on all multicore setups
      that require cache/TLB flushing operations across window switching. The flag should be set if P4_TPT-
      ABLE_FLAG_SYNC_SWITCH_IN is required. The flag is implicitly activated by PikeOS on time partition
      scheme changes.

VM_SCF_SYNC_SWITCH_IN 256

      Description:
      Setting this flag instructs the time partition switcher to synchronize (via barrier busy waiting) the time
      partition switching on all CPUs of the window table. This flag controls the switch-in synchronization
      of the current window. The synchronization is performed after invoking KDEV drivers registered on the
      alert_timepart callback. Setting the flag ensures that no userspace code on the CPU of the window table
      may execute in parallel with still pending TPS driver operations. Setting the flag is only recommended if
      alert_timepart drivers calbacks are registered and synchronization after their invocation is required.

vm_window_flags_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

vm_window_flags_MAX 256

      Description:
      Maximum value of the enum type

vm_window_flags_MASK 509

      Description:
      All values of this bitmask enum ORed together into a bitmask

1.19.5 Data Type Definitions

P4_tptable_t Time partition window. P4_timepart_wtable_t Time partition window table. Within a time partition schema, a window table identifies (via first and last indexes) all the windows with the same cpu_mask and synchronization cpu sync_cpu. The PSSW (or privileged software with P4_AB_TIMEPART_SETUP ability) uses an array of window tables to describe a time partition schema upon time partition switch (start or switch). P4_timepart_window_attr_t Current time partition window attribute structure.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

276 The PikeOS Kernel API

    The function p4_timepart_window_get_attr() (see section 1.19.6.5) returns the attributes of the currently
    active time partition window in a data structure of type P4_timepart_window_attr_t. All attributes are
    specific to on the processor for which the attributes were retrieved.

    Note:
    In periodic ticker mode only, immediately after a time partition switch, the time stored in last_switch may
    differ by at most one tick from the time reported by the PSP-based, high resolution time base (e.g.,
    accessed via p4_get_time() (see section 1.6.2.3)). This is due to the way employed by the kernel to
    compute the last_switch time to prevent drifting of the time partition switching mechanism.

vm_window_flags_t Time partition window flags. This type is defined in such a way that its values are equal to the P4_TPTABLE_FLAG_* value from the PikeOS kernel API.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Time Partition API 277

1.19.6 Functions

1.19.6.1 p4_timepart_load

Load time partition table into kernel.

Synopsis:

P4_e_t p4_timepart_load(const P4_tptable_t *table, P4_uint32_t entries)

Parameters: table IN: Pointer to time partition table in user space. Must be a valid user space pointer entries IN: Number of entries in the table. Must be in range [1 .. MAX_ENTRIES] MAX_ENTRIES is set via kernel parameter UK_TPTABLE_MAX_WINDOWS.

Description: Load time partition table referenced by table into the kernel. The table consists of entries entries of type P4_tpt- able_t. All entries of the table are validated:

• timepart must be in range [0 .. kinfo->num_timepart-1]

Time partition schema should be explicitly switched by calling p4_timepart_switch() (see section 1.19.6.2) (p4_timepart_load() (see section 1.19.6.1) does not perform any switch). In case of error codes P4_E_PAGEFAULT and P4_E_PERM, no new time partition table will be installed. The synchronization flags P4_TPTABLE_FLAG_SYNC_SWITCH_IN, P4_TPT- ABLE_FLAG_SYNC_SWITCH_OUT, P4_TPTABLE_FLAG_SYNC_PRE_FLUSH, P4_TPT- ABLE_FLAG_SYNC_POST_FLUSH are only allowed as part of an entry if strong synchronization (UK_TPS_STRONG_SYNC) is enabled. Note that this function is normally limited to privileged software: loading a new time partition table while the system is running in a time partition schema different from the default one may lead to races with the previous time partition switching.

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TIMEPART_SETUP enabled. P4_E_STATE if a time partition schema switch is currently in progress. P4_E_INVAL if entries is zero, or if table is NULL, or if table points to an invalid user space region. P4_E_SIZE if the number of entries entries is too large to fit in the table. P4_E_PAGEFAULT if the new time partition table table is not fully mapped in the callers address space. P4_E_PERM if the new time partition table contains invalid entries.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

278 The PikeOS Kernel API

1.19.6.2 p4_timepart_switch

Switch time partition schema to the schema specified in a set of time partition window tables.

Synopsis:

P4_e_t p4_timepart_switch(const P4_timepart_wtable_t *wtable_list, P4_uint32_t entries, P4_cpuid_t sync_cpu, P4_uint32_t flags)

Parameters: wtable_list IN: Pointer to time partition window table list in user space. Must be a valid user space pointer (or NULL when switching to the default time partition schema). entries IN: Number of entries in the wtable_list. Must be in range [1 .. P4_NUM_CPU] (or 0 when switching to the default time partition schema). sync_cpu IN: Synchronization CPU for the time partition switching. Must be in range [0 .. P4_NUM_CPU - 1] (or P4_NUM_CPU when switching to the default time partition schema). flags IN: Flags field controlling the operation.

           • P4_TIMEPART_SWITCH_IMMEDIATE: request immediate time partition schema switch.
           • P4_TIMEPART_SWITCH_MAJOR: defers the switch to the next major time switch. This flag can
             only be used if UK_TPS_STRONG_SYNC is enabled (stong synchronization).
             The flags are mutually exclusive, and there is no default. One of the flags must be set.

Description: Switch time partition schema to the set of time partition window tables specified in wtable_list. The group of time partition window tables corresponds to a time partition schema as specified in the configuration. Before switching time partition schema, a time partition table must be loaded in the kernel using p4_timepart_load() (see section 1.19.6.1). At boot time, the system executes in a default time partition schema with "infinite" duration (i.e., no time partition switches are enforced). Switching to the default time partition schema (e.g., after having performed a switch to a different schema) is pos- sible with the following parameters combination: wtable_list = NULL, entries = 0, and sync_cpu = P4_NUM_CPU. A schema may define window tables with different time partition windows on different CPUs. All the window tables in a schema must share the same "Major Time Frame," i.e., the sum of the duration of the windows in a table must be equal on all CPUs in the schema. Although discouraged due to the induced time-partition interference, multiple schemes on different CPUs (with different major frames) may overlap in time. Each entry of the list (up to entries, with entries at most P4_NUM_CPU) is of type P4_timepart_wtable_t: each entry specifies a set of windows (identified by first and last indexes), and a cpumask that is common to all the window in that entry. On all the CPUs identified by the union of the cpumask in all the entries (all the CPUs in a schema), the time partition scheduling is activated in the sub range denoted by first and last. The kernel starts switching at first and switches to all consecutive entries until it reaches last. The successor entry of last will be first again (wrap around).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Time Partition API 279

NOTE: first and last may identify different time partitions in different entries, but the sum of the duration of all the windows in a window table ("Major Time Frame"), should be the same for all the entries specified in entries (i.e., different CPUs in a schema may have different "minor time frames", but they must share the same "major time frame"). When switching to a schema different from the default one, the P4_TIMEPART_SWITCH_IMMEDIATE or P4_TIMEPART_SWITCH_MAJOR flags specify the requested switch type: if P4_TIMEPART_SWITCH_IMME- DIATE is specified in flags, the time partitioning is started (the sub range first - last is activated) immediately (at the next tick). In this case P4_TIMEPART_SWITCH_MAJOR is specified in flags, the time partitioning is started in a deferred fashion at the next major time frame. Note that, since the default time partition schema does not have an associated "major time frame", switching to a schema different from the default one should make use of the P4_TIMEPART_SWITCH_IMMEDIATE flag. The time partition schema switch is synchronized to the CPU defined by sync_cpu. If the PSP callback tp_sync() is defined, the callback will be invoked on the sync_cpu upon initialization (refer to the PSP development guide for more information).

Note: On SMP systems, while a time partition switch is in-progress (on a different CPU) it is not possible to initiate a time partition switch. This call will return P4_E_STATE in this case.

Note: Immediate switching to a different time partition schema may introduce partition interference on other concurrently running CPUs.

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. When switching to the default time partition schema, only P4_E_OK or P4_E_NOABILITY may be returned as error codes. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TIMEPART_SETUP enabled. P4_E_INVAL if not exactly one of P4_TIMEPART_SWITCH_IMMEDIATE or P4_TIMEPART_SWITCH_MA- JOR is set in flags. P4_E_INVAL if P4_TIMEPART_SWITCH_MAJOR is specified in flags, but stong synchronization (UK_TPS_STRONG_SYNC) is not enabled. P4_E_INVAL if an invalid flag is set in flags. P4_E_INVAL if entries is zero, or wtable_list is NULL. P4_E_INVAL if wtable points to an invalid user space region. P4_E_INVAL if first or last indices in any of the wtable_list entries are invalid. P4_E_INVAL if the cpu_mask in any of the wtable_list entries exceeds the available number of CPUs. P4_E_INVAL if the union of the cpu_mask specified in all the wtable_list entries do not completly cover all the available CPUs. P4_E_INVAL if sync_cpu exceeds the number of available CPUs. P4_E_SIZE if entries is greater than P4_NUM_CPU. P4_E_NOENT if the time partition table is empty. P4_E_PAGEFAULT if the new window table list wtable_list is not fully mapped in the callers address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

280 The PikeOS Kernel API

P4_E_STATE if a time partition window switch is already taking place.

                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Time Partition API 281

1.19.6.3 p4_fast_timepart_switch_disable

Disable time partition switching on current processor.

Synopsis:

P4_e_t p4_fast_timepart_switch_disable(P4_prio_t newprio)

Parameters: newprio IN: New priority. Invalid or too high priorities are limited to the callers task MCP.

Description: A call to this function disables the next time partition switch and extends the current time partition window until switching is enabled again. Additionally, this function sets the current threads priority to newprio. P4_PRIO_KEEP, P4_PRIO_INHERIT, invalid priorities, or priorities larger than the callers tasks MCP result in setting the priority to the callers tasks MCP.

Returns: Upon success, a call to this function returns P4_E_OK, otherwise the following error code will be returned, and the priority of the caller will not be modified. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TIMEPART_EN- ABLE_DISABLE enabled. P4_E_STATE if a time partition schema change is currently in progress.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

282 The PikeOS Kernel API

1.19.6.4 p4_fast_timepart_switch_enable

Enable time partitioning switching on current processor.

Synopsis:

P4_e_t p4_fast_timepart_switch_enable(P4_prio_t newprio)

Parameters: newprio IN: New priority. Invalid or too high priorities are limited to the callers task MCP.

Description: A call to this function enables time partition switching again after it was disabled by p4_fast_timepart_switch_disable() (see section 1.19.6.3). A pending time partition switch interrupt is im- mediately handled and leads to activation of the next time partition window. Additionally, this function sets the current threads priority to newprio. P4_PRIO_KEEP, P4_PRIO_INHERIT, invalid priorities, or priorities larger than the callers tasks MCP result in setting the priority to the callers tasks MCP.

Returns: Upon success, a call to this function returns P4_E_OK, otherwise the following error code will be returned. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TIMEPART_EN- ABLE_DISABLE enabled.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Time Partition API 283

1.19.6.5 p4_timepart_window_get_attr

Retrieve the attributes of the currently active time partition window on a processor.

Synopsis:

P4_e_t p4_timepart_window_get_attr(P4_cpuid_t cpuid, P4_timepart_window_attr_t *attr_p)

Parameters: cpuid IN: ID of the processor for which the current time partition window attributes shall be retrieved or P4_CPU_MYSELF for the callers processor. attr_p OUT: Pointer to a time partition window attribute structure Upon successful completion, the structure referenced by attr_p will contain the attributes of the currently active time partition window on the given processor. A NULL pointer indicates that the attributes should not be retrieved.

Description: This function retrieves the attributes of the currently active time partition window on processor cpuid. For security reasons, access on information is limited to the processors enabled in the callers task CPU mask. Specifying a processor other than the current CPU requires the P4_AB_TIMEPART_CHANGE ability. For a detailed description of the task attribute structure, refer to the documentation of P4_timepart_window_attr_t.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if cpuid references an invalid processor. P4_E_INVAL if attr_p is not a valid address or exceeds the callers virtual address space. P4_E_PERM if the referenced processor is not available for the caller. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel is not fully mapped in the callers virtual address space. P4_E_NOABILITY The caller is attempting to retrieve the attributes of a different CPU than its current CPU and the caller does not have the ability P4_AB_TIMEPART_CHANGE enabled.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

284 The PikeOS Kernel API

1.20 Thread Local Storage

This section describes constants, data types, access macros, and service functions related to the PikeOS TLS (thread local storage) API.

1.20.1 Structure Definitions

1.20.1.1 struct P4_tls_area_str

TLS (thread local storage) area required layout. The following data structure describes the required layout of the thread local storage memory area. The PikeOS kernel and PikeOS service calls access various entries defined in this structure. Beyond these entries, remaining space is free for application purposes.

Note: To extend the thread local storage area with user defined entries, include the required P4_tls_area_t structure at the beginning of another data structure. Refer to p4_tls_get_uint8() (see section 1.20.3.4), p4_tls_get_uint16() (see section 1.20.3.5), p4_tls_get_uint32() (see section 1.20.3.6), p4_tls_get_uint64() (see section 1.20.3.7), p4_tls_get_ptr() (see section 1.20.3.8), p4_tls_set_uint8() (see section 1.20.3.9), p4_tls_set_uint16() (see section 1.20.3.10), p4_tls_set_uint32() (see section 1.20.3.11), p4_tls_set_uint64() (see section 1.20.3.12), and p4_tls_set_ptr() (see section 1.20.3.13) how to access data in the thread local storage area.

Note: Refer to p4_tls_init() (see section 1.20.3.14), p4_tls_register() (see section 1.20.3.2), and p4_thread_create_syscall() (see section 1.16.5.1) how to initialize and register the thread local storage area.

Note: Refer to the PikeOS User Manual for an example of the setup of a thread local storage area.

Synopsis: struct P4_tls_area_str { void * tls_self; P4_uid_t uid; P4_uint8_t uprio; P4_uint8_t kprio; P4_uint8_t cpuid; P4_uint8_t timepart; P4_rulock_t * rulock_trying; P4_rulock_list_elem_t rulock_list; P4_uint32_t rulock_count; P4_uint32_t error; void * preempt_handler; void * preempt_stack; P4_regs_t * preempt_regs; P4_cpureg_t preempt_flags; void * sysemu_handler; void * sysemu_stack;

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 285

  P4_regs_t * sysemu_regs;
  P4_cpureg_t sysemu_flags;
  void * except_handler;
  void * except_stack;
  P4_regs_t * except_regs;
  P4_cpureg_t except_flags;
  P4_uint32_t error_domain;
  P4_hm_type_t error_type;
  P4_uint32_t error_id;
  P4_uint32_t error_code;
  void * error_msg;
  P4_uint32_t error_msg_size;
  P4_uint32_t unused;

};

Structure Element Description: tls_self Pointer to the memory area used for thread local storage. On some architectures, the thread local storage area can be accessed with indirect read and write operations, but the address of the thread local storage area itself cannot be determined. uid The UID of the associated thread.

       Note:
       The kernel initializes this field with the related threads UID and updates it whenever the threads time
       partition changes.
 uprio Current user priority.

       Note:
       The kernel initializes this field with the related threads scheduling priority and updates it whenever the
       priority changes or on scheduling the related thread. User code can change the scheduling priority
       within the limit of its tasks MCP by updating this field. The kernel checks uprio on scheduling decisions
       and updates kprio accordingly.
 kprio Current kernel priority.

       Note:
       The kernel initializes this field with the related threads scheduling priority and updates it whenever the
       priority changes or on scheduling the related thread. The priority in kprio reflects the kernels assumption
       of the threads scheduling priority.
 cpuid Current processor ID.

       Note:
       The kernel initializes this field with the related threads processor ID and updates it whenever the thread
       migrates to another processor or on scheduling the related thread.
 timepart Current time partition.

       Note:
       The kernel initializes this field with the related threads time partition ID and updates it whenever the
       thread migrates to another time partition or on scheduling the related thread.
 rulock_trying User space lock a thread tries to acquire or is waiting on.


                                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

286 The PikeOS Kernel API

rulock_list Linked list of user space locks a thread has already locked. rulock_count Number of entries in the list error Error code.

    Note:
    A C environment may use this entry to maintain a thread specific errno implementation.

preempt_handler Preemption handler entry point.

    Note:
    If not NULL, preempt_handler is invoked by the preemption handling mechanism when the associated
    thread is preempted via p4_thread_preempt() (see section 1.16.5.12). During execution of the handler,
    the threads scheduling priority is elevated to the related tasks MCP.
    The preemption handlers arguments are a pointer to the user mode context and the previous priority,
    i.e.,
    void handler(P4_regs_t *regs, P4_prio_t oldprio);

preempt_stack Preemption handling stack.

    Note:
    preempt_stack defines the stack to use during preemption handling. If preempt_stack is NULL, the
    threads current stack is used.

preempt_regs Preemption handling register save area.

    Note:
    If not NULL, preempt_regs defines the register save area where the current threads registers are stored
    during an preemption. If preempt_regs is NULL, the threads registers are saved on the new stack
    defined by preempt_stack.

preempt_flags Preemption handling flags.

    Note:
    Set of bits used to further control the execution state of the invoked preemption handler. Currently, the
    following flag bits are defined:

       • P4_THREAD_ARG_FPU
         If set, the FPU will be initialised to default settings and the use of the FPU will be enabled for the
         preemption handler.
       • P4_THREAD_ARG_VEC
            If set, the vector unit will be initialised to default settings and the use of the vector unit will be
            enabled for the preemption handler.

sysemu_handler SYSEMU return handler entry point.

    Note:
    sysemu_handler is invoked on return from SYSEMU state: the previous register context is saved in
    sysemu_regs and the threads scheduling priority is elevated to the tasks MCP. sysemu_handler must
    not be set to NULL when SYSEMU is used.
    The handlers arguments are a pointer to the previous register context and the previous priority, i.e.,


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 287

     void handler(P4_regs_t *regs, P4_prio_t oldprio);

sysemu_stack SYSEMU return stack.

     Note:
     sysemu_stack defines the stack to use upon return from SYSEMU state. sysemu_stack must not be
     set to NULL when SYSEMU is used.

sysemu_regs SYSEMU register save area.

     Note:
     If not NULL, sysemu_regs defines the register save area where the previous register context is stored
     upon return from SYSEMU state. If sysemu_regs is NULL, the previous register context is saved on the
     SYSEMU return stack defined by sysemu_stack.
     If a page fault occurs when accessing sysemu_regs or the registers on a register frame created on the
     stack, the associated thread will raise an exception of type P4_TRAP_CTXT.

sysemu_flags SYSEMU flags.

     Note:
     Set of bits used to further control the execution state of the invoked SYSEMU return handler. Currently,
     the following flag bits are defined:

        • P4_THREAD_ARG_FPU
          If set, the FPU will be initialised to default settings and the use of the FPU will be enabled for the
          handler.
        • P4_THREAD_ARG_VEC
             If set, the vector unit will be initialised to default settings and the use of the vector unit will be
             enabled for the handler.

except_handler Exception handler entry point.

     Note:
     If not NULL, except_handler is invoked by the TLS-based exception handling mechanism when the
     associated thread generates an exception. During execution of the handler, the threads scheduling
     priority is elevated to the related tasks MCP.
     The exception handlers arguments are a pointer to the user mode context and the previous priority, i.e.,
     void handler(P4_regs_t *regs, P4_prio_t oldprio);

except_stack Exception handling stack.

     Note:
     except_stack defines the stack to use during exception handling. If except_stack is NULL, the threads
     current stack is used.

except_regs Exception handling register save area.

     Note:
     If not NULL, except_regs defines the register save area where the current threads registers are stored
     during an exception. If except_regs is NULL, the threads registers are saved on the new stack defined
     by except_stack.


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

288 The PikeOS Kernel API

except_flags Exception handling flags.

     Note:
     Set of bits used to further control the execution state of the invoked exception handler. Currently, the
     following flag bits are defined:


         • P4_THREAD_ARG_FPU
             If set, the FPU will be initialised to default settings and the use of the FPU will be enabled for the
             exception handler.
         • P4_THREAD_ARG_VEC
             If set, the vector unit will be initialised to default settings and the use of the vector unit will be
             enabled for the exception handler.

error_domain Error domain that reported an error

     Note:
     The kernel health monitor will set the error domain to the domain that reported the error.

error_type Type of the error id

     Note:
     The kernel health monitor sets the type of the error id to one of the values specified in the P4_hm_type_t
     type.

error_id Error identifier

     Note:
     The kernel health monitor will set the reported error identifier.

error_code Error code

     Note:
     The kernel health monitor will set the error code defined in the HM table for the respective error id.

error_msg Error message

     Note:
     If not NULL, the kernel health monitor will write the error message passed into the HM to the specified
     user space address.

error_msg_size Error message size

     Note:
     The kernel health monitor will write the size of the error message if error_msg is not NULL

unused

Associated Data Type

P4_tls_area_t TLS (thread local storage) area required layout.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 289

1.20.2 Data Type Definitions

P4_tls_area_t TLS (thread local storage) area required layout. The following data structure describes the required layout of the thread local storage memory area. The PikeOS kernel and PikeOS service calls access various entries defined in this structure. Beyond these entries, remaining space is free for application purposes.

      Note:
      To extend the thread local storage area with user defined entries, include the required P4_tls_area_t
      structure at the beginning of another data structure.
      Refer to p4_tls_get_uint8() (see section 1.20.3.4), p4_tls_get_uint16() (see section 1.20.3.5),
      p4_tls_get_uint32() (see section 1.20.3.6), p4_tls_get_uint64() (see section 1.20.3.7), p4_tls_get_ptr()
      (see section 1.20.3.8), p4_tls_set_uint8() (see section 1.20.3.9), p4_tls_set_uint16() (see section
      1.20.3.10), p4_tls_set_uint32() (see section 1.20.3.11), p4_tls_set_uint64() (see section 1.20.3.12), and
      p4_tls_set_ptr() (see section 1.20.3.13) how to access data in the thread local storage area.

      Note:
      Refer to p4_tls_init() (see section 1.20.3.14), p4_tls_register() (see section 1.20.3.2), and
      p4_thread_create_syscall() (see section 1.16.5.1) how to initialize and register the thread local stor-
      age area.

      Note:
      Refer to the PikeOS User Manual for an example of the setup of a thread local storage area.


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

290 The PikeOS Kernel API

1.20.3 Functions

1.20.3.1 p4_thread_tls_register

Register TLS (thread local storage) area in register context.

Synopsis:

void p4_thread_tls_register(P4_regs_t *regs, const void *tls)

Parameters: regs OUT: User mode context. tls IN: Memory area for thread local storage.

Description: This function registers the memory area tls as thread local storage in register context regs. As described in PikeOS User Manual (Initialization of Thread Local Storage), the usage of p4_tls_init() (see section 1.20.3.14) and p4_tls_register() (see section 1.20.3.2), or alternatively, the usage of p4_tls_init() (see section 1.20.3.14) and p4_thread_create_syscall() (see section 1.16.5.1) is the preferred way of initializing and registering the TLS in the register context. Since this call is implemented as a user library function and involves no kernel activity, the usage of p4_tls_register() (see section 1.20.3.2) or p4_thread_create_syscall() (see section 1.16.5.1) should be preferred over the use of p4_thread_tls_register() (see section 1.20.3.1): values defined in the user mode context refer- ring to the thread local storage by this function will be overwritten by a call to either p4_tls_register() (see section 1.20.3.2) or p4_thread_create_syscall() (see section 1.16.5.1).

Note: Since this call works on a saved user mode context, it can not be used by a thread to register its own thread local storage.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 291

1.20.3.2 p4_tls_register

Register TLS (thread local storage) area of calling thread.

Synopsis:

P4_e_t p4_tls_register(void *tls)

Parameters: tls IN: Memory area for thread local storage, assumed to be of type P4_tls_area_t.

Description: This function registers the memory area tls as thread local storage for the calling thread. Setting tls to NULL unregisters thread local storage. If tls is not NULL, the kernel initializes the following fields of the thread local storage area, assuming a P4_tls_area_t type:

• uid,
• uprio,
• kprio,
• cpuid, and
• timepart.
    This call overrides any value previously defined in the user mode context referring to the thread local storage
    area set by p4_thread_tls_register() (see section 1.20.3.1).

Note: The structure of the thread local storage area must match the layout of P4_tls_area_t, as the kernel accesses various entries.

Note: Refer to PikeOS User Manual (Initialization of Thread Local Storage) for additional information about the initializa- tion and extension of the TLS area.

Note: The valid mapping of tls into the callers virtual address space is tested before accessing the upper fields in the thread local storage area for the initialization and will result in a pagefault, if the access for one of these fields fails. These tests during registration ensure a proper mapping of the fields relevant for the initialization and access during normal operations by the kernel. But they do not prevent subsequent manipulation of the tls memory mapping, which will be tested by each accessing functionality for the relevant fields again.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if tls does not point to a valid address or exceeds the callers virtual address space. P4_E_ALIGN if tls is not properly aligned. P4_E_PAGEFAULT if the field access for the initialization of tls with size P4_tls_area_t fails, because one of the fields is not properly mapped in the callers virtual address space.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

292 The PikeOS Kernel API

1.20.3.3 p4_tls_ptr

Get pointer to TLS (thread local storage) area of calling thread.

Synopsis:

void* p4_tls_ptr(void)

Description: This function returns a pointer to the callers thread local storage area. On some architectures, the thread local storage pointer can be addressed only indirectly using the first entry at the beginning of the thread local storage area of type P4_cpureg_t.

Returns: This function returns a pointer to the callers thread local storage area.

Note: If the threads local storage area is uninitialized or the first entry in the local storage area is not the size of a pointer that does not refer to the thread local storage area itself, using this function may cause an exception or the result is undefined.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 293

1.20.3.4 p4_tls_get_uint8

Read 8-bit value from TLS (thread local storage) area of calling thread.

Synopsis:

P4_uint8_t p4_tls_get_uint8(P4_size_t offset)

Parameters: offset IN: Byte offset within thread local storage area.

Description: This function reads an 8-bit sized value from offset offset of the calling threads local storage area.

Returns: This function returns the 8-bit sized value at offset offset from the calling threads local storage area.

Note: If the threads local storage area is uninitialized or offset exceeds the areas limits, using this function may cause an exception.

Note: The recommended way to access an 8-bit value "z" from a thread local storage area of type "struct y" is: P4_uint8_t x = p4_tls_get_uint8(p4_offsetof(struct y, z));

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

294 The PikeOS Kernel API

1.20.3.5 p4_tls_get_uint16

Read 16-bit value from TLS (thread local storage) area of calling thread.

Synopsis:

P4_uint16_t p4_tls_get_uint16(P4_size_t offset)

Parameters: offset IN: Byte offset within thread local storage area.

Description: This function reads a 16-bit sized value from offset offset of the calling threads local storage area.

Returns: This function returns the 16-bit sized value at offset offset from the calling threads local storage area.

Note: If the threads local storage area is uninitialized or offset exceeds the areas limits, using this function may cause an exception.

Note: The recommended way to access a 16-bit value "z" from a thread local storage area of type "struct y" is: P4_uint16_t x = p4_tls_get_uint16(p4_offsetof(struct y, z));

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 295

1.20.3.6 p4_tls_get_uint32

Read 32-bit value from TLS (thread local storage) area of calling thread.

Synopsis:

P4_uint32_t p4_tls_get_uint32(P4_size_t offset)

Parameters: offset IN: Byte offset within thread local storage area.

Description: This function reads a 32-bit sized value from offset offset of the calling threads local storage area.

Returns: This function returns the 32-bit sized value at offset offset from the calling threads local storage area.

Note: If the threads local storage area is uninitialized or offset exceeds the areas limits, using this function may cause an exception.

Note: The recommended way to access a 32-bit value "z" from a thread local storage area of type "struct y" is: P4_uint32_t x = p4_tls_get_uint32(p4_offsetof(struct y, z));

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

296 The PikeOS Kernel API

1.20.3.7 p4_tls_get_uint64

Read 64-bit value from TLS (thread local storage) area of calling thread.

Synopsis:

P4_uint64_t p4_tls_get_uint64(P4_size_t offset)

Parameters: offset IN: Byte offset within thread local storage area.

Description: This function reads a 64-bit sized value from offset offset of the calling threads local storage area.

Returns: This function returns the 64-bit sized value at offset offset from the calling threads local storage area.

Note: If the threads local storage area is uninitialized or offset exceeds the areas limits, using this function may cause an exception.

Note: The recommended way to access a 64-bit value "z" from a thread local storage area of type "struct y" is: P4_uint64_t x = p4_tls_get_uint64(p4_offsetof(struct y, z));

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 297

1.20.3.8 p4_tls_get_ptr

Read pointer value from TLS (thread local storage) area of calling thread.

Synopsis:

void* p4_tls_get_ptr(P4_size_t offset)

Parameters: offset IN: Byte offset within thread local storage area.

Description: This function reads a pointer from offset offset of the calling threads local storage area.

Returns: This function returns the pointer at offset offset from the calling threads local storage area.

Note: If the threads local storage area is uninitialized or offset exceeds the areas limits, using this function may cause an exception.

Note: The recommended way to access a pointer "z" from a thread local storage area of type "struct y" is: void *x = p4_tls_get_ptr(p4_offsetof(struct y, z));

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

298 The PikeOS Kernel API

1.20.3.9 p4_tls_set_uint8

Set 8-bit value to TLS (thread local storage) area of calling thread.

Synopsis:

void p4_tls_set_uint8(P4_size_t offset, P4_uint8_t value)

Parameters: offset IN: Byte offset within thread local storage area. value IN: Value to store in thread local storage area.

Description: This function writes an 8-bit sized value at offset offset of the calling threads local storage area.

Note: If the threads local storage area is uninitialized or offset exceeds the areas limits, using this function may cause an exception.

Note: The recommended way to access an 8-bit value "z" from a thread local storage area of type "struct y" is: p4_tls_set_uint8(p4_offsetof(struct y, z), 42);

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 299

1.20.3.10 p4_tls_set_uint16

Set 16-bit value to TLS (thread local storage) area of calling thread.

Synopsis:

void p4_tls_set_uint16(P4_size_t offset, P4_uint16_t value)

Parameters: offset IN: Byte offset within thread local storage area. value IN: Value to store in thread local storage area.

Description: This function writes a 16-bit sized value at offset offset of the calling threads local storage area.

Note: If the threads local storage area is uninitialized or offset exceeds the areas limits, using this function may cause an exception.

Note: The recommended way to access a 16-bit value "z" from a thread local storage area of type "struct y" is: p4_tls_set_uint16(p4_offsetof(struct y, z), 42);

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

300 The PikeOS Kernel API

1.20.3.11 p4_tls_set_uint32

Set 32-bit value to TLS (thread local storage) area of calling thread.

Synopsis:

void p4_tls_set_uint32(P4_size_t offset, P4_uint32_t value)

Parameters: offset IN: Byte offset within thread local storage area. value IN: Value to store in thread local storage area.

Description: This function writes a 32-bit sized value at offset offset of the calling threads local storage area.

Note: If the threads local storage area is uninitialized or offset exceeds the areas limits, using this function may cause an exception.

Note: The recommended way to access a 32-bit value "z" from a thread local storage area of type "struct y" is: p4_tls_set_uint32(p4_offsetof(struct y, z), 42);

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 301

1.20.3.12 p4_tls_set_uint64

Set 64-bit value to TLS (thread local storage) area of calling thread.

Synopsis:

void p4_tls_set_uint64(P4_size_t offset, P4_uint64_t value)

Parameters: offset IN: Byte offset within thread local storage area. value IN: Value to store in thread local storage area.

Description: This function writes a 64-bit sized value at offset offset of the calling threads local storage area.

Note: If the threads local storage area is uninitialized or offset exceeds the areas limits, using this function may cause an exception.

Note: The recommended way to access a 64-bit value "z" from a thread local storage area of type "struct y" is: p4_tls_set_uint64(p4_offsetof(struct y, z), 42);

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

302 The PikeOS Kernel API

1.20.3.13 p4_tls_set_ptr

Write pointer value to TLS (thread local storage) area of calling thread.

Synopsis:

void p4_tls_set_ptr(P4_size_t offset, void *value)

Parameters: offset IN: Byte offset within thread local storage area. value IN: Value to store in thread local storage area.

Description: This function writes a pointer value at offset offset of the calling threads local storage area.

Note: If the threads local storage area is uninitialized or offset exceeds the areas limits, using this function may cause an exception.

Note: The recommended way to access a pointer "z" from a thread local storage area of type "struct y" is: p4_tls_set_ptr(p4_offsetof(struct y, z), new_value);

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 303

1.20.3.14 p4_tls_init

Initialize a TLS (thread local storage) area data structure.

Synopsis:

void p4_tls_init(P4_tls_area_t *tls)

Parameters: tls OUT: Thread local storage area data structure to initialize.

Description: This function initializes a threads local storage area to default values

Note: This call only sets up tls_self and rulock_list. The remaining values are cleared.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

304 The PikeOS Kernel API

1.20.3.15 p4_tls_uid

Retrieve current threads UID from the TLS (thread local storage) area of calling thread.

Synopsis:

P4_uid_t p4_tls_uid(void)

Description: This function returns the UID of the calling thread.

Returns: Upon success, a call to this function returns the current threads UID.

Note: If the threads local storage area is uninitialized, using this function may cause an exception.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 305

1.20.3.16 p4_tls_thread

Retrieve current threads thread number from the TLS (thread local storage) area of calling thread.

Synopsis:

__forceinline P4_thr_t p4_tls_thread(void)

Description: This function returns the thread number of the calling thread.

Returns: Upon success, a call to this function returns the current threads thread number.

Note: If the threads local storage area is uninitialized, using this function may cause an exception.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

306 The PikeOS Kernel API

1.20.3.17 p4_tls_task

Retrieve current threads task number from the TLS (thread local storage) area of calling thread.

Synopsis:

__forceinline P4_task_t p4_tls_task(void)

Description: This function returns the task number of the calling thread.

Returns: Upon success, a call to this function returns the current threads task number.

Note: If the threads local storage area is uninitialized, using this function may cause an exception.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 307

1.20.3.18 p4_tls_respart

Retrieve current threads resource partition number from the TLS (thread local storage) area of calling thread.

Synopsis:

__forceinline P4_uint32_t p4_tls_respart(void)

Description: This function returns the resource partition of the calling thread.

Returns: Upon success, a call to this function returns the current threads resource partition.

Note: If the threads local storage area is uninitialized, using this function may cause an exception.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

308 The PikeOS Kernel API

1.20.3.19 p4_tls_timepart

Retrieve current threads time partition number from the TLS (thread local storage) area of calling thread.

Synopsis:

P4_uint32_t p4_tls_timepart(void)

Description: This function returns the time partition of the calling thread.

Returns: Upon success, a call to this function returns the current threads time partition.

Note: If the threads local storage area is uninitialized, using this function may cause an exception.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 309

1.20.3.20 p4_tls_prio

Retrieve the threads priority from the TLS (thread local storage) area of calling thread.

Synopsis:

P4_prio_t p4_tls_prio(void)

Description: This function retrieves the threads priority.

Returns: Upon success, a call to this function returns the current threads priority.

Note: If the threads local storage area is uninitialized, using this function may cause an exception.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

310 The PikeOS Kernel API

1.20.3.21 p4_tls_change_prio

Set the current threads priority in the TLS (thread local storage) area of calling thread.

Synopsis:

P4_prio_t p4_tls_change_prio(P4_prio_t new_prio)

Parameters: new_prio IN: New priority. Invalid or too high priorities are limited to the callers task MCP.

Description: This function sets the current threads priority to new_prio. The function immediately set new_prio in the TLS area of the calling thread, but the priority may be synchronized with the kernel in a later point in time (point of synchronization). Invalid or too high priorities are effectively limited to the callers task MCP, but the capping do not become visible until the point of synchronization.

Returns: Upon success, a call to this function returns the current threads previously set priority before setting it to new_prio. If the point of synchronization has not been yet reached, the returned priority may be higher than the threads effective one.

Note: If the threads local storage area is uninitialized, using this function may cause an exception.

Note: The effective priority of the thread may be retrieved with e.g., p4_fast_get_prio() (see section 1.9.5.12) or p4_thread_get_priority() (see section 1.16.5.19).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Local Storage 311

1.20.3.22 p4_tls_sync_prio

Synchronize the current threads user space scheduling data with the kernel.

Synopsis:

void p4_tls_sync_prio(void)

Description: This function synchronizes the current threads user space priority with the kernel priority. Invalid or too high priorities are limited to the callers task MCP (the possible capping is immediately enacted in the effective priority of the thread). In the case of MCP priority capping, the current threads user space priority (retrieved with e.g., p4_tls_prio() (see section 1.20.3.20)) may not reflect the effective thread priority after the synchronization. This behavior is intended.

Note: The effective priority of the thread may be retrieved with e.g., p4_fast_get_prio() (see section 1.9.5.12) or p4_thread_get_priority() (see section 1.16.5.19).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

312 The PikeOS Kernel API

1.20.3.23 p4_tls_cpuid

Retrieve the threads current CPU ID from the TLS (thread local storage) area of calling thread.

Synopsis:

P4_cpuid_t p4_tls_cpuid(void)

Description: This function retrieves the ID of the threads current processor.

Returns: Upon success, a call to this function returns the current threads processor ID.

Note: If the threads local storage area is uninitialized, using this function may cause an exception.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Level Device Drivers 313

1.21 Kernel Level Device Drivers

This section describes all constants, data types, access macros, and service calls related to the PikeOS kernel level device driver API.

1.21.1 Structure Definitions

1.21.1.1 struct P4_device_bitmap_str

Device bitmap structure. The device bitmap is used to store and communicate the set of devices granted to a task. The bitmap contains one bit for every device number (0 ... P4_NUM_DEVICE-1) where the device number is reflected in the bit position within the bitmap and the attribute value is given by the bit value. The device bitmap structure is to be treated as an opaque data type and should only be accessed by the macros P4_DEV_GET_BIT() (see section 1.21.2) and P4_DEV_SET_BIT() (see section 1.21.2).

Synopsis: struct P4_device_bitmap_str { unsigned long m[...]; };

Structure Element Description: m Storage for bitmap.

Associated Data Type

P4_device_bitmap_t Device bitmap structure.

1.21.2 Defines

P4_NUM_DEVICE Number of devices handled by the kernel. Description: The kernel is able to handle a maximum number of P4_NUM_DEVICE kernel level devices.

P4_DEV_GET_BIT (dbm_p, num) This macro tests, whether the bit for device num is set in the device bitmap pointed to by dbm_p.

        Parameters:
            dbm_p Pointer to the device bitmap to be tested.
            num Device number (0 ... P4_NUM_DEVICE-1).
        Returns:
        TRUE if the bit is set, FALSE otherwise.

        Note:
        If num is not a valid device number the return value is undefined.


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

314 The PikeOS Kernel API

P4_DEV_SET_BIT (dbm_p, num) This macro sets the bit for the device number given by num in the device bitmap pointed to by dbm_p.

      Parameters:
          dbm_p Pointer to the device bitmap.
          num Device number (0 ... P4_NUM_DEVICE-1).
      Note:
      If num is not a valid device number the effects of this macro are undefined.

P4_DEV_FILL_SET (dbm_p) Initialise device bitmap with all bits set. Description: This macro fills the device bitmap pointed to by dbm_p, i.e. all device rights will be set (enabled).

      Parameters:
          dbm_p Pointer to the device bitmap.

P4_DEV_CLEAR_SET (dbm_p) Initialise device bitmap with all bits cleared. Description: This macro clears the device bitmap pointed to by dbm_p, i.e. all device rights will be cleared (disabled).

      Parameters:
          dbm_p Pointer to the device bitmap.

1.21.3 Data Type Definitions

P4_device_bitmap_t Device bitmap structure. The device bitmap is used to store and communicate the set of devices granted to a task. The bitmap contains one bit for every device number (0 ... P4_NUM_DEVICE-1) where the device number is reflected in the bit position within the bitmap and the attribute value is given by the bit value. The device bitmap structure is to be treated as an opaque data type and should only be accessed by the macros P4_DEV_GET_BIT() (see section 1.21.2) and P4_DEV_SET_BIT() (see section 1.21.2).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Level Device Drivers 315

1.21.4 Functions

1.21.4.1 p4_dev_grant

Grant the right to access a set of PSP-level devices to another task.

Synopsis:

P4_e_t p4_dev_grant(P4_task_t task, const P4_device_bitmap_t *dev_map_p)

Parameters: task IN: Number of the task which shall receive the PSP-level device access permission. dev_map_p IN: Pointer to device bitmap.

Description: A call to this function grants the right to acess a PSP-level device to another task. The parameter dev_map_p points to a device bitmap, and the parameter task specifies the destination task number, which must be an active child task of the calling task. A set bit in the bitmap indicated that the corresponding device access permission shall be granted. The calling thread must have the permission to access this device. The permission still remains in the calling task. The permission cannot be revoked, except by killing the receiving child task.

Note: PSP-level device drivers are deprecated and their support will be removed in future versions. Consider using KDEV drivers instead.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if dev_map_p is NULL, or if dev_map_p is invalid or exceeds the virtual address space, or if dev_map_p does not point to a valid address in the callers address space, or if task does not refer to a valid task number. P4_E_PAGEFAULT if dev_map_p is not fully mapped in the callers address space. P4_E_BADTASK if task is not a child task of the callers task. P4_E_STATE if task does not exist. P4_E_PERM if dev_map_p has bits set of devices not being granted to the calling task.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

316 The PikeOS Kernel API

1.21.4.2 p4_dev_link

Grant a single PSP-level device access permission to another task.

Synopsis:

P4_e_t p4_dev_link(P4_task_t task, P4_devid_t devid)

Parameters: task IN: Number of the task that shall receive the device access right. devid IN: Number of the device that shall be granted.

Description: A call to this function passes the permission to access a device to another task. The parameter devid must specify a valid device, and the task of the calling thread must have the permission to access this device. The parameter task specifies the destination task number, which must be an active child task of the calling task. The permission still remains in the calling task. The permission cannot be revoked, except by killing the receiving child task.

Note: PSP-level device drivers are deprecated and their support will be removed in future versions. Consider using KDEV drivers instead.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if devid does not refer to a valid device number, or if task does not refer to a valid task number. P4_E_BADTASK if task is not a child task of the calling task. P4_E_STATE if task does not exist. P4_E_PERM if the calling threads task does not have the right to access device devid.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Level Device Drivers 317

1.21.4.3 p4_dev_call

Call a PSP-level device driver.

Synopsis:

P4_e_t p4_dev_call(P4_devid_t devid, P4_uint32_t func, P4_cpureg_t arg1, P4_cpureg_t arg2, P4_cpureg_t arg3, P4_cpureg_t arg4)

Parameters: devid IN: Number of the device that shall be called. func IN: Function arg1 IN: Argument 1 arg2 IN: Argument 2 arg3 IN: Argument 3 arg4 IN: Argument 4

Description: A call to this function calls the PSP-level device drivers devid. The called functionality func is defined by the PSP- level device driver. Up to four arguments arg1, arg2, arg3, and arg4 can be passed to the driver. Interpretation of these arguments and func depends on the PSP-level device driver.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if devid does not refer to a valid device number. P4_E_PERM if the calling threads task does not have the right to access device devid. P4_E_NOENT if the call for device devid is not implemented.

Note: Depending on the arguments passed in, further error codes may be generated by the PSP-level device driver.

Note: PSP-level device drivers are deprecated and their support will be removed in future versions. Consider using KDEV drivers instead.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

318 The PikeOS Kernel API

1.22 Tracing

This section describes all constants, data types, access macros, and service calls related to tracing.

1.22.1 Structure Definitions

1.22.1.1 struct P4_trace_client_str

Trace client attribute structure. The kernel maintains a user visible array of the trace client attributes.

Synopsis: struct P4_trace_client_str { P4_trace_state_t state; P4_uid_t uid; P4_size_t requested_size; P4_size_t status_offset; P4_size_t buffer_offset; P4_size_t buffer_size; char name[P4_NAMELEN]; };

Structure Element Description: state State of the trace client uid UID of the trace client requested_size Requested size of the trace buffer status_offset Address of the trace clients status page buffer_offset Address of the trace clients trace buffer buffer_size Real size of the trace buffer name Trace client name. The name is always a valid C string terminated with a NUL character.

Associated Data Type

P4_trace_client_t Trace client attribute structure.

1.22.1.2 struct P4_trace_info_str

Trace info page structure. The kernel maintains a user visible structure where common and client related trace attributes are saved.

Synopsis: struct P4_trace_info_str { P4_uint32_t signature; P4_trace_mem_state_t state; P4_phys_addr_t phys_base; P4_size_t size; P4_size_t free_offset;

                                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Tracing 319

  P4_size_t param_default_buffer_size;
  P4_size_t param_kernel_buffer_size;
  P4_size_t param_control_size;
  int param_start_kernel_tracing;
  int param_post_mortem;
  P4_size_t default_buffer_size;
  P4_size_t control_offset;
  P4_size_t control_size;
  P4_size_t trigger_offset;
  P4_uid_t server_uid;
  P4_uint32_t max_clients;
  P4_trace_client_t clients[P4_TRACE_MAX_CLIENTS];

};

Structure Element Description: signature Signature, is set to P4_TRACE_INFO_SIGNATURE state Internal state of the trace memory pool phys_base Address of the trace memory pool in bytes (physical address) size Size of the trace memory pool in bytes free_offset Pointer to next free page within trace memory pool param_default_buffer_size Kernel parameter: default size of the trace buffer param_kernel_buffer_size Kernel parameter: size of the kernel trace buffer param_control_size Kernel parameter: size of the trace control page param_start_kernel_tracing Kernel parameter: status of kernel tracing param_post_mortem Kernel parameter: status of post mortem tracing default_buffer_size Default size of the trace buffer control_offset Base address of the trace control page control_size Size of the trace control page trigger_offset Base address of the trigger page server_uid UID of the trace server max_clients Maximum number of clients. clients Client descriptors

Associated Data Type

 P4_trace_info_t Trace info page structure.

1.22.2 Defines

 P4_TRACE_MAX_CLIENTS
      Maximum number of trace clients.

 P4_TRACE_INVALID_ID
      Special trace client ID.

 P4_TRACE_INFO_SIGNATURE
      Trace info page signature.


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

320 The PikeOS Kernel API

1.22.3 Data Type Definitions

P4_traceid_t Trace ID. P4_trace_client_t Trace client attribute structure. The kernel maintains a user visible array of the trace client attributes. P4_trace_info_t Trace info page structure. The kernel maintains a user visible structure where common and client related trace attributes are saved.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Tracing 321

1.22.4 Enumerations

Enumeration type P4_trace_page_t

Trace page type definitions.

Name Description P4_TRACE_INFO Tracer info page (written by kernel)

P4_TRACE_CONTROL Tracer control page (written by server)

P4_TRACE_STATUS Trace clients status page (written by client)

P4_TRACE_BUFFER Trace clients trace buffer pages (written by client)

P4_TRACE_TRIGGER Trace clients trigger page (written by server and client)

Enumeration type P4_trace_state_t

Trace client state definitions.

Name Description P4_TRACE_STATE_NC A trace client is not connected.

P4_TRACE_STATE_REGISTERED A trace client has been registered.

P4_TRACE_STATE_DEAD A trace client was once registered.

Enumeration type P4_trace_mem_state_t

Trace memory pool state definitions.

Name Description P4_TRACE_MEM_OK Trace memory pool is OK, clients may connect.

P4_TRACE_MEM_LOCKED Trace memory pool contains post mortem data, only server may connect.

P4_TRACE_MEM_CORRUPT Trace memory pool is corrupted.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

322 The PikeOS Kernel API

1.22.5 Functions

1.22.5.1 p4_trace_client_register

Register a trace client for tracing.

Synopsis:

P4_e_t p4_trace_client_register(const char *name, P4_traceid_t *id)

Parameters: name IN: If name is not NULL, the kernel will copy P4_NAMELEN bytes starting at name as the tracers name. If the string is longer than or equal to P4_NAMELEN characters, it will be truncated to P4_NAMELEN characters with a NUL character at the end. id OUT: ID of the trace client.

Description: This function registers the calling thread as trace client with the identifier name. The identifier is used to distinguish between different trace clients. A trace client can register itself multiple times for tracing, this concept allows partition restarts without data loss. In case of error codes P4_E_OK and P4_E_STATE, a trace client id is returned in id.

Returns: This function returns one of the following error codes, where P4_E_OK or P4_E_STATE indicate success: P4_E_OK if the thread registers the first time. P4_E_STATE if the thread registers again. P4_E_LIMIT if too many tracers are already registered. P4_E_ABORT if trace memory pool is in post-mortem state P4_E_NOTIMPL if tracing support is disabled. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TRACE enabled. P4_E_INVAL if id or name do not point to a valid address or exceed the callers virtual address space. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel are not fully mapped in the callers virtual address space.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Tracing 323

1.22.5.2 p4_trace_client_unregister

Unregister a trace client for tracing.

Synopsis:

P4_e_t p4_trace_client_unregister(P4_traceid_t id)

Parameters: id IN: ID of the trace client.

Description: A call to this function unregisters the trace client identified by id for tracing.

Note: The trace client with id 0 cannot be unregistered.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if id does not reference a valid trace client. P4_E_ABORT if trace memory pool is in post-mortem state P4_E_NOTIMPL if tracing support is disabled. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TRACE enabled.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

324 The PikeOS Kernel API

1.22.5.3 p4_trace_server_register

Register a trace server for collecting trace data.

Synopsis:

P4_e_t p4_trace_server_register(void)

Description: This function registers the calling thread as trace server. The trace server collects all the trace data from the clients. No more than one trace server may be registered.

Returns: This function returns one of the following error codes, where P4_E_OK, P4_E_STATE or P4_E_BADUID indicate success: P4_E_OK if the thread registers the first time. P4_E_STATE if the thread is already registered as trace server. P4_E_BADUID if trace memory pool is in post-mortem state P4_TRACE_MEM_LOCKED P4_E_ABORT if trace memory pool is in post-mortem state P4_TRACE_MEM_CORRUPT P4_E_LIMIT if another thread is already registered as trace server. P4_E_NOTIMPL if tracing support is disabled. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TRACE enabled.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Tracing 325

1.22.5.4 p4_trace_server_unregister

Unregister the trace server.

Synopsis:

P4_e_t p4_trace_server_unregister(void)

Description: A call to this function unregisters the calling thread as trace server.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if the calling thread was not registered as trace server. P4_E_ABORT if trace memory pool is in post-mortem state P4_E_NOTIMPL if tracing support is disabled. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TRACE enabled.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

326 The PikeOS Kernel API

1.22.5.5 p4_trace_set_bufsize

Set size of a trace clients buffer.

Synopsis:

P4_e_t p4_trace_set_bufsize(P4_traceid_t id, P4_size_t size)

Parameters: id IN: ID of the trace client. size IN: New buffer size.

Description: A call to this function sets the size of the trace buffer of client id to size, which must be a multiple of P4_PAGESIZE. To set the default value of for trace client, use P4_TRACE_INVALID_ID as id.

Note: This call is restricted to the trace server.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if the calling thread was not registered as trace server, or if id does not reference a valid trace client, or if size is not a multiple of P4_PAGESIZE. P4_E_ABORT if trace memory pool is in post-mortem state P4_E_NOTIMPL if tracing support is disabled. P4_E_STATE if the buffer size cannot be changed. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TRACE enabled.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Tracing 327

1.22.5.6 p4_trace_map

Map special trace pages to the callers task address space.

Synopsis:

P4_e_t p4_trace_map(P4_trace_page_t type, P4_traceid_t id, P4_address_t addr, P4_size_t size, P4_size_t *realsize, P4_size_t *map_offs)

Parameters: type IN: Type of page to map. id IN: ID of the trace client. addr IN: Destination address in callers address space. The value must be a multiple of P4_PAGESIZE. size IN: Size of the maximum accepted trace buffer. The value must be non-zero and a multiple of P4_PA- GESIZE. realsize OUT: realsize contains the actually mapped size in the destination area. If NULL, no size will be returned. map_offs OUT: map_offs contains the mapping offset within in the destination area. If NULL, no offset will be returned.

Description: This function maps pages containing trace information described by type and id to the callers address space to address addr with a maximum size of size. The destination area must be a valid user space region. In realsize the size of actually mapped pages is returned. Depending on the architecture, the mapping is automatically aligned and moved by the kernel to fulfill architecture specific requirements. This offset is returned in map_offs. Older mappings in the destination area will not be overwritten. In case of error codes P4_E_NOKMEM or P4_E_OVERMAP, only a partial mapping of size realsize was installed in the destination area. In case of error codes P4_E_NOABILITY, P4_E_INVAL, P4_E_STATE or P4_E_NOTIMPL no mapping was installed at all. In case of error code P4_E_SIZE, no mapping is installed because the destination area is too small. The sum of map_offs and realsize is the space needed.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if type does not refer to a valid page type, or if id does not reference a valid trace client, or if addr or size are not multiples of P4_PAGESIZE, or if size is zero, or if addr and size do not describe a valid memory area in the callers virtual address space, or if realsize or map_offs are not NULL and do not point to a valid address or exceed the callers virtual address space.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

328 The PikeOS Kernel API

P4_E_PAGEFAULT if realsize or map_offs are not NULL and are not fully mapped in the callers virtual address space. P4_E_SIZE if the destination area is not large enough to apply the mapping. P4_E_STATE if the client is in an invalid state. P4_E_NOKMEM if there is not enough kernel memory available in the resource partition of the callers task to apply the mapping. P4_E_LIMIT if there is not enough trace memory availabile. P4_E_OVERMAP if the destination area already contains a mapping. P4_E_ABORT if trace memory pool is in post-mortem state P4_E_NOTIMPL if tracing support is disabled. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TRACE enabled.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Tracing 329

1.22.5.7 p4_trace_reset

Reset post-mortem state.

Synopsis:

P4_e_t p4_trace_reset(void)

Description: A call to this function cleans the trace memory pool and resets all post-mortem states. This call is restricted to the trace server. On a successful call, the trace server is unregistered.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if the calling thread was not registered as a trace server. P4_E_ABORT if trace memory pool is not in a post-mortem state P4_E_NOTIMPL if tracing support is disabled. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_TRACE enabled.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

330 The PikeOS Kernel API

1.23 Monitoring

This section describes all constants, data types, access macros, and service calls related to system monitoring. 1 The module p4_monitor defines the service calls related to the PikeOS System Monitor API.

1.23.1 Structure Definitions

1.23.1.1 struct P4_thread_bitmap_str

Thread bitmap structure. The thread bitmap is used to retrieve the active threads of a task. The thread bitmap contains one bit for every thread (0 ... P4_NUM_THREAD-1) where each thread number corresponds to a bit position within the bitmap and a set bit mentions an active thread. The thread bitmap structure is to be treated as an opaque data type and should only be accessed using the macros P4_THREAD_GET_BIT() (see section 1.23.2).

Synopsis: struct P4_thread_bitmap_str { unsigned long m[...]; };

Structure Element Description: m Storage for bitmap.

Associated Data Type

P4_thread_bitmap_t Thread bitmap structure.

1.23.2 Defines

P4_THREAD_GET_BIT (tbm_p, tnum) This macro tests whether the bit for thread tnum is set in the thread bitmap pointed to by tbm_p.

        Parameters:
            tbm_p Pointer to the thread bitmap to be tested.
            tnum Thread number (0 ... P4_NUM_THREAD-1).
        Returns:
        TRUE if the bit is set, FALSE otherwise.

        Note:
        If tnum is not a valid thread number, the return value is undefined.

P4_THREAD_SET_BIT (tbm_p, tnum) This macro sets the bit for thread tnum in the thread bitmap pointed to by tbm_p.

        Parameters:


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Monitoring 331

          tbm_p Pointer to the thread bitmap.
          tnum Thread number (0 ... P4_NUM_THREAD-1).
      Note:
      If tnum is not a valid thread number, the effects of this macro are undefined.

P4_THREAD_CLEAR_SET (tbm_p) Initialise thread bitmap with all bits cleared. Description: This macro clears the thread bitmap pointed to by tbm_p.

      Parameters:
          tbm_p Pointer to the thread bitmap.

P4_THREAD_FILL_SET (tbm_p) Initialise thread bitmap with all bits set. Description: This macro fills the thread bitmap pointed to by tbm_p.

      Parameters:
          tbm_p Pointer to the thread bitmap.

1.23.3 Data Type Definitions

P4_thread_bitmap_t Thread bitmap structure. The thread bitmap is used to retrieve the active threads of a task. The thread bitmap contains one bit for every thread (0 ... P4_NUM_THREAD-1) where each thread number corresponds to a bit position within the bitmap and a set bit mentions an active thread. The thread bitmap structure is to be treated as an opaque data type and should only be accessed using the macros P4_THREAD_GET_BIT() (see section 1.23.2).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

332 The PikeOS Kernel API

1.23.4 Functions

1.23.4.1 p4_mon_respart_get_attr

Retrieve resource partition status.

Synopsis:

P4_e_t p4_mon_respart_get_attr(P4_uint32_t rp_id, P4_respart_attr_t *rp_info_p)

Parameters: rp_id IN: Resource partition id. The value of rp_id must be the ID of an existing partition. The value P4_RESPART_INHERIT is not supported here. rp_info_p OUT: Pointer to a resource partition attribute structure Upon successful completion, the structure referenced by rp_info_p will contain the resource partition attributes. A NULL pointer indicates the resource partition attributes should not be retrieved.

Description: This function retrieves the status of resource partition rp_id and saves the status information in rp_info_p (if non NULL). The resource partition must exist.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if rp_id is not a valid resource partition ID, or if rp_info_p is not a valid address or exceeds the callers virtual address space. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_MONITOR enabled. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel is not fully mapped in the callers virtual address space.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Monitoring 333

1.23.4.2 p4_mon_get_task_map

Retrieve bitmap of active tasks in the system.

Synopsis:

P4_e_t p4_mon_get_task_map(P4_task_bitmap_t *task_map_p)

Parameters: task_map_p OUT: Bitmap of active tasks in the system. Each bit in this bitmap represents one task, the bit position corresponding to the task number. If a bit is set, the corresponding task is active. A NULL pointer indicates that the bitmap of active tasks should not be retrieved.

Description: This function retrieves a bitmap of active tasks in the system. Upon successful completion, the bitmap is stored at task_map_p, if not NULL.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if task_map_p is not a valid address or exceeds the callers virtual address space. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_MONITOR enabled. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel is not fully mapped in the callers virtual address space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

334 The PikeOS Kernel API

1.23.4.3 p4_mon_task_get_thread_map

Retrieve bitmap of active threads in a task.

Synopsis:

P4_e_t p4_mon_task_get_thread_map(P4_task_t task, P4_thread_bitmap_t *thread_map_p)

Parameters: task IN: Number of the task whose active thread bitmap shall be retrieved. The parameter must be a valid task number or P4_TASK_MYSELF to refer to the callers task. thread_map_p OUT: Bitmap of active threads in task task. Each bit in this bitmap represents one thread, the bit position corresponding to the thread number. If a bit is set, the corresponding thread is active. A NULL pointer indicates that the bitmap of active threads should not be retrieved.

Description: This function retrieves a bitmap of active threads of active task task. Upon successful completion, the bitmap is stored at thread_map_p, if not NULL.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if task is not a valid task number, or if thread_map_p is not a valid address or exceeds the callers virtual address space. P4_E_STATE if task does not refer to an active task. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_MONITOR enabled. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel is not fully mapped in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Monitoring 335

1.23.4.4 p4_mon_thread_get_attr

Retrieve thread attributes of a thread in any task.

Synopsis:

P4_e_t p4_mon_thread_get_attr(P4_task_t task, P4_thr_t tnum, P4_thread_attr_t *attr_p)

Parameters: task IN: Number of the task whose threads attributes shall be retrieved. The parameter must be a valid task number or P4_TASK_MYSELF to refer to the callers task. tnum IN: Number of the thread whose attributes shall be retrieved. The parameter must be a valid thread number for the configured task limits. attr_p OUT: Location of attribute structure for storing result.

Description: This function retrieves the thread attributes for thread tnum of task task and stores them in the thread attribute structure pointed to by attr_p (if non NULL). Both task and thread must exist.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if task is not a valid task number, or if tnum is not a valid thread number, or if attr_p is an invalid user space address or exceeds the callers virtual address space. P4_E_STATE if task does not refer to an active task, or if tnum does not refer to an active thread. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_MONITOR enabled. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel is not fully mapped in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

336 The PikeOS Kernel API

1.23.4.5 p4_mon_thread_get_regs

Retrieve user mode context of a thread in any task.

Synopsis:

P4_e_t p4_mon_thread_get_regs(P4_task_t task, P4_thr_t tnum, P4_regs_t *regs)

Parameters: task IN: Number of the task whose threads attributes shall be retrieved. The parameter must be a valid task number or P4_TASK_MYSELF to refer to the callers task. tnum IN: Number of the thread whose attributes shall be retrieved. The parameter must be a valid thread number for the configured task limits. regs OUT: Upon successful return of this function, regs, if non-NULL, will contain the user mode context of the target thread.

Description: This function retrieves the user mode context for thread tnum of task task and stores it in the location pointed to by regs (if non NULL). Both task and thread must exist. The returned user mode context reflects the state of the thread running either in user or in kernel mode and may be corrupted. Its purpose is for diagnostic use only. The target thread is not unblocked or otherwise modified.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if task is not a valid task number, or if tnum is not a valid thread number, or if regs is an invalid user space address or exceeds the callers virtual address space. P4_E_STATE if task does not refer to an active task, or if tnum does not refer to an active thread. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_MONITOR enabled. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel is not fully mapped in the callers virtual address space.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Monitoring 337

1.23.4.6 p4_mon_get_syscall_name

Get system call name for given system call number.

Synopsis:

const char* p4_mon_get_syscall_name(P4_cpureg_t syscall)

Parameters: syscall IN: System call number.

Description: This function returns the name of the system call with system call number syscall. The system call number can be retrieved by p4_regs_get_syscall() (see section 1.14.6.15). Invalid system call numbers result in the string "INVALID". The returned string must not be modified.

Returns: System call name.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

338 The PikeOS Kernel API

1.23.4.7 p4_mon_get_trap_name

Get trap name for given trap code.

Synopsis:

const char* p4_mon_get_trap_name(P4_cpureg_t trap)

Parameters: trap IN: Trap code.

Description: This function translates the trap code trap into a readable string. Invalid trap codes result in the string "INVALID". The returned string must not be modified.

Returns: Trap code name.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Monitoring 339

1.23.4.8 p4_strerror

Get name for given error code.

Synopsis:

const char* p4_strerror(P4_e_t rc)

Parameters: rc IN: Error code.

Description: This function translates the error code rc into a readable string. Invalid error codes result in the string "P4_E_?". The returned string must not be modified.

Returns: Error code name.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

340 The PikeOS Kernel API

1.23.4.9 p4_strerror_r

Get name for given error code.

Synopsis:

const char* p4_strerror_r(P4_e_t rc, char *buff, P4_size_t size)

Parameters: rc IN: Error code buff IN: Buffer to write the error code description size IN: Number of bytes available in buff

Description: This function translates the error code rc into a readable string in the same way p4_mon_get_error_name does. Invalid error codes result in a descriptive string of the kind "P4_E_?:0x If size > 0 and buff is an invalid pointer or NULL, the behaviour of this function is undefined.

Returns: The error code description. This returns either a static string or a pointer into buff.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Monitoring 341

1.23.4.10 p4_mon_get_error_name

Get name for given error code.

Synopsis:

__forceinline const char* p4_mon_get_error_name(P4_e_t error)

Parameters: error IN: error type

Description: This function is an alias for p4_strerror() (see section 1.23.4.8).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

342 The PikeOS Kernel API

1.23.4.11 p4_mon_task_get_attr

Retrieve task attributes.

Synopsis:

P4_e_t p4_mon_task_get_attr(P4_task_t which, P4_task_attr_t *attr_p, P4_task_bitmap_t *pt_bitmap_p, P4_task_bitmap_t *comm_map_p, P4_interrupt_bitmap_t *int_map_p, P4_device_bitmap_t *dev_map_p)

Parameters: which IN: ID of the task whose task attributes shall be retrieved. The parameter must be a valid task number or P4_TASK_MYSELF to refer to the callers task. attr_p OUT: Pointer to a task attribute structure Upon successful completion, the structure referenced by attr_p will contain the task attributes. A NULL pointer indicates that the task attributes should not be retrieved. pt_bitmap_p OUT: Bitmap of passive tasks. Each bit in this bitmap represents one task, the bit position corresponding to the task number. If a bit is set, the corresponding task is a passive task of the task to which this task bitmap belongs. A NULL pointer indicates that the bitmap of passive tasks should not be retrieved. comm_map_p OUT: Communication bitmap. Each bit in this bitmap represents one task, the bit position corresponding to the task number. If a bit is set, task which has the right to send IPC messages to the corresponding task. A NULL pointer indicates that the communication bitmap should not be retrieved. int_map_p OUT: Interrupt bitmap. Each bit in this bitmap represents an interrupt granted to this task with the bit position corresponding to the interrupt number. If a bit is set, task which has the right to attach to the corresponding interrupt. A NULL pointer indicates that the interrupt bitmap should not be retrieved. dev_map_p OUT: Device bitmap. Each bit in this bitmap represents a kernel level device with the bit position corresponding to the device number. If a bit is set, task which has the granted access right for this dedicated kernel level device. A NULL pointer indicates that the device bitmap should not be retrieved.

Description: This function retrieves the attributes of task which. Task id which may be any valid task number. For a detailed description of the task attribute structure, refer to the documentation of P4_task_attr_t.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if which is not a valid task ID. P4_E_INVAL if either attr_p, pt_bitmap_p, comm_map_p, int_map_p, or dev_map_p are not valid addresses or exceed the callers virtual address space.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Monitoring 343

P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_MONITOR enabled. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel is not fully mapped in the callers virtual address space.

                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

344 The PikeOS Kernel API

1.23.4.12 p4_mon_mem_list

Get a list of mappings for a virtual memory area.

Synopsis:

P4_e_t p4_mon_mem_list(P4_task_t task, P4_address_t addr, P4_size_t length, P4_sglist_t *sglist, P4_uint32_t *entries)

Parameters: task IN: ID of the task whose address space will be referenced. The parameter must be a valid task number or P4_TASK_MYSELF to refer to the callers task. addr IN: Address of the virtual memory area in task address space. The value must be a multiple of P4_PAGESIZE. length IN: Size of the virtual memory area. The value must be non-zero and a multiple of P4_PAGESIZE. sglist OUT: Pointer to a memory area where the mapping list shall be created. entries IN: Maximum allowed number of entries in mapping list. OUT: Number of entries in list actually written.

Description: This function builds a list with memory attributes of the memory area described by addr and length in the address space of task task. For each block of physical continuous memory pages having the same attributes, a new entry of type P4_sglist_t will be created. The maximum space needed for the list is:

                       size = (length/P 4_P AGESIZE)  sizeof (P 4_sglist_t)

The user must specify the maximum number of entries the list can hold. The number of entries actually used for the list is returned in entries. If the supplied list space is too small to hold all the entries needed to descibe the memory area, P4_E_TRUNC is returned. In the case of error code P4_E_TRUNC, only a partial mapping list may have been created. The address where the error occurred can be calculated from the last valid entry in the mapping list. In the case of error code P4_E_PAGEFAULT, a partial mapping list may have been created, but the mapping may be corrupted. In the case of error codes P4_E_INVAL, P4_E_BADTASK, or P4_E_STATE, no mapping list will have been built.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_MONITOR enabled. P4_E_INVAL if addr or length are not multiples of P4_PAGESIZE, or if length is zero, or if addr and length do not describe a valid memory area in the task virtual address space, or if sglist is NULL, or if sglist does not point to a valid address or exceeds the callers virtual address space, or

                                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Monitoring 345

      if entries is NULL, or
      if entries does not point to a valid address or exceeds the callers virtual address space, or
      if task is zero and refers to the kernel, or
      if task is not a valid task id.

P4_E_STATE if task does not refer to an active task. P4_E_TRUNC if there is no more space to store entries into the mapping list. P4_E_PAGEFAULT if entries does not point to a fully mapped memory area in the callers virtual address space, or if sglist does not point to a fully mapped memory area in the callers virtual address space.

Note: A non-writeable memory area for entries will not raise an error in this system call.

Note: Unlike p4_mem_build_sglist() (see section 1.15.6.5), p4_mon_mem_list() (see section 1.23.4.12) gracefully han- dles unmapped areas in the virtual address space and will never return the error code P4_E_BADMAP. Thus the returned list may contain virtually non-contiguous entries. entries is set to zero if no mappings were found in the specified memory area.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

346 The PikeOS Kernel API

1.23.4.13 p4_mon_memreg_get_attr

Get the attributes of a memory region.

Synopsis:

P4_e_t p4_mon_memreg_get_attr(P4_uint32_t memreg_id, P4_memreg_attr_t *memreg_attr_p)

Parameters: memreg_id IN: ID of the memory region whose attributes will be read out. memreg_attr_p OUT: Pointer to a memory region attribute structure.

Description: This function retrieves the attributes of a memory region identified by memreg_id and will copy them to the structure provided via memreg_attr_p. Using P4_MEMREG_GLOBAL for memreg_id will access the attributes of the global memory region. Otherwise, memory region identifiers for memreg_id can be generated via the P4_MEMREG() (see section 1.26.2) helper.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_MONITOR enabled. P4_E_INVAL if memreg_attr_p is NULL or does not point to a valid address or exceeds the callers virtual address space, or if memreg_attr_p does not point to a valid address or exceeds the callers virtual address space. P4_E_NOENT if memreg_id does not refer to an existing memory region. P4_E_PAGEFAULT if memreg_attr_p does not point to a fully mapped memory area in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Control 347

1.24 Kernel Control

This section describes constants, data types, access macros and service calls related to the PikeOS kernel control API.

1.24.1 Defines

P4_KCTL (group, sub) Build kernel control function selector. Description: Combines parameters group and sub to form a function selector for p4_kernel_control() (see section 1.24.2.1).

       Parameters:
             group Selects function group
             sub Selects subfunction in group

P4_KCTL_GROUP (x) Extract group from kernel control function selector.

P4_KCTL_SUB (x) Extract subfunction from kernel control function selector.

P4_KCTL_PSP Kernel control group selector for PSP functions.

P4_KCTL_ASP Kernel control group selector for ASP functions.

P4_KCTL_PSP_RESET Perform a hardware reset. Description: If supported by the PSP, this function performs a hardware reset. On systems where reset functionality is not available, the system is halted. The function takes no additional parameters, and if successful, does not return to the caller. The calling task must have the ability P4_AB_PSP_RESET enabled, otherwise p4_kernel_control() (see section 1.24.2.1) will return an error.

P4_KCTL_PSP_HALT Halt the processor. Description: This function halts the processor. The function takes no additional parameters, and if successful, does not return to the caller. The calling task must have the ability P4_AB_PSP_RESET enabled, otherwise p4_kernel_control() (see section 1.24.2.1) will return an error.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

348 The PikeOS Kernel API

P4_KCTL_PSP_POWER_OFF Power off the system. Description: If supported by the PSP, this function performs a power off of the system. On systems where power off functionality is not available, the system is halted. The function takes no additional parameters, and if successful, does not return to the caller. The calling task must have the ability P4_AB_PSP_RESET enabled, otherwise p4_kernel_control() (see section 1.24.2.1) will return an error.

P4_KCTL_PSP_CNSPOLL Poll the status of the console. Description: If supported by the PSP, this function polls the status of the serial console port. The function returns a value in ret that can be analyzed with P4_KCTL_PSP_POLL_RXAVAIL() (see section 1.24.1) and P4_KCTL_PSP_POLL_TXSPACE() (see section 1.24.1). The calling task must have the ability P4_AB_PSP_CONSOLE enabled, otherwise p4_kernel_control() (see section 1.24.2.1) will return an error.

P4_KCTL_PSP_CNSPUT Write a character to the console. Description: If supported by the PSP, this function sends data to the console port. param1 in the call to p4_kernel_control() (see section 1.24.2.1) is interpreted as the character to send to the console. The calling task must have the ability P4_AB_PSP_CONSOLE enabled, otherwise p4_kernel_control() (see section 1.24.2.1) will return an error.

P4_KCTL_PSP_CNSGET Read a character from the console. Description: If supported by the PSP, this function reads a character from the console and returns it in ret. If the console has no data available for reading, ret is set to zero. The calling task must have the ability P4_AB_PSP_CONSOLE enabled, otherwise p4_kernel_control() (see section 1.24.2.1) will return an error.

P4_KCTL_PSP_HMRESET Perform a hardware reset, indicate HM involvement. Description: If supported by the PSP, this function performs a hardware reset and saves the involvement of a health monitoring function to non-volatile area, where it can be retrieved after the reset. On systems where reset functionality is not available, the system is halted and the HM involvement is not preserved. The function takes no additional parameters, and if successful, does not return to the caller. The calling task must have the ability P4_AB_PSP_RESET enabled, otherwise p4_kernel_control() (see section 1.24.2.1) will return an error.

P4_KCTL_ASP_TLS_SET Set TLS (thread local storage) area for calling thread. Description:

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Kernel Control 349

     On ARM, MIPS and V850, the new TLS value must be placed in param1. Not implemented on PPC and
     SPARC. On x86, the value of param1 selects if TLS0 or TLS1 is to be updated. On x86_amd64, the
     value of param2 is the new segment base.

P4_KCTL_ASP_READ_UWIN Read unsaved register windows. Description: On SPARC architecture, read outstanding unsaved register windows of the current thread. Not im- plemented on other architectures. The kernel implementation for SPARC supports up to 8 outstanding register windows which it could not save on the user stack. The number of register windows to read must be placed in param1, and a pointer to the register windows save area must be placed in param2. The register window save area has the following format: struct p4_sparc_uwin P4_cpureg_t window_sp[8]; struct P4_cpureg_t regs[16]; window[8]; ; Element window_sp contains the stack pointer of the match- ing window.

P4_KCTL_ASP_WRITE_UWIN Write unsaved register windows. Description: On SPARC architecture, write outstanding unsaved register windows of the current thread. Not imple- mented on other architectures. The number of register windows to read must be placed in param1, a pointer to the register windows save area must be placed in param2.

P4_KCTL_PSP_POLL_RXAVAIL (x) Extract information from console poll return value.

     Parameters:
            x Return value from console poll PSP subfunction.
     This macro extracts the number of characters available for reading from the return value of the PSP
     console poll subfunction (P4_KCTL_PSP_CNSPOLL).

P4_KCTL_PSP_POLL_TXSPACE (x) Extract information from console poll return value.

     Parameters:
            x Return value from console poll PSP subfunction.
     This macro extracts the number of characters available for writing from the return value of the PSP
     console poll subfunction (P4_KCTL_PSP_CNSPOLL).

P4_KCTL_PSP_POLL_RETURN (rx, tx) Build console poll return value.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

350 The PikeOS Kernel API

1.24.2 Functions

1.24.2.1 p4_kernel_control

Call a kernel control function.

Synopsis:

P4_e_t p4_kernel_control(P4_uint32_t func, P4_cpureg_t param1, P4_cpureg_t param2, P4_cpureg_t param3, P4_cpureg_t *ret)

Parameters: func IN: Kernel control function selector param1 IN: First parameter passed to selected function param2 IN: Second parameter passed to selected function param3 IN: Third parameter passed to selected function ret OUT: Result of the selected function

Description: This function is used to invoke generic kernel control functions. The control function is specified by a function selector func consisting of a function group and a subfunction in the group. Up to three parameters can be passed to the selected control function. A single value may be returned in the location pointed to by ret. On error codes other than P4_E_OK, the value returned in ret is undefined.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_NOABILITY The task of the calling thread does not have the ability to call this function. P4_E_NOTIMPL func does not specify a valid function. P4_E_INVAL if ret is not NULL and does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT if ret is not NULL and is not fully mapped in the callers virtual address space.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Cache Handling 351

1.25 Cache Handling

This section describes constants, data types, access macros, and service functions related to cache handling in PikeOS.

1.25.1 Defines

P4_INVAL_ICACHE_RANGE Cache operation. Description: In cache maintenance operations, the following constants are used to specify a cache flush or cache invalidation operation on the systems instruction and/or data caches.Synchronize instruction cache content with data cache content for a given memory range in the current virtual address space for application loading. Upon completion, the instruction cache is guaranteed to be in a coherent state with the data cache. This operation does not ensure that data cache content is written to memory or invalidated in the caches. On architectures with non-snooping instruction caches, this operation typically writes back any content in the data caches and invalidates any content in the instruction caches for the given memory range up to the point in the cache hierarchy where data caches and instruction caches join. On architectures with snooping instruction caches or unified L1-caches, this operation typically does nothing. On multiprocessor systems, this operation ensures that the caches of all processors are affected.

       Note:
       This operation takes care of potential aliases in the instruction cache for an additional memory region
       in another address space.
       Any given cache flags are ignored for this operation.

P4_FLUSH_DCACHE_RANGE

       Description:
       Write back and invalidate cache content in the data caches for a given memory range in the current
       virtual address space.
       Depending on the given flags, the operation writes back and invalidates cache content down to different
       levels in the cache and memory hierarchy:

          • P4_CACHE_FLAG_DMA for cache coherency to DMA bus masters.
          • P4_CACHE_FLAG_CPU affects cache content on the current processor only, up to a shared
               cache.
          • P4_CACHE_FLAG_ALL affects all levels of the cache hierarchy, up to memory.

       Note:
       On architectures with write-through caches, this operation invalidates data cache content only.

P4_SYNC_DCACHE_RANGE

       Description:


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

352 The PikeOS Kernel API

  Write back cache content in the data caches for a given memory range in the current virtual address
  space.
  Depending on the given flags, the operation writes back cache content down to different levels in the
  cache and memory hierarchy:

     • P4_CACHE_FLAG_DMA for cache coherency to DMA bus masters.
     • P4_CACHE_FLAG_CPU affects cache content on the current processor only, up to a shared
          cache.
     • P4_CACHE_FLAG_ALL affects all levels of the cache hierarchy, up to memory.

  Note:
  On architectures with write-through caches, this operation invalidates data cache content only.

  Note:
  On some architectures, this operation may also invalidate the caches after write back, making this
  operation equivalent to P4_FLUSH_DCACHE_RANGE.

P4_INVAL_DCACHE_RANGE

  Description:
  Invalidate cache content in the data caches for a given memory range in the current virtual address
  space.
  Depending on the given flags, the operation invalidates cache content down to different levels in the
  cache and memory hierarchy:

     • P4_CACHE_FLAG_DMA for cache coherency to DMA bus masters.
     • P4_CACHE_FLAG_CPU affects cache content on the current processor only, up to a shared
          cache.
     • P4_CACHE_FLAG_ALL affects all levels of the cache hierarchy, up to memory.

  Note:
  This operation requires a writable memory region and additionally writes back cache content at the
  beginning and the end of the memory area if the memory area is not properly aligned.

  Note:
  On some architectures or in some processor modes, the operation may be equivalent to
  P4_FLUSH_DCACHE_RANGE and write back any data before invalidating caches. The calling code
  should be written in a robust way that write back of previous data is acceptable.

P4_CACHE_FLAG_DMA Cache flags. Description: In cache maintenance operations, the following flags are used to specify the affected level in the cache and memory hierarchy and the affected target memory region, e.g. user space or kernel space.Cache operation flag Write back and/or invalidate cache content for cache coherency to DMA bus masters. Upon completion, cache content is written back and/or invalidated down to a level in the cache and memory hierarchy where DMA bus masters access the data. On architectures with non-cache coherent DMA bus masters, this operation affects all levels of caches in the cache hierarchy down to the point where the bus master accesses the data.

                       c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Cache Handling 353

     On architectures with cache coherent DMA bus masters, this operation may only affect the first levels of
     the cache hierarchy.
     On multiprocessor systems, this operation ensures that the caches of all processors are affected.

P4_CACHE_FLAG_CPU Cache operation flag. Description: Write back and/or invalidate cache content on the current processor only. Upon completion, cache content is written back and/or invalidated down to at least the next level in the cache and memory hierarchy on the current processor. On multiprocessor systems, this operation only guarantees to have an effect on the first level data cache of the callers CPU, but may also affect further levels of data caches if these are private to the callers CPU.

P4_CACHE_FLAG_ALL Cache operation flag. Description: Write back and/or invalidate cache content in the whole cache and memory hierarchy. Upon completion, cache content is written back and/or invalidated to memory. On multiprocessor systems, it is implementation specific whether the caches of other processors are affected.

VM_MEM_CACHE_CB 0

     Description:
     Cached write-back memory access. This mode maps to P4_M_C_WB.

VM_MEM_CACHE_WT 1

     Description:
     Cached write-through memory access. This mode maps to P4_M_C_WT.

VM_MEM_CACHE_INHIBIT 2

     Description:
     Uncached strongly-ordered memory access. This mode maps to P4_M_C_UC.

VM_MEM_CACHE_WC 3

     Description:
     Cached write-combining memory access. This mode maps to P4_M_C_WC.

VM_MEM_CACHE_DEV 4

     Description:
     Uncached memory access or ARM memory type device. This mode maps to P4_M_C_DEV.


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

354 The PikeOS Kernel API

vm_memory_cache_mode_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

vm_memory_cache_mode_MAX 4

      Description:
      Maximum value of the enum type

1.25.2 Data Type Definitions

vm_memory_cache_mode_t Cache mode for memory areas. Values are conveniently unified with P4_M_C_* values.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Cache Handling 355

1.25.3 Functions

1.25.3.1 p4_inval_icache_range

Synchronize instruction cache content with data cache content.

Synopsis:

P4_e_t p4_inval_icache_range(P4_address_t start, P4_size_t size)

Parameters: start IN: Start address in the callers address space. size IN: Size of memory region in the callers address space.

Description: A call to this function synchronizes instruction cache content with data cache content for the memory region defined by start and size in the callers address space.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if the memory region defined by start and size is invalid or exceeds the callers virtual address space. P4_E_PAGEFAULT if the memory region defined by start and size is not fully mapped in the callers virtual address space.

Note: When this call returns, the instruction cache is guaranteed to be in a coherent state with the data cache. This call does not ensure that cache content is written to memory or invalidated in the caches. The actual implementation depends on the architecture.

Note: This call may be implemented as a user library function and may involve no system call if P4_FEATURE_IN- VAL_ICACHE_RANGE is defined. Memory referenced by start and size should be mapped properly in the callers address space. Otherwise, the service is implemented at PSP-level and equivalent to a call to p4_cache(P4_IN- VAL_ICACHE_RANGE, start, size, start, P4_CACHE_FLAG_CPU).

Note: This call does not guarantee to invalidate potential aliases in the instruction cache, especially modifying code for other address spaces. Use p4_inval_icache_range_alias(start, size, alias) or p4_cache(P4_IN- VAL_ICACHE_RANGE, start, size, alias, P4_CACHE_FLAG_CPU) instead.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

356 The PikeOS Kernel API

1.25.3.2 p4_inval_icache_range_alias

Synchronize instruction cache content with data cache content for application loading.

Synopsis:

P4_e_t p4_inval_icache_range_alias(P4_address_t start, P4_size_t size, P4_address_t alias)

Parameters: start IN: Start address in the callers address space. size IN: Size of memory region in the callers address space. alias IN: Start address in another address space that might alias the instruction cache content.

Description: A call to this function synchronizes instruction cache content with data cache content for the memory region de- fined by start and size in the callers address space. The function additionally handles potential aliases in the instruction cache in cross address space memory accesses. The function uses alias to derive the addresses of potential instruction cache aliases in other address spaces. In this case, the caller should perform a P4_IN- VAL_ICACHE_RANGE operation on the data memory region, i.e. the memory region or mapping where data cache content was modified, and provide the memory region where instructions will be executed from as alias. alias might refer to an address in a different address space. Set alias equal to start if both regions are equal.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if the memory region defined by start and size is invalid or exceeds the callers virtual address space. P4_E_PAGEFAULT if the memory region defined by start and size is not fully mapped in the callers virtual address space.

Note: When this call returns, the instruction cache is guaranteed to be in a coherent state with the data cache. This call does not ensure that cache content is written to memory or invalidated in the caches. The actual implementation depends on the architecture.

Note: This call may be implemented as a user library function and may involve no system call if P4_FEATURE_IN- VAL_ICACHE_RANGE is defined. Memory referenced by start and size should be mapped properly in the callers address space. Otherwise, the service is implemented at PSP-level and equivalent to a call to p4_cache(P4_IN- VAL_ICACHE_RANGE, start, size, alias, P4_CACHE_FLAG_CPU).

Note: For application loading in the callers address space, use p4_inval_icache_range(start, size).

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Cache Handling 357

1.25.3.3 p4_flush_dcache_range

Write back and invalidate data cache content.

Synopsis:

P4_e_t p4_flush_dcache_range(P4_address_t start, P4_size_t size)

Parameters: start IN: Start address in the callers address space. size IN: Size of memory region in the callers address space.

Description: A call to this function writes back and invalidates data cache content for the memory region defined by start and size in the callers address space.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if the memory region defined by start and size is invalid or exceeds the callers virtual address space. P4_E_PAGEFAULT if the memory region defined by start and size is not fully mapped in the callers virtual address space.

Note: When this call returns, the affected data cache content is guaranteed to be written back and invalidated in the data cache up to a point in the cache and memory hierarchy where a non-cache coherent DMA bus master can access the data. The actual implementation depends on the architecture or the PSP.

Note: On architectures with write-through caches, this operation invalidates data cache content only.

Note: This call may be implemented as a user library function and may involve no system call if P4_FEA- TURE_FLUSH_DCACHE_RANGE is defined. Memory referenced by start and size should be mapped properly in the callers address space. Otherwise, the service is implemented at PSP-level and equivalent to a call to p4_cache(P4_FLUSH_DCACHE_RANGE, start, size, start, P4_CACHE_FLAG_DMA).

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

358 The PikeOS Kernel API

1.25.3.4 p4_sync_dcache_range

Write back data cache content.

Synopsis:

P4_e_t p4_sync_dcache_range(P4_address_t start, P4_size_t size)

Parameters: start IN: Start address in the callers address space. size IN: Size of memory region in the callers address space.

Description: A call to this function writes back data cache content for the memory region defined by start and size in the callers address space.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if the memory region defined by start and size is invalid or exceeds the callers virtual address space. P4_E_PAGEFAULT if the memory region defined by start and size is not fully mapped in the callers virtual address space.

Note: When this call returns, the affected data cache content is guaranteed to be written back up to a point in the cache and memory hierarchy where a non-cache coherent DMA bus master can access the data. The actual implementation depends on the architecture or the PSP.

Note: On architectures with write-through caches, this operation invalidates data cache content only.

Note: On some architectures, this operation may also invalidate the caches after write back, making this operation equivalent to P4_FLUSH_DCACHE_RANGE.

Note: This call may be implemented as a user library function and may involve no system call if P4_FEA- TURE_SYNC_DCACHE_RANGE is defined. Memory referenced by start and size should be mapped properly in the callers address space. Otherwise, the service is implemented at PSP-level and equivalent to a call to p4_cache(P4_SYNC_DCACHE_RANGE, start, size, start, P4_CACHE_FLAG_DMA).

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Cache Handling 359

1.25.3.5 p4_inval_dcache_range

Invalidate data cache content.

Synopsis:

P4_e_t p4_inval_dcache_range(P4_address_t start, P4_size_t size)

Parameters: start IN: Start address in the callers address space. size IN: Size of memory region in the callers address space.

Description: A call to this function invalidates data cache content for the memory region defined by start and size in the callers address space. The operation requires a writable memory region and additionally writes back cache content at the beginning and the end of the memory area if the memory area is not properly aligned.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if the memory region defined by start and size is invalid or exceeds the callers virtual address space. P4_E_PAGEFAULT if the memory region defined by start and size is not fully mapped in the callers virtual address space.

Note: When this call returns, the affected data cache content is guaranteed to be invalidated in the data cache up to a point in the cache and memory hierarchy where a non-cache coherent DMA bus master can access the data. The actual implementation depends on the architecture or the PSP.

Note: On some architectures or in some processor modes, the operation may be equivalent to P4_FLUSH_DCACHE_RANGE and write back any data before invalidating caches. The calling code should be written in a robust way that write back of previous data is acceptable.

Note: This call may be implemented as a user library function and may involve no system call if P4_FEATURE_IN- VAL_DCACHE_RANGE is defined. Memory referenced by start and size should be mapped properly in the callers address space. Otherwise, the service is implemented at PSP-level and equivalent to a call to p4_cache(P4_IN- VAL_DCACHE_RANGE, start, size, start, P4_CACHE_FLAG_DMA).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

360 The PikeOS Kernel API

1.25.3.6 p4_cache

Perform data and instruction cache operations on a given memory region.

Synopsis:

P4_e_t p4_cache(P4_cache_op_t op, P4_address_t start, P4_size_t size, P4_address_t alias, P4_uint32_t flags)

Parameters: op IN: Cache operation. start IN: Start address in the callers address space. size IN: Size of memory region in the callers address space. alias IN: Start address in another address space that might alias the instruction cache content. flags IN: Flags for the cache operation.

Description: A call to this function performs the following operations on the data and instruction caches, depending on op:

  • P4_INVAL_ICACHE_RANGE Synchronize instruction cache content with data cache content for application
    loading.
  • P4_FLUSH_DCACHE_RANGE Write back and invalidate data cache content.
  • P4_SYNC_DCACHE_RANGE Write back data cache content.
  • P4_INVAL_DCACHE_RANGE Invalidate data cache content.

Depending on flags, cache content in the cache and memory hierarchy is affected differently by the operation:

  • P4_CACHE_FLAG_CPU affects caches on current processor only.
  • P4_CACHE_FLAG_DMA for cache coherency to DMA bus masters.
  • P4_CACHE_FLAG_ALL affects all levels of the cache hierarchy. If flags is zero, P4_CACHE_FLAG_DMA
    applies.

The operations P4_FLUSH_DCACHE_RANGE, P4_SYNC_DCACHE_RANGE, and P4_IN- VAL_DCACHE_RANGE affect content in the cache related to the memory region defined by start and size. Set alias to start for these operations. The operation P4_INVAL_DCACHE_RANGE requires a writable memory region and additionally writes back cache content at the beginning and the end of the memory area if the memory area is not prop- erly aligned. On some architectures or in some processor modes, the operation may be equivalent to P4_FLUSH_DCACHE_RANGE and write back any data before invalidating caches. The calling code should be written in a robust way that write back of previous data is acceptable. The operation P4_INVAL_ICACHE_RANGE additionally handles potential aliases in the instruction cache in cross address space memory accesses. The operation uses alias to derive the addresses of potential instruction cache aliases in other address spaces. In this case, the caller should perform a P4_INVAL_ICACHE_RANGE operation

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Cache Handling 361

on the data memory region, i.e. the memory region or mapping where data cache content was modified, and provide the memory region where instructions will be executed from as alias. alias might refer to an address in a different address space. Set alias equal to start if both regions are equal.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_NOTIMPL if op or flags are not supported by the PSP. P4_E_INVAL if size is zero, or if the memory region defined by start and size is invalid or exceeds the callers virtual address space. P4_E_INVAL if an invalid flag is set in flags. P4_E_PAGEFAULT if the memory region defined by start and size is not fully mapped in the callers virtual address space.

Note: This call is always implemented as a system call at PSP-level. Refer to the platform manual for supported operations and resulting effective combinations.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

362 The PikeOS Kernel API

1.26 Memory Allocation

This section describes constants, data types, access macros, and service functions related to the PikeOS memory allocation API.

1.26.1 Structure Definitions

1.26.1.1 struct P4_memreg_attr_str

Memory region attribute info entry. Format of a info entry used by p4_mon_memreg_get_attr() (see section 1.23.4.13).

Synopsis: struct P4_memreg_attr_str { P4_size_t free; P4_size_t total; P4_uint32_t type; P4_uint32_t unused; };

Structure Element Description: free Number of available bytes in this memregion total Total number of bytes assigned to this memregion type Type of the underying memory region: privileged / default (non-priv) unused Padding

Associated Data Type

P4_memreg_attr_t Memory region attribute info entry.

1.26.2 Defines

P4_MEMREG_GLOBAL

        Description:
        Memory region identifier for the global memory region.
        This memory region ID is used as the default memory region if no other memory regions are defined in
        the system.
        By convention, the global memory region is memory region 0 in (resource) partition 0.

P4_NUM_MEMREG

        Description:
        Maximum number of memory regions per partition.


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Memory Allocation 363

P4_MEMREG_INVALID

     Description:
     Invalid memory region ID.
     A memory region ID that is guaranteed to be invalid and not conflicting with other memory region IDs.

P4_MEMREG (respart_id, local_id)

     Description:
     Helper macro to build a full memory region ID from a (resource) partition ID respart_id and a memory
     region ID local_id local to the partition.

P4_MEMREG_GET_RESPART (memreg_id)

     Description:
     Helper macro to retrieve the resource partition ID from a full memory region ID memreg_id.

P4_MEMREG_GET_LOCAL_ID (memreg_id)

     Description:
     Helper macro to retrieve the local memory region ID from a full memory region ID memreg_id.

VM_MEM_ACCESS_RD 1

     Description:
     The memory can be read.

VM_MEM_ACCESS_WR 2

     Description:
     The memory can be written.

VM_MEM_ACCESS_EXEC 4

     Description:
     Code can execute from the memory.

VM_MEM_ACCESS_RD_WR (VM_MEM_ACCESS_RD (see section 1.26.2) | VM_MEM_ACCESS_WR (see section 1.26.2))

     Description:
     Convenience definition for read and write permissions.

VM_MEM_ACCESS_RD_EXEC (VM_MEM_ACCESS_RD (see section 1.26.2) | VM_MEM_ACCESS_EXEC (see section 1.26.2))

     Description:
     Convenience definition for read and execute permissions.


                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

364 The PikeOS Kernel API

VM_MEM_ACCESS_RD_WR_EXEC (VM_MEM_ACCESS_RD_WR (see section 1.26.2) | VM_MEM_ACCESS_EXEC (see section 1.26.2))

    Description:
    Convenience definition for read, write, and execute permissions.

VM_MEM_ACCESS_EXCL (VM_O_EXCL (see section 1.10.1))

    Description:
    For some function (like vm_map): If this bit is set, then mappings must not be replaced, but such an
    attempt should cause an error. The corresponding functions will specify whether this flag is supported.
    This corresponds to VM_O_EXCL (and actually has the same bit value for convenience), because the
    semantics is basically the same in open.

vm_memory_access_mode_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

vm_memory_access_mode_MAX 4

    Description:
    Maximum value of the enum type

vm_memory_access_mode_MASK 7

    Description:
    All values of this bitmask enum ORed together into a bitmask

VM_MEM_TYPE_RAM 0

    Description:
    General purpose random access memory.

VM_MEM_TYPE_IO_PORT 1

    Description:
    Real IO ports on platform that support this (like x86).

VM_MEM_TYPE_IO_MEM 2

    Description:
    Memory mapped IO area.

VM_MEM_TYPE_ROM 3

    Description:
    Read-only memory.


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Memory Allocation 365

VM_MEM_TYPE_KMEM 4

      Description:
      KMEM is a special type of memory that the kernel, PSSW, and drivers use for management data
      associated with partitions. There is a single memory pool of KMEM per partition, filled at boot time
      by the kernel.

vm_memory_type_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

vm_memory_type_MAX 4

      Description:
      Maximum value of the enum type

1.26.3 Data Type Definitions

P4_memreg_attr_t Memory region attribute info entry. Format of a info entry used by p4_mon_memreg_get_attr() (see section 1.23.4.13). vm_memory_access_mode_t Similar to vm_file_access_mode_t, there is this type that controls access permissions to memory. Only a subset of bits is supported here, but the values are made to coincide with the corresponding vm_file_access_mode_t values. vm_memory_type_t Specifies the type of memory in memory requirements in the configuration.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

366 The PikeOS Kernel API

1.26.4 Functions

1.26.4.1 p4_memmap_alloc_phys

Allocate memory region with known physical address.

Synopsis:

P4_e_t p4_memmap_alloc_phys(P4_phys_addr_t addr, P4_size_t length, P4_uint32_t memreg_id)

Parameters: addr IN: Address of physical memory to be allocated. The value must be a multiple of P4_PAGESIZE. length IN: Size of the to be allocated memory area. The value must be non-zero and a multiple of P4_PAGE- SIZE. memreg_id IN: Take memory from the memory region with this ID.

Description: A successful call to this function allocates the physical memory range given by addr and length. Otherwise no memory will be allocated. The allocated physical memory is taken from the memory region memreg_id. Using P4_MEMREG_GLOBAL for memreg_id will use the global memory region. Otherwise, memory region identifiers for memreg_id can be generated via the P4_MEMREG() (see section 1.26.2) helper. The memory range is marked as allocated and the user should create a mapping of it with p4_mem_create() (see section 1.15.6.6).

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_KMEM_HANDLING enabled. P4_E_INVAL if the physical memory range described by addr and length is not page aligned, has zero size, or overflows the physical address space. P4_E_NOENT if memreg_id does not refer to an existing memory region. P4_E_NOENT if the given physical memory range doesnt exist on the platform or if it is already allocated.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Memory Allocation 367

1.26.4.2 p4_memmap_alloc_aligned

Allocate memory with known physical alignment.

Synopsis:

P4_e_t p4_memmap_alloc_aligned(P4_uint32_t memreg_id, P4_address_t align, P4_size_t length, P4_address_t dest_addr, P4_phys_addr_t *phys_addr)

Parameters: memreg_id IN: Take memory from the memory region with this ID. align IN: Alignment requirement of the to be allocated memory block. If align is zero, a minimum alignment of P4_PAGESIZE is taken. Otherwise align must be a power of two. length IN: Size of the to be allocated memory area. The value must be non-zero and a multiple of P4_PAGE- SIZE. dest_addr IN: Destination address for the allocated memory in user space. Only necessary on platforms with cache aliasing effects to prevent side effects. The to be allocated memory block must match this requirement. phys_addr OUT: phys_addr contains the base address of the allocated memory in physical address space. In the case of other error codes others than P4_E_OK, phys_addr is undefined.

Description: A successful call to this function allocates a physical piece of memory of size length from the kernels free memory space in the memory region memreg_id. The allocated physical memory is taken from the memory region memreg_id. Using P4_MEMREG_GLOBAL for memreg_id will use the global memory region. Otherwise, memory region identifiers for memreg_id can be generated via the P4_MEMREG() (see section 1.26.2) helper. The memory range is marked as allocated and its physical address is returned in phys_addr. The user should create a mapping of it with p4_mem_create() (see section 1.15.6.6). The caller supplies an alignment align and the size of the memory piece by length. On platforms with cache aliasing effects, the destination address in user space dest_addr must be supplied.

Returns: Upon success, a call to this function returns P4_E_OK, otherwise one of the following error codes will be returned. P4_E_NOABILITY if the task of the calling thread does not have the ability P4_AB_KMEM_HANDLING enabled. P4_E_INVAL if length is zero or not page aligned, or if align is not zero or a power of two, or if phys_addr is NULL. P4_E_NOENT if memreg_id does not refer to an existing memory region. P4_E_ALIGN if align does not match dest_addr and the architectures cache aliasing mask. P4_E_NOENT if a memory piece matching the requirements couldnt be allocated.

Note:

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

368 The PikeOS Kernel API

Invalid pointers or unmapped memory areas for phys_addr will not raise an error in this system call.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

System Emulation 369

1.27 System Emulation

This section describes constants, data types, access macros, and service functions related to the system emula- tion API.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

370 The PikeOS Kernel API

1.27.1 Functions

1.27.1.1 p4_sysemu_enter

Enter SYSEMU state.

Synopsis:

P4_e_t p4_sysemu_enter(P4_task_t task, P4_regs_t *regs, P4_prio_t prio, P4_uint32_t flags)

Parameters: task IN: Task ID of the calling task or a child task in which the calling thread executes during SYSEMU state. regs IN: User mode context while running in SYSEMU state. prio IN: Priority of the calling thread during SYSEMU state. Values P4_PRIO_KEEP and P4_PRIO_INHERIT do not change the priority. The priority is limited to the MCP of the calling task. flags IN: Set of bits used to further control this operation. Currently, no flag bits are defined and zero must be set.

Description: On a successful call to this function, the calling thread enters SYSEMU state. During SYSEMU state, the thread executes:

  • in the address space of task task
  • using the register context in regs
  • at scheduling priority prio
  • without the ability to use p4 system calls
     until the thread raises an exception or is preempted from SYSEMU state by another thread.

     On return from SYSEMU state, the address space binding is released and the previous register context is
     saved in the register context defined by P4_tls_area_t::sysemu_regs (see section 1.20.1.1) in the thread
     local storage area of the calling thread. The thread continues execution at the registered SYSEMU return
     handler P4_tls_area_t::sysemu_handler (see section 1.20.1.1) on a stack P4_tls_area_t::sysemu_stack
     (see section 1.20.1.1) in its original address space. Any other application registers are clobbered. The
     scheduling priority is raised to the callers tasks MCP. Critical system registers are set to default values.
     The thread local storage area is set to the threads previously registered thread local storage area. See
     P4_tls_area_t::sysemu_flags (see section 1.20.1.1) how to further control the execution state of the return
     handler.

     Any exception raised in SYSEMU state must be handled by the SYSEMU return handler, no further excep-
     tion IPC can be raised.

     regs must not be NULL.

Note:

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

System Emulation 371

On entering SYSEMU state, the kernel loads the integer part of regs, but may skip loading any FPU or vector registers if the new register state indicates that the FPU or the vector unit are unused.

Note: The function p4_thread_preempt() (see section 1.16.5.12) can be used to request a thread to leave the SYSEMU state.

Note: The flags parameter is reserved for future use and must be zero.

Returns: Upon success, this function does not return, otherwise one of the following error codes is returned to the caller: P4_E_INVAL task is not a valid task ID. P4_E_INVAL if an invalid flag is set in flags. P4_E_BADTASK task task is not a child task of the caller. P4_E_STATE task task is a passive task of the caller. P4_E_STATE the caller has a pending deadline. P4_E_STATE The caller was stopped, deleted, preempted, or exregsed before SYSEMU state was entered. P4_E_STATE The caller is running in a preemption or exception handler function. P4_E_STATE The caller is registered as task notification handler. P4_E_INVAL if the calling thread has no registered thread local storage area. P4_E_INVAL if regs is NULL. P4_E_INVAL if regs does not point to a valid address or exceeds the callers virtual address space.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

372 The PikeOS Kernel API

1.28 User Space Locking

This section describes constants, data types, access macros, and service functions related to the PikeOS user space locking API.

1.28.1 Structure Definitions

1.28.1.1 struct P4_ulock_str

User space lock. This data type is used for user space locks.

Synopsis: struct P4_ulock_str { unsigned int lock; };

Structure Element Description: lock Lock state.

Associated Data Type

P4_ulock_t User space lock.

1.28.1.2 struct P4_rulock_list_elem_str

Robust user space lock list. This data type is a doubly linked list for robust user space locks.

Synopsis: struct P4_rulock_list_elem_str { struct P4_rulock_list_elem_str * next; struct P4_rulock_list_elem_str * prev; };

Structure Element Description: next Linked list next pointer. prev Linked list previous pointer (not used by the kernel).

Associated Data Type

P4_rulock_list_elem_t Robust user space lock list.

1.28.1.3 struct P4_rulock_str

Robust user space lock.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

User Space Locking 373

This data type is used for robust user space locks. A robust user space lock must implement the mutex protocol and the structure must be embedded into a P4_mutex_t mutex.

Synopsis: struct P4_rulock_str { unsigned int lock; unsigned int padding; P4_rulock_list_elem_t list; };

Structure Element Description: lock Lock state. padding padding (unused). list Linked list of robust user space locks.

Associated Data Type

P4_rulock_t Robust user space lock.

1.28.2 Defines

P4_ULOCK_LIMIT Ulock limit value. Description: This limit defines:

         • the maximum number of robust user space locks a thread can hold locked. If this limit is exceeded,
           subsequent calls to p4_mutex_lock() (see section 1.29.4.3) or p4_mutex_trylock() (see section
           1.29.4.4) will fail with error code P4_E_LIMIT.
         • the maximum number of ulock waiters woken up in a "wake all" operation (e.g., cond broadcast,
           barrier wait, etc.).

P4_ULOCK_WAITERS Pending waiters flag in mutex type user space lock. Description: This value (which is set in a user space lock objects lock element) indicates that the user space lock has pending waiters in the kernel.

P4_ULOCK_OWNER_DIED Owner died flag in mutex type user space lock. Description: This value (which is set in a user space lock objects lock element) indicates that the owner of the user space lock died.

P4_ULOCK_UID_MASK UID mask in user space lock.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

374 The PikeOS Kernel API

    Description:
    Mask to extract the UID of the lock holder from a user space lock object lock element.

P4_ULOCK_FREE Unlocked state of user space lock. Description: Unlocked state of a user space lock object lock element.

P4_ULOCK_SHARED Value definition for p4_ulock_wait() and p4_ulock_wake()flags parameter. Description: This value indicates to p4_ulock_wait() (see section 1.28.4.3) and p4_ulock_wake() (see section 1.28.4.4) that a user space lock is shareable between tasks. To use a shared user space lock, the calling threads task needs to have the ability P4_AB_ULOCK_SHARED enabled.

P4_ULOCK_MUTEX Value definition for p4_ulock_wait() and p4_ulock_wake()flags parameter. Description: This flag indicates to p4_ulock_wait() (see section 1.28.4.3) and p4_ulock_wake() (see section 1.28.4.4) that the user space lock is a mutex.

P4_ULOCK_COND Value definition for p4_ulock_wait() and p4_ulock_wake()flags parameter. Description: This value indicates to p4_ulock_wait() (see section 1.28.4.3) and p4_ulock_wake() (see section 1.28.4.4) that the user space lock is a condition variable.

P4_ULOCK_PRIO Value definition for p4_ulock_wait() and p4_ulock_wake()flags parameter. Description: This value indicates to p4_ulock_wait() (see section 1.28.4.3) and p4_ulock_wake() (see section 1.28.4.4) that the user space lock has priority order rather than FIFO order.

P4_ULOCK_PRIO_CHANGE Value definition for p4_ulock_wait() and p4_ulock_wake()flags parameter. Description: This value indicates to p4_ulock_wait() (see section 1.28.4.3) and p4_ulock_wake() (see section 1.28.4.4) that an additional priority value is encoded in the flags field using the P4_ULOCK_PRIO_SET() (see section 1.28.2) macro. p4_ulock_wait() (see section 1.28.4.3) atomically changes the scheduling priority to the encoded value before waiting. p4_ulock_wake() (see section 1.28.4.4) interprets this value as new scheduling priority of the calling thread when additionally changing the register context with the P4_ULOCK_SET_REGS flag. The flag P4_ULOCK_PRIO_CHANGE and the corresponding priority value are removed before the calls further evaluate flags.

                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

User Space Locking 375

P4_ULOCK_SHIFT_PRIO Shift for prio value in flags for P4_ULOCK_CHANGE_PRIO.

P4_ULOCK_MASK_PRIO Mask for prio value in flags for P4_ULOCK_CHANGE_PRIO.

P4_ULOCK_WAKE_ALL Value definition for p4_ulock_wake()flags parameter. Description: This value indicates to p4_ulock_wake() (see section 1.28.4.4) that all waiting threads shall be woken up.

P4_ULOCK_SET_REGS Value definition for p4_ulock_wake()flags parameter. Description: This value indicates to p4_ulock_wake() (see section 1.28.4.4) that the fourth argument refers to a register context.

P4_ULOCK_DELETE_SELF Value definition for p4_ulock_wake()flags parameter. Description: This value indicates to p4_ulock_wake() (see section 1.28.4.4) that the caller should be deleted after releasing the lock.

P4_ULOCK_PRIO_GET (flags) Extract the priority value encoded in the flags when using P4_ULOCK_CHANGE_PRIO in p4_ulock_wait() and p4_ulock_wake().

P4_ULOCK_PRIO_CLEAR (flags) Clear the priority contained within the flags when using P4_ULOCK_CHANGE_PRIO in p4_ulock_wait() and p4_ulock_wake().

P4_ULOCK_PRIO_SET (prio, flags) Encode the priority prio in flags for use with P4_ULOCK_CHANGE_PRIO in p4_ulock_wait() and p4_ulock_wake().

P4_ULOCK_INIT User space lock initializer. Description: Static initializer for user space locks, sets the lock to unlocked state.

     Note:
     Manipulation and handling of UIDs stored in user space locking objects require the proper masking via
     P4_ULOCK_UID_MASK to remove all information except the task number and the thread number.

     Note:
     Synchronization objects use atomic operations that are only guaranteed to work properly on cached
     mapped memory (memory mapped with P4_M_C_WB attributes).


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

376 The PikeOS Kernel API

P4_RULOCK_INIT Robust user space lock initializer. Description: Static initializer for robust user space locks, sets the lock to unlocked state.

      Note:
      Manipulation and handling of UIDs stored in user space locking objects require the proper masking via
      P4_ULOCK_UID_MASK to remove all information except the task number and the thread number.

      Note:
      Synchronization objects use atomic operations that are only guaranteed to work properly on cached
      mapped memory (memory mapped with P4_M_C_WB attributes).

1.28.3 Data Type Definitions

P4_ulock_t User space lock. This data type is used for user space locks. P4_rulock_list_elem_t Robust user space lock list. This data type is a doubly linked list for robust user space locks. P4_rulock_t Robust user space lock. This data type is used for robust user space locks. A robust user space lock must implement the mutex protocol and the structure must be embedded into a P4_mutex_t mutex.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

User Space Locking 377

1.28.4 Functions

1.28.4.1 p4_ulock_init

Initialize a user space lock to unlocked state.

Synopsis:

__forceinline void p4_ulock_init(P4_ulock_t *ulock)

Parameters: ulock INOUT: User space locking object

Description: This function initializes the user space lock ulock to unlocked state.

Note: Manipulation and handling of UIDs stored in user space locking objects require the proper masking via P4_ULOCK_UID_MASK to remove all information except the task number and the thread number.

Note: Synchronization objects use atomic operations that are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

378 The PikeOS Kernel API

1.28.4.2 p4_rulock_init

Initialize a robust user space lock to unlocked state.

Synopsis:

__forceinline void p4_rulock_init(P4_rulock_t *ulock)

Parameters: ulock INOUT: Robust user space locking object

Description: This function initializes the robust user space locks rulock to unlocked state.

Note: Manipulation and handling of UIDs stored in user space locking objects require the proper masking via P4_ULOCK_UID_MASK to remove all information except the task number and the thread number.

Note: Synchronization objects use atomic operations that are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

User Space Locking 379

1.28.4.3 p4_ulock_wait

Wait to acquire a user space lock.

Synopsis:

P4_e_t p4_ulock_wait(P4_timeout_t timeout, void *ulock, P4_uint32_t flags, unsigned int compare, void *ulock2)

Parameters: timeout IN: Maximum time to wait to acquire the lock ulock INOUT: User space locking object flags IN: Flags and operation mode compare IN: compare value ulock2 INOUT: Second user space locking object

Description: This function blocks on the user space lock ulock with timeout timeout until it is woken up by p4_ulock_wake() (see section 1.28.4.4). Only threads of the same lock type (mutex, condition, counter) can block on the same lock. The flags argument further defines the behaviour of this call. The same set of flags must be passed to p4_ulock_wait() (see section 1.28.4.3) and p4_ulock_wake() (see section 1.28.4.4).

• If P4_ULOCK_SHARED is set, the lock is shareable between tasks. • If P4_ULOCK_PRIO is set, the set of waiting threads is ordered by thread priority instead of FIFO order. • Flag P4_ULOCK_MUTEX enables mutex mode. compare and ulock2 are ignored and this function tries to acquire the mutex ulock for the calling thread. If the mutex is already locked by another thread, the functions blocks in the kernel until it acquires the lock or the timeout timeout expires. On successful acquisition of the mutex ulock, the calling thread is registered as mutex owner of ulock via setting its UID in the lock element of ulock. If the mutex ulock is already locked and no other waiters are pending, the P4_ULOCK_WAITERS flag will be set in the lock element of mutex. • If P4_ULOCK_COND is set, ulock acts as a condition variable. The value of the condition variable is compared with compare before the calling thread is blocked. ulock2 refers to a mutex which shall be acquired when the condition is signaled. If the mutex cant be locked immediately, the calling thread will block on this condition with a timeout of P4_TIMEOUT_INFINITE. • If P4_ULOCK_PRIO_CHANGE is set, the callers priority will be changed to the priority encoded within the flags argument before blocking on the ulock. The new priority can be encoded in flags using the P4_ULOCK_PRIO_SET() (see section 1.28.2) macro. Both the encoded priority and the P4_ULOCK_PRIO_CHANGE flags are removed from flags before the actual suspension of the caller: this allow the wake counterpart to be unaware of the use of this flag from the waiters. If the caller is not subject to suspension (the error code is different from P4_E_OK or P4_E_TIMEOUT), the priority is not altered. • The registration and checking of UIDs identifying threads owning a user space locking object is performed on the related lock element of this structure. For user space locking objects already owned by a thread, other threads trying to acquire this object will be appended to a wait queue internally in the kernel. Flags combinations:

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

380 The PikeOS Kernel API

  • If both P4_ULOCK_COND and P4_ULOCK_MUTEX are clear, ulock is a counter and compared with
    compare before blocking the calling thread. ulock2 is ignored.
  • Flags P4_ULOCK_MUTEX and P4_ULOCK_COND should not be set at the same time.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if ulock is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_INVAL if P4_ULOCK_COND is set in flags and ulock2 is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_INVAL if flags contains an unsupported combination of flags. P4_E_PAGEFAULT if ulock or ulock2 are not fully mapped in the callers virtual address space. P4_E_PAGEFAULT if the cache attributes for the mapping of ulock2 mismatch (e.g., the memory is mapped as uncached) when trying to acquire the mutex ulock2 after the condition ulock has been signaled (P4_ULOCK_COND flag set). P4_E_BADTIMEOUT if the specified timeout is invalid or in the past. P4_E_TIMEOUT if the specified timeout has expired before the lock was acquired by the caller. P4_E_CANCEL if the function was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU. P4_E_STATE if ulock does not match compare. P4_E_STATE if ulock in P4_ULOCK_MUTEX mode could not be updated atomically. P4_E_BADUID if ulock or ulock2 reference invalid waiting threads. P4_E_ABORT if the previous owner of the robust user space lock ulock died. P4_E_NOABILITY if a user space lock is shareable (P4_ULOCK_SHARED set in flags), but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: This call is always implemented as a system call.

Note: Manipulation and handling of UIDs stored in user space locking objects require the proper masking via P4_ULOCK_UID_MASK to remove all information except the task number and the thread number.

Note: The use of shareable user space locks requires the P4_AB_ULOCK_SHARED ability.

Note: In mutex mode, the caller has the mutex locked only if error code P4_E_OK is returned.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

User Space Locking 381

1.28.4.4 p4_ulock_wake

Wakeup threads waiting on a user space lock.

Synopsis:

P4_e_t p4_ulock_wake(void *ulock, P4_uint32_t flags, unsigned int compare, void *ptr)

Parameters: ulock INOUT: User space locking object flags IN: Flags and operation mode compare IN: compare value, must be zero ptr INOUT: Pointer, meaning depends on flags

Description: This function unblocks threads blocked on the user space lock ulock. The flags argument further defines the behaviour of this call. The same set of flags must be passed to p4_ulock_wait() (see section 1.28.4.3) and p4_ulock_wake() (see section 1.28.4.4).

• If P4_ULOCK_SHARED is set, the lock is shareable between tasks. • If P4_ULOCK_PRIO is set, the set of waiting threads is ordered by thread priority instead of FIFO order. • If P4_ULOCK_MUTEX is set, the woken up thread will acquire ulock as mutex. Flag P4_ULOCK_WAKE_ALL is ignored. • If P4_ULOCK_COND is set, the condition variable ulock is signaled or broadcasted, depending on P4_ULOCK_WAKE_ALL. Depending on kind of operation, signal or broadcast, either one or all threads are queued on their registered mutex lock. If the mutex is not currently locked, the first thread is woken up and the mutex is passed to it. • If P4_ULOCK_WAKE_ALL is set, all waiting threads are woken up. Otherwise the first waiting thread only is woken up. • If P4_ULOCK_SET_REGS is set, ptr refers to a register context of type P4_regs_t which shall be set as new register context of the calling thread after unlocking. Additionally, the P4_ULOCK_PRIO_CHANGE flag controls the new priority when setting a new register context:

       ◦ If P4_ULOCK_PRIO_CHANGE is set, the callers priority will be changed to the priority en-
         coded within the flags argument. The new priority can be encoded in flags using the
         P4_ULOCK_PRIO_SET() (see section 1.28.2) macro.          Both the encoded priority and the
         P4_ULOCK_PRIO_CHANGE flags are removed from flags before further evaluation of flags.
       ◦ If P4_ULOCK_PRIO_CHANGE is not set, the callers priority will be set implicitly to P4_PRIO_IN-
         HERIT.

• If P4_ULOCK_DELETE_SELF is set, the calling thread deletes itself after successfully performing the operation on the user space lock. • Threads waiting on a user space locking object are registered via a kernel-internal wait queue. Flags precendence and combinations:

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

382 The PikeOS Kernel API

  • If both P4_ULOCK_COND and P4_ULOCK_MUTEX are clear, threads waiting on the counter ulock are
    woken up.
  • P4_ULOCK_MUTEX and P4_ULOCK_COND should not be set at the same time.
  • P4_ULOCK_DELETE_SELF takes precedence over P4_ULOCK_SET_REGS.
  • P4_ULOCK_PRIO_CHANGE and the encoded priority are ignored by all operations except
    P4_ULOCK_SET_REGS.

Note: The kernel limits the number of woken threads to P4_ULOCK_LIMIT.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if ulock is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_INVAL if flags contains an unsupported combination of flags. P4_E_INVAL if compare is not zero. P4_E_INVAL if P4_ULOCK_SET_REGS is set in flags and ptr is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT if ulock is not fully mapped in the callers virtual address space. P4_E_BADUID if ulock references invalid waiting threads. P4_E_LIMIT if the number of threads to be woken up exceeds P4_ULOCK_LIMIT. At most P4_ULOCK_LIMIT threads are woken up. P4_E_NOABILITY if a user space lock is shareable (P4_ULOCK_SHARED set in flags), but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: The compare argument is currently unused and must be set to zero.

Note: Manipulation and handling of UIDs stored in user space locking objects require the proper masking via P4_ULOCK_UID_MASK to remove all information except the task number and the thread number.

Note: If P4_ULOCK_SET_REGS is set and if a page fault occurs when accessing ptr, the register context of the calling thread is in an undefined state, which also affects the error code. In this case, this function will raise an exception of type P4_TRAP_CTXT. Depending on the action taken by the exception handlers, p4_ulock_wake() (see section 1.28.4.4) may never return. The lock is always unlocked before changing the register context.

Note: The use of shareable user space locks requires the P4_AB_ULOCK_SHARED ability.

Note: This call is always implemented as a system call.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mutexes 383

1.29 Mutexes

This section describes constants, data types, access macros, and service functions related to the PikeOS user space mutex API.

1.29.1 Structure Definitions

1.29.1.1 struct P4_mutex_str

Mutex. This opaque type is used for mutexes.

Synopsis: struct P4_mutex_str { P4_rulock_t lock; P4_uint32_t count; P4_uint32_t flags; };

Structure Element Description: lock Internal lock. count Reference count. flags Mutex flags.

Associated Data Type

P4_mutex_t Mutex.

1.29.2 Defines

P4_MUTEX_RECURSIVE Recursive mutex flag. Description: This mutex flag indicates a mutex may be acquired recursively.

P4_MUTEX_ROBUST Robust mutex flag. Description: This mutex flag indicates a robust mutex, i. e. threads waiting to acquire a mutex are notified if the mutex owner dies.

P4_MUTEX_CANCELABLE Cancelable mutex flag. Description: This mutex flag indicates a mutex is cancelable and a p4_mutex_lock() (see section 1.29.4.3) operation returns P4_E_CANCEL if the waiting thread is unblocked.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

384 The PikeOS Kernel API

P4_MUTEX_SHARED Shared mutex flag. Description: This mutex flag indicates that a mutex is shareable by multiple tasks. To use a shareable mutex, the calling threads task needs to have the ability P4_AB_ULOCK_SHARED enabled.

P4_MUTEX_PRIO Priority ordered mutexes. Description: This mutex flag indicates that waiting threads are ordered by thread priority.

P4_MUTEX_MAX_RECURSION Maximum depth of a recursive mutex. Description: If a mutex recursion counter has this value, subsequent calls to p4_mutex_lock() (see section 1.29.4.3) or p4_mutex_trylock() (see section 1.29.4.4) will fail with error code P4_E_LIMIT.

P4_MUTEX_INIT Mutex initializer. Description: Static initializer for mutexes, sets the lock to unlocked state and non-recursive, non-robust, non- shareable type.

      Note:
      Synchronization objects use atomic operations that are only guaranteed to work properly on cached
      mapped memory (memory mapped with P4_M_C_WB attributes).

P4_MUTEX_INIT_FLAGS (FLAGS) Mutex initializer with flags. Description: Static initializer for mutexes, sets the lock to unlocked state with type defined by the given FLAGS

      Note:
      Synchronization objects use atomic operations that are only guaranteed to work properly on cached
      mapped memory (memory mapped with P4_M_C_WB attributes).

1.29.3 Data Type Definitions

P4_mutex_t Mutex. This opaque type is used for mutexes.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mutexes 385

1.29.4 Functions

1.29.4.1 p4_mutex_init

Initialize a mutex to unlocked state.

Synopsis:

__forceinline void p4_mutex_init(P4_mutex_t *mutex, P4_uint32_t flags)

Parameters: mutex OUT: Mutex object flags IN: Mutex flags

Description: This function initializes the mutex mutex to unlocked state. If P4_MUTEX_SHARED is set in flags, the mutex is shareable by multiple tasks. If P4_MUTEX_RECURSIVE is set in flags, the mutex can be acquired recursively. If P4_MUTEX_CANCELABLE is set in flags, blocking mutex operations can be cancelled and the mutex lock function returns P4_E_CANCEL. If P4_MUTEX_ROBUST is set in flags, threads blocking on a mutex get notified when the mutex owner dies. If P4_MUTEX_PRIO is set in flags, waiting threads are ordered by their corresponding thread priorities rather than FIFO order.

Note: Synchronization objects use atomic operations that are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

386 The PikeOS Kernel API

1.29.4.2 p4_mutex_owned

Test mutex lock owner.

Synopsis:

P4_bool_t p4_mutex_owned(P4_mutex_t *mutex, P4_uid_t uid)

Parameters: mutex IN: Mutex object uid IN: UID

Description: This function compares the owner of the mutex mutex to uid. The time partition and resource partition information included in uid is ignored in the comparison.

Returns: Returns TRUE if uid is the owner of mutex, otherwise returns FALSE.

Note: The lock owner is transient and may have changed by the time this call returns.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mutexes 387

1.29.4.3 p4_mutex_lock

Lock mutex.

Synopsis:

P4_e_t p4_mutex_lock(P4_mutex_t *mutex, P4_timeout_t timeout)

Parameters: mutex INOUT: Mutex object timeout IN: Timeout

Description: This function tries to lock the mutex mutex. If the mutex is already locked by another thread, the functions blocks in the kernel until it acquires the lock or the timeout timeout expires. For recursive mutexes, the mutex counter is increased on recursive lock attempts. If error codes P4_E_OK or P4_E_STATE are returned, the caller owns the mutex. If the thread is unblocked by another thread, the calling thread will block again unless the mutex is cancelable.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_STATE if the caller already owns the mutex (recursive locking attempt on non-recursive mutex). P4_E_LIMIT if the maximum recursion level P4_MUTEX_MAX_RECURSION is reached. P4_E_LIMIT if the maximum number of robust mutexes is reached. P4_E_BADTIMEOUT if the specified timeout is invalid or in the past. P4_E_TIMEOUT if the specified timeout has expired before the lock was acquired by the caller. P4_E_INVAL if mutex is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT if mutex is not fully mapped in the callers virtual address space. P4_E_CANCEL if the mutex is cancelable (flag P4_MUTEX_CANCELABLE is set), and the function was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU. P4_E_BADUID if mutex references invalid waiting threads. P4_E_ABORT if the previous lock owner of the robust mutex mutex died. Note that at most P4_ULOCK_LIMIT threads waiting for a robust mutex are woken up when the lock owner dies. P4_E_NOABILITY if the mutex is shareable (P4_MUTEX_SHARED is used), but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: Mutexes must be initialized before using.

Note: The use of shareable mutexes requires the P4_AB_ULOCK_SHARED ability.

Note:

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

388 The PikeOS Kernel API

Mutexes depend on thread local storage.

Note: If mutex is NULL or an invalid pointer, this function may cause an exception.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Mutexes 389

1.29.4.4 p4_mutex_trylock

Try to lock mutex.

Synopsis:

P4_e_t p4_mutex_trylock(P4_mutex_t *mutex)

Parameters: mutex INOUT: Mutex object

Description: This function tries to lock the mutex mutex. If the mutex is already locked by another thread, the functions returns immediately. For recursive mutexes, the mutex counter is increased on recursive lock attempts. If error codes P4_E_OK or P4_E_STATE are returned, the caller owns the mutex.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_STATE if the caller already owns the mutex (recursive locking attempt on non-recursive mutex). P4_E_LIMIT if the maximum recursion level P4_MUTEX_MAX_RECURSION is reached. P4_E_LIMIT if the maximum number of robust mutexes is reached. P4_E_TIMEOUT if mutex is currently locked by another thread.

Note: Mutexes must be initialized before using.

Note: The use of shareable mutexes requires the P4_AB_ULOCK_SHARED ability.

Note: Mutexes depend on thread local storage.

Note: If mutex is NULL or an invalid pointer, this function may cause an exception.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

390 The PikeOS Kernel API

1.29.4.5 p4_mutex_unlock

Unlock mutex.

Synopsis:

P4_e_t p4_mutex_unlock(P4_mutex_t *mutex)

Parameters: mutex INOUT: Mutex object

Description: This function tries to unlock the mutex mutex locked by the calling thread. For recursive mutexes, the mutex counter is decreased on recursive unlocks and finally freed if the counter reaches zero.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_STATE if mutex is not locked by the caller. P4_E_INVAL if mutex is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT if mutex is not fully mapped in the callers virtual address space. P4_E_BADUID if mutex references invalid waiting threads. P4_E_ABORT if the previous lock owner of the robust mutex mutex died. P4_E_NOABILITY if the mutex is shareable (P4_MUTEX_SHARED is used), but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: Mutexes must be initialized before using.

Note: The use of shareable mutexes requires the P4_AB_ULOCK_SHARED ability.

Note: Mutexes depend on thread local storage.

Note: If mutex is NULL or an invalid pointer, this function may cause an exception.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Condition variables 391

1.30 Condition variables

This section describes constants, data types, access macros, and service functions related to the PikeOS user space condition variables API.

1.30.1 Structure Definitions

1.30.1.1 struct P4_cond_str

Condition variable. This opaque type is used for condition variables.

Synopsis:

struct P4_cond_str { P4_ulock_t lock; };

Structure Element Description: lock Internal lock.

Associated Data Type

P4_cond_t Condition variable.

1.30.2 Defines

P4_COND_SHARED Shared condition variable flag. Description: This flag indicates that a condition variable is shareable by multiple tasks. To use a shareable condition variable, the calling threads task needs to have the ability P4_AB_ULOCK_SHARED enabled.

P4_COND_PRIO Priority ordered condition variables. Description: This flag indicates that waiting threads are ordered by thread priority. Must match the flag specified in the associated mutex.

P4_COND_WAKE_ALL Value definition for p4_cond_wake()flags parameter. Description: This value indicates to p4_cond_wake() (see section 1.30.4.3) that all waiting threads shall be woken up.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

392 The PikeOS Kernel API

P4_COND_INIT Condition variable initializer. Description: Static initializer for condition variables. It initializes the condition variable to non-shareable type.

      Note:
      Synchronization objects use atomic operations that are only guaranteed to work properly on cached
      mapped memory (memory mapped with P4_M_C_WB attributes).

1.30.3 Data Type Definitions

P4_cond_t Condition variable. This opaque type is used for condition variables.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Condition variables 393

1.30.4 Functions

1.30.4.1 p4_cond_init

Initialize a condition variable.

Synopsis:

__forceinline void p4_cond_init(P4_cond_t *cond, P4_uint32_t flags)

Parameters: cond OUT: Condition variable object flags IN: Condition variable flags

Description: This function initializes the condition variable cond. If P4_COND_SHARED is set in flags, the condition variable is shareable by multiple tasks. If P4_COND_PRIO is set in flags, waiting threads are ordered by their corresponding thread priorities rather than FIFO order.

Note: Synchronization objects use atomic operations that are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

394 The PikeOS Kernel API

1.30.4.2 p4_cond_wait

Wait on a condition.

Synopsis:

P4_e_t p4_cond_wait(P4_cond_t *cond, P4_mutex_t *mutex, P4_timeout_t timeout)

Parameters: cond INOUT: Condition variable mutex INOUT: Mutex timeout IN: Timeout

Description: This function suspends the calling thread on the condition variable cond until the condition is signaled by p4_cond_signal() (see section 1.30.4.4) or p4_cond_broadcast() (see section 1.30.4.5) or the timeout timeout expires. The caller must have the mutex mutex locked before calling. The mutex is unlocked immediately before blocking, and locked again after the condition is signaled, the timeout expires, or waiting is cancelled otherwise. The caller waits with P4_TIMEOUT_INFINITE on the mutex lock. The mutex and cond must have the same queuing strategy (either FIFO / FIFO, or PRIO / PRIO) and the same shareable attribute. On errors codes other than P4_E_OK, P4_E_STATE, P4_E_TIMEOUT, P4_E_BADTIMEOUT, or P4_E_CANCEL, the mutex state is undefined (probably no longer locked). For cancelable mutexes, P4_E_CANCEL can also mean that the mutex is in undefined state. The caller should then use p4_mutex_owned() (see section 1.29.4.2) to check if the caller owns the mutex or not before proceeding. When using a condition variable there is always a boolean predicate associated with the cond that is true if the calling thread should proceed. A return from the wait does not necessarily imply that such a predicate is either true or false. The calling thread has to re-evaluate the predicate to determine whether it can safely proceed.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_STATE if cond and mutex have different shareable attributes or define a different queuing strategy (see P4_COND_PRIO and P4_MUTEX_PRIO). P4_E_STATE if the caller does not own the mutex or owns it recursively. P4_E_BADTIMEOUT if the specified timeout is invalid or in the past. P4_E_TIMEOUT if the specified timeout has expired before the condition was signaled. P4_E_INVAL if cond or mutex are NULL or do not point to valid addresses or exceed the callers virtual address space. P4_E_PAGEFAULT if cond or mutex are not fully mapped in the callers virtual address space. P4_E_PAGEFAULT if the cache attributes for the mapping of mutex mismatch (e.g., the memory is mapped as uncached) when trying to acquire the mutex after the condition cond has been signaled. P4_E_CANCEL if the function was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Condition variables 395

P4_E_BADUID if cond or mutex reference invalid waiting threads. P4_E_ABORT if mutex is a robust mutex and its lock owner died. P4_E_NOABILITY if the mutex or the condition variable is shareable, but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: Mutexes and condition variables must be initialized before using.

Note: The use of shareable mutexes and condition variables requires the P4_AB_ULOCK_SHARED ability.

Note: Mutexes and condition variables depend on thread local storage.

Note: If cond or mutex are NULL or invalid pointers, this function may cause an exception.

Note: Synchronization objects use atomic operations that are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

396 The PikeOS Kernel API

1.30.4.3 p4_cond_wake

Signal or broadcast a condition.

Synopsis:

P4_e_t p4_cond_wake(P4_cond_t *cond, P4_uint32_t flags)

Parameters: cond INOUT: Condition variable flags IN: Flags and operation mode

Description: A call to this function signals unblocks one or all of the threads waiting for the condition cond. If no threads are currently waiting on the condition cond, this call has no effect. The woken threads try to acquire their associated mutexes then. If P4_COND_WAKE_ALL is set in flags, all waiting threads are woken up. Otherwise the first waiting thread only is woken up.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if cond is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_INVAL if an invalid flag is set in flags. P4_E_PAGEFAULT if cond is not fully mapped in the callers virtual address space. P4_E_BADUID if cond references invalid waiting threads. P4_E_ABORT if the support mutex associated with cond is a robust mutex and its lock owner died. P4_E_LIMIT if more than P4_ULOCK_LIMIT threads are woken up. P4_E_NOABILITY if the condition variable is shareable (P4_COND_SHARED is used), but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: Condition variables must be initialized before using.

Note: The use of shareable condition variables requires the P4_AB_ULOCK_SHARED ability.

Note: If cond is NULL or an invalid pointer, this function may cause an exception.

Note: Synchronization objects use atomic operations that are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Condition variables 397

1.30.4.4 p4_cond_signal

Signal a condition.

Synopsis:

__forceinline P4_e_t p4_cond_signal(P4_cond_t *cond)

Parameters: cond INOUT: Condition variable

Description: A call to this function signals unblocks one of the threads waiting for the condition cond. If no threads are currently waiting on the condition cond, this call has no effect. The woken thread tries to acquire its associated mutex then. This function is a convenience function implemented using p4_cond_wake() (see section 1.30.4.3).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if cond is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT if cond is not fully mapped in the callers virtual address space. P4_E_BADUID if cond references invalid waiting threads. P4_E_ABORT if the support mutex associated with cond is a robust mutex and its lock owner died. P4_E_NOABILITY if the condition variable is shareable (P4_COND_SHARED is used), but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: Condition variables must be initialized before using.

Note: The use of shareable condition variables requires the P4_AB_ULOCK_SHARED ability.

Note: If cond is NULL or an invalid pointer, this function may cause an exception.

Note: Synchronization objects use atomic operations that are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

398 The PikeOS Kernel API

1.30.4.5 p4_cond_broadcast

Broadcast a condition.

Synopsis:

__forceinline P4_e_t p4_cond_broadcast(P4_cond_t *cond)

Parameters: cond INOUT: Condition variable

Description: A call to this function signals unblocks all of the threads waiting for the condition cond. If no threads are currently waiting on the condition cond, this call has no effect. The woken threads try to acquire their associated mutexes then. This function is a convenience function implemented using p4_cond_wake() (see section 1.30.4.3).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if cond is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT if cond is not fully mapped in the callers virtual address space. P4_E_BADUID if cond references invalid waiting threads. P4_E_ABORT if the support mutex associated with cond is a robust mutex and its lock owner died. P4_E_LIMIT if more than P4_ULOCK_LIMIT threads are woken up. P4_E_NOABILITY if the condition variable is shareable (P4_COND_SHARED is used), but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: Condition variables must be initialized before using.

Note: The use of shareable condition variables requires the P4_AB_ULOCK_SHARED ability.

Note: If cond is NULL or an invalid pointer, this function may cause an exception.

Note: Synchronization objects use atomic operations that are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Semaphores 399

1.31 Semaphores

This section describes constants, data types, access macros, and service functions related to the PikeOS user space semaphores API.

1.31.1 Structure Definitions

1.31.1.1 struct P4_sem_str

Semaphore. This opaque type is used for semaphores.

Synopsis: struct P4_sem_str { P4_ulock_t lock; };

Structure Element Description: lock Internal lock.

Associated Data Type

P4_sem_t Semaphore.

1.31.2 Defines

P4_SEM_SHARED Shared semaphore flag. Description: This flag indicates that a semaphore is shareable by multiple tasks. To use a shareable semaphore, the calling threads task needs to have the ability P4_AB_ULOCK_SHARED enabled.

P4_SEM_MAX_COUNT Maximum count of a semaphore. Description: If a semaphore counter has this value, subsequent calls to p4_sem_post() (see section 1.31.4.5) will fail with error code P4_E_LIMIT.

1.31.3 Data Type Definitions

P4_sem_t Semaphore. This opaque type is used for semaphores.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

400 The PikeOS Kernel API

1.31.4 Functions

1.31.4.1 p4_sem_init

Initialize a semaphore.

Synopsis:

__forceinline void p4_sem_init(P4_sem_t *sem, unsigned int start, P4_uint32_t flags)

Parameters: sem OUT: Semaphore object start IN: Counter value flags IN: Semaphore flags

Description: This function initializes the semaphore sem to counter value start. If P4_SEM_SHARED is set in flags, the semaphore is shareable by multiple tasks.

Note: The value of start must be less or equal to P4_SEM_MAX_COUNT.

Note: Synchronization objects use atomic operations that are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Semaphores 401

1.31.4.2 p4_sem_value

Get semaphore counter value.

Synopsis:

P4_uint32_t p4_sem_value(P4_sem_t *sem)

Parameters: sem IN: Semaphore object

Description: This function returns a semaphores counter value.

Returns: Semaphore counter value. A value of zero indicates that there might be threads waiting on this semaphore, because the available resources protected by it are already in use.

Note: The counter value is transient and may have changed by the time this call returns.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

402 The PikeOS Kernel API

1.31.4.3 p4_sem_wait

Lock semaphore.

Synopsis:

P4_e_t p4_sem_wait(P4_sem_t *sem, P4_timeout_t timeout)

Parameters: sem INOUT: Semaphore object timeout IN: Timeout

Description: This function tries to lock the semaphore sem by decrementing the semaphore counter if the counter value is not zero. If count equals zero, the caller blocks until woken by p4_sem_post() (see section 1.31.4.5). In case of errors, the semaphore counter remains unchanged.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_BADTIMEOUT if the specified timeout is invalid or in the past. P4_E_TIMEOUT if the specified timeout has expired before the lock was acquired by the caller. P4_E_INVAL if sem is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_LIMIT if the caller could not acquire sem and the number of waiting threads would exceed P4_SEM_MAX_COUNT. P4_E_PAGEFAULT if sem is not fully mapped in the callers virtual address space. P4_E_BADUID if sem references invalid waiting threads. P4_E_CANCEL if the function was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU. P4_E_NOABILITY if the semaphore is shareable (P4_SEM_SHARED is used), but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: Semaphores must be initialized before using.

Note: The use of shareable semaphores requires the P4_AB_ULOCK_SHARED ability.

Note: If sem is NULL or an invalid pointer, this function may cause an exception.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Semaphores 403

1.31.4.4 p4_sem_trywait

Try to lock semaphore.

Synopsis:

P4_e_t p4_sem_trywait(P4_sem_t *sem)

Parameters: sem INOUT: Semaphore object

Description: This function tries to lock the semaphore sem by decrementing the semaphore counter if the counter value is not zero. This function does not block. In case of errors, the semaphore counter remains unchanged.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_TIMEOUT if sem can not be locked without waiting.

Note: Semaphores must be initialized before using.

Note: The use of shareable semaphores requires the P4_AB_ULOCK_SHARED ability.

Note: If sem is NULL or an invalid pointer, this function may cause an exception.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

404 The PikeOS Kernel API

1.31.4.5 p4_sem_post

Unlock semaphore.

Synopsis:

P4_e_t p4_sem_post(P4_sem_t *sem)

Parameters: sem INOUT: Semaphore object

Description: This function unlocks the semaphore sem by incrementing the semaphore counter. If there are waiting threads, one is unblocked and will try to lock the semaphore. Except for error code P4_E_LIMIT, this function always increments the semaphore counter

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if sem is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT if sem is not fully mapped in the callers virtual address space. P4_E_BADUID if sem references invalid waiting threads. P4_E_LIMIT if the semaphore counter is P4_SEM_MAX_COUNT and would overflow on further increments. P4_E_NOABILITY if the semaphore is shareable (P4_SEM_SHARED is used), but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: Semaphores must be initialized before using.

Note: The use of shareable semaphores requires the P4_AB_ULOCK_SHARED ability.

Note: If sem is NULL or an invalid pointer, this function may cause an exception.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Synchronization Barriers 405

1.32 Thread Synchronization Barriers

This section describes constants, data types, access macros, and service functions related to the PikeOS user space thread synchronization barrier API.

1.32.1 Structure Definitions

1.32.1.1 struct P4_barrier_str

Thread synchronization barrier. This opaque type is used for thread synchronization barriers.

Synopsis: struct P4_barrier_str { P4_ulock_t lock; unsigned int num_thread; };

Structure Element Description: lock Internal lock. num_thread thread maximum count

Associated Data Type

P4_barrier_t Thread synchronization barrier.

1.32.2 Defines

P4_BARRIER_SHARED Shared thread synchronization barrier flag. Description: This flag indicates that a barrier is shareable by multiple tasks. To use a barrier semaphore, the calling threads task needs to have the ability P4_AB_ULOCK_SHARED enabled.

P4_BARRIER_MAX_THREAD Maximum number of threads handled by a thread synchronization barrier. Description: Defines the maximum number of threads handled by a synchronization barrier.

1.32.3 Data Type Definitions

P4_barrier_t Thread synchronization barrier. This opaque type is used for thread synchronization barriers.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

406 The PikeOS Kernel API

1.32.4 Functions

1.32.4.1 p4_barrier_init

Initialize a thread synchronization barrier.

Synopsis:

P4_e_t p4_barrier_init(P4_barrier_t *barrier, unsigned int num_thread, P4_uint32_t flags)

Parameters: barrier OUT: Barrier object num_thread IN: Number of threads flags Barrier flags

Description: This function initializes the thread synchronization barrier barrier for num_thread threads. The value of num_thread must be greater than zero and less than or equal to P4_BARRIER_MAX_THREAD. If P4_BARRIER_SHARED is set in flags, the barrier is shareable by multiple tasks.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if num_thread is zero or greater than P4_BARRIER_MAX_THREAD. P4_E_INVAL if an invalid flag is set in flags.

Note: Synchronization objects use atomic operations that are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Thread Synchronization Barriers 407

1.32.4.2 p4_barrier_wait

Wait and synchronize at a thread synchronization barrier.

Synopsis:

P4_e_t p4_barrier_wait(P4_barrier_t *barrier)

Parameters: barrier INOUT: Barrier object

Description: A call to this function synchronizes the calling thread with other threads on the thread synchronization barrier barrier. The function blocks until the specified number of threads have reached this barrier as well by calling this function on the same barrier object. When the specified number of threads have reached the barrier, the barrier is released (i.e. all waiting threads are woken up) and this function return P4_E_LIMIT.

Note: Error code P4_E_OK indicates that the caller blocked on the barrier. Error code P4_E_LIMIT indicates that the caller released the barrier, i.e., the thread receiving this error code is the "last" thread synchronizing on the barrier and causing the specified number of threads (num_thread in barrier_init()) to be reached.

Returns: Upon success, this function returns P4_E_OK or P4_E_LIMIT, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if barrier is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT if barrier is not fully mapped in the callers virtual address space. P4_E_BADUID if barrier references invalid waiting threads. P4_E_NOABILITY if the barrier is shareable (P4_BARRIER_SHARED is used), but the task of the calling thread does not have the ability P4_AB_ULOCK_SHARED enabled.

Note: Barriers must be initialized before using.

Note: The use of shareable barriers requires the P4_AB_ULOCK_SHARED ability.

Note: If barrier is NULL or an invalid pointer, this function may cause an exception.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

408 The PikeOS Kernel API

1.33 One Time Initialization

This section describes constants, data types, access macros, and service functions related to the PikeOS user space "once" API.

1.33.1 Structure Definitions

1.33.1.1 struct P4_once_str

One time initializer. This opaque type is used for one time initializers.

Synopsis: struct P4_once_str { P4_ulock_t lock; };

Structure Element Description: lock Internal state.

Associated Data Type

P4_once_t One time initializer.

1.33.2 Defines

P4_ONCE_INIT
    Static initializer for one time initialization.
        Description:
        Static initializer for initializer objects, set them to "not done" state.

1.33.3 Data Type Definitions

P4_once_t One time initializer.
        This opaque type is used for one time initializers.


                                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

One Time Initialization 409

1.33.4 Functions

1.33.4.1 p4_once

One time initializer.

Synopsis:

void p4_once(P4_once_t *once, void(*init_func)(void))

Parameters: once INOUT: "Once" object init_func IN: Initializer callback

Description: On the first call, this function calls the user supplied initializer function init_func. After initialization, the function sets the initialization phase to "done" in once, so that subsequent calls to this function will not call init_func. This function handles concurrent calls on the same once object, only one function will call the initializer, others block until initialization is complete. The internal blocking can not be cancelled.

Note: Once objects must be initialized with P4_ONCE_INIT before using.

Note: If once is NULL or an invalid pointer, this function may cause an exception.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

410 The PikeOS Kernel API

1.34 Atomic Operations

This section describes constants, data types, access macros, and service functions related to the PikeOS user space API for atomic operations.

1.34.1 Defines

P4_ATOMIC_INIT Atomic data type static initializer. Description: The atomic data type is initialized to zero. For initialization with other values use p4_atomic_write() (see section 1.34.2.1).

       Note:
       Atomic operations are only guaranteed to work properly on cached mapped memory (memory mapped
       with P4_M_C_WB attributes).


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 411

1.34.2 Functions

1.34.2.1 p4_atomic_write

Atomic assignment operation.

Synopsis:

void p4_atomic_write(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value assigned atomically to "atomic"

Returns: Nothing.

Note: Atomic read and write operations ensure that (on a given CPU) the compiler will preserve the order of dependent memory accesses and that the order of interleaved load store on the same memory location will be preserved.

Note: If required, additional memory barriers should be used to ensure appropriate (cross CPU) memory ordering.

Note: Atomic operations are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

412 The PikeOS Kernel API

1.34.2.2 p4_atomic_add

Atomic ADD operation.

Synopsis:

void p4_atomic_add(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value added atomically to "atomic"

Returns: Nothing.

Note: If required, additional memory barriers should be used to ensure appropriate (cross CPU) memory ordering.

Note: "Negative" values may be used as argument val to implement subtraction using unsigned int semantics, thus avoiding possible integer overflows.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 413

1.34.2.3 p4_atomic_inc

Atomic increment operation.

Synopsis:

void p4_atomic_inc(P4_atomic_t *atomic)

Parameters: atomic IN: atomic data type

Note: If required, additional memory barriers should be used to ensure appropriate (cross CPU) memory ordering.

Returns: Nothing.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

414 The PikeOS Kernel API

1.34.2.4 p4_atomic_dec

Atomic decrement operation.

Synopsis:

void p4_atomic_dec(P4_atomic_t *atomic)

Parameters: atomic IN: atomic data type

Note: If required, additional memory barriers should be used to ensure appropriate (cross CPU) memory ordering.

Returns: Nothing.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 415

1.34.2.5 p4_atomic_or

Atomic OR (bit set) operation.

Synopsis:

void p4_atomic_or(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value OR-ed atomically to "atomic"

Note: If required, additional memory barriers should be used to ensure appropriate (cross CPU) memory ordering.

Returns: Nothing.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

416 The PikeOS Kernel API

1.34.2.6 p4_atomic_bic

Atomic AND NOT (bit clear) operation.

Synopsis:

void p4_atomic_bic(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value AND NOT-ed atomically to "atomic"

Note: If required, additional memory barriers should be used to ensure appropriate (cross CPU) memory ordering.

Returns: Nothing.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 417

1.34.2.7 p4_atomic_and

Atomic AND operation.

Synopsis:

void p4_atomic_and(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value AND-ed atomically to "atomic"

Note: If required, additional memory barriers should be used to ensure appropriate (cross CPU) memory ordering.

Returns: Nothing.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

418 The PikeOS Kernel API

1.34.2.8 p4_atomic_xor

Atomic XOR operation.

Synopsis:

void p4_atomic_xor(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value XOR-ed atomically to "atomic"

Note: If required, additional memory barriers should be used to ensure appropriate (cross CPU) memory ordering.

Returns: Nothing.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 419

1.34.2.9 p4_atomic_read

Atomic reading operation.

Synopsis:

P4_uint32_t p4_atomic_read(P4_atomic_t *atomic)

Parameters: atomic IN: atomic data type

Returns: Returns value in "atomic".

Note: Atomic read and write operations ensure that (on a given CPU) the compiler will preserve the order of dependent memory accesses and that the order of interleaved load store on the same memory location will be preserved.

Note: If required, additional memory barriers should be used to ensure appropriate (cross CPU) memory ordering.

Note: Atomic operations are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

420 The PikeOS Kernel API

1.34.2.10 p4_atomic_swap

Atomic swap operation.

Synopsis:

P4_uint32_t p4_atomic_swap(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value assigned atomically to "atomic"

Returns: Returns value in "atomic" before modification.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 421

1.34.2.11 p4_atomic_fetch_and_add

Atomic ADD operation.

Synopsis:

P4_uint32_t p4_atomic_fetch_and_add(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value added atomically to "atomic"

Returns: Returns value in "atomic" before modification.

Note: "Negative" values may be used as argument val to implement subtraction using unsigned int semantics, thus avoiding possible integer overflows.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

422 The PikeOS Kernel API

1.34.2.12 p4_atomic_fetch_and_or

Atomic OR (bit set) operation.

Synopsis:

P4_uint32_t p4_atomic_fetch_and_or(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value OR-ed atomically to "atomic"

Returns: Returns value in "atomic" before modification.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 423

1.34.2.13 p4_atomic_fetch_and_bic

Atomic AND NOT (bit clear) operation.

Synopsis:

P4_uint32_t p4_atomic_fetch_and_bic(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value AND NOT-ed atomically to "atomic"

Returns: Returns value in "atomic" before modification.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

424 The PikeOS Kernel API

1.34.2.14 p4_atomic_fetch_and_and

Atomic AND operation.

Synopsis:

P4_uint32_t p4_atomic_fetch_and_and(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value AND-ed atomically to "atomic"

Returns: Returns value in "atomic" before modification.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 425

1.34.2.15 p4_atomic_fetch_and_xor

Atomic XOR operation.

Synopsis:

P4_uint32_t p4_atomic_fetch_and_xor(P4_atomic_t *atomic, P4_uint32_t val)

Parameters: atomic IN: atomic data type val IN: value XOR-ed atomically to "atomic"

Returns: Returns value in "atomic" before modification.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

426 The PikeOS Kernel API

1.34.2.16 p4_atomic_cas_relaxed

Atomic compare and swap operation, relaxed version without barriers.

Synopsis:

P4_bool_t p4_atomic_cas_relaxed(P4_atomic_t *atomic, P4_uint32_t oldval, P4_uint32_t newval)

Parameters: atomic IN: atomic data type oldval IN: old value which is expected in "atomic" newval IN: new value which is written to "atomic"

Returns: Returns TRUE if the CAS operation succeeded.

Note: The CAS operation compares the value of oldval with the value stored in "atomic". If values match, the newval is written to "atomic" and CAS operation succeeded. If oldval is different from the value stored in "atomic", CAS operation is unsuccessful and newval is not written. The compare and conditional store are executed as single atomic operation.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 427

1.34.2.17 p4_atomic_cas

Atomic compare and swap operation.

Synopsis:

P4_bool_t p4_atomic_cas(P4_atomic_t *atomic, P4_uint32_t oldval, P4_uint32_t newval)

Parameters: atomic IN: atomic data type oldval IN: old value which is expected in "atomic" newval IN: new value which is written to "atomic"

Returns: Returns TRUE if the CAS operation succeeded.

Note: The CAS operation compares the value of oldval with the value stored in "atomic". If values match, the newval is written to "atomic" and CAS operation succeeded. If oldval is different from the value stored in "atomic", CAS operation is unsuccessful and newval is not written. The compare and conditional store are executed as single atomic operation.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

428 The PikeOS Kernel API

1.34.2.18 p4_atomic_fetch_and_cas_relaxed

Atomic compare and swap operation, relaxed version without barriers.

Synopsis:

P4_uint32_t p4_atomic_fetch_and_cas_relaxed(P4_atomic_t *atomic, P4_uint32_t oldval, P4_uint32_t newval)

Parameters: atomic IN: atomic data type oldval IN: old value which is expected in "atomic" newval IN: new value which is written to "atomic"

Returns: Returns the previous value of "atomic".

Note: The CAS operation compares the value of oldval with the value stored in "atomic". If values match, the newval is written to "atomic" and CAS operation succeeded. If oldval is different from the value stored in "atomic", CAS operation is unsuccessful and newval is not written. The compare and conditional store are executed as single atomic operation.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 429

1.34.2.19 p4_atomic_fetch_and_cas

Atomic compare and swap operation (return previous value)

Synopsis:

P4_uint32_t p4_atomic_fetch_and_cas(P4_atomic_t *atomic, P4_uint32_t oldval, P4_uint32_t newval)

Parameters: atomic IN: atomic data type oldval IN: old value which is expected in "atomic" newval IN: new value which is written to "atomic"

Returns: Returns the previous value of "atomic".

Note: The CAS operation compares the value of oldval with the value stored in "atomic". If values match, the newval is written to "atomic" and CAS operation succeeded. If oldval is different from the value stored in "atomic", CAS operation is unsuccessful and newval is not written. The compare and conditional store are executed as single atomic operation.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

430 The PikeOS Kernel API

1.34.2.20 p4_atomic_ptr_write

Atomic assignment operation of pointer.

Synopsis:

void p4_atomic_ptr_write(P4_atomic_ptr_t *atomic, P4_address_t val)

Parameters: atomic IN: atomic pointer data type val IN: pointer assigned atomically to "atomic"

Returns: Nothing.

Note: Atomic operations are only guaranteed to work properly on cached mapped memory (memory mapped with P4_M_C_WB attributes).

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 431

1.34.2.21 p4_atomic_ptr_read

Atomic reading operation of pointer.

Synopsis:

P4_address_t p4_atomic_ptr_read(P4_atomic_ptr_t *atomic)

Parameters: atomic IN: atomic pointer data type

Returns: Returns pointer value in "atomic".

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

432 The PikeOS Kernel API

1.34.2.22 p4_atomic_ptr_cas

Atomic compare and swap operation of pointers.

Synopsis:

P4_bool_t p4_atomic_ptr_cas(P4_atomic_ptr_t *atomic, P4_address_t oldval, P4_address_t newval)

Parameters: atomic IN: atomic pointer data type oldval IN: old pointer value which is expected in "atomic" newval IN: new pointer value which is written to "atomic"

Returns: Returns TRUE if the CAS operation succeeded.

Note: The CAS operation compares the value of oldval with the value stored in "atomic". If values match, the newval is written to "atomic" and CAS operation succeeded. If oldval is different from the value stored in "atomic", CAS operation is unsuccessful and newval is not written. The compare and conditional store are executed as single atomic operation.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Atomic Operations 433

1.34.2.23 p4_atomic_ptr_swap

Atomic swap operation of pointers.

Synopsis:

P4_address_t p4_atomic_ptr_swap(P4_atomic_ptr_t *atomic, P4_address_t val)

Parameters: atomic IN: atomic pointer data type val IN: pointer value assigned atomically to "atomic"

Returns: Returns pointer value in "atomic" before modification.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

434 The PikeOS Kernel API

1.34.2.24 p4_atomic_ptr_fetch_and_cas

Atomic compare and swap operation of pointers.

Synopsis:

P4_address_t p4_atomic_ptr_fetch_and_cas(P4_atomic_ptr_t *atomic, P4_address_t oldval, P4_address_t newval)

Parameters: atomic IN: atomic pointer data type oldval IN: old pointer value which is expected in "atomic" newval IN: new pointer value which is written to "atomic"

Returns: Returns the previous pointer value of "atomic".

Note: The CAS operation compares the value of oldval with the value stored in "atomic". If values match, the newval is written to "atomic" and CAS operation succeeded. If oldval is different from the value stored in "atomic", CAS operation is unsuccessful and newval is not written. The compare and conditional store are executed as single atomic operation.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Memory Barriers 435

1.35 Memory Barriers

This section describes constants, data types, access macros, and service functions related to the PikeOS user space memory barrier API for multiprocessor systems.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

436 The PikeOS Kernel API

1.35.1 Functions

1.35.1.1 p4_atomic_read_barrier

Read memory barrier.

Synopsis:

void p4_atomic_read_barrier(void)

Returns: Nothing.

Note: The read memory barrier enforces ordering of load operations: All load operations before this barrier have completed. Any load operation after this barrier will not be speculated before the barrier. This relates to a load-load barrier or stronger on the target hardware.

Note: This memory barrier is intended to synchronize data in cached memory only. For ordering of writes to I/O resources, see p4_io_write_barrier() (see section 1.35.1.6).

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Memory Barriers 437

1.35.1.2 p4_atomic_write_barrier

Write memory barrier.

Synopsis:

void p4_atomic_write_barrier(void)

Returns: Nothing.

Note: The write memory barrier enforces ordering of store operations: All store operations before this barrier succeeded and are guaranteed to be globally visible. Any store operation after this barrier will not be speculated before the barrier. This relates to a store-store barrier or stronger on the target hardware.

Note: This memory barrier is intended to synchronize data in cached memory only. For ordering of writes to I/O resources, see p4_io_write_barrier() (see section 1.35.1.6).

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

438 The PikeOS Kernel API

1.35.1.3 p4_atomic_barrier

Full memory barrier.

Synopsis:

void p4_atomic_barrier(void)

Returns: Nothing.

Note: This memory barrier enforces ordering of load and store operations: All memory operations before this barrier succeeded and are guaranteed to be globally visible. Any memory operation after this barrier will not be speculated before the barrier. This relates to a full load-load, load-store, store-load, and store-store barrier or stronger on the target hardware.

Note: This memory barrier is intended to synchronize data in cached memory only. For ordering of writes to I/O resources, see p4_io_write_barrier() (see section 1.35.1.6).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Memory Barriers 439

1.35.1.4 p4_atomic_acquire_barrier

Acquire barrier.

Synopsis:

void p4_atomic_acquire_barrier(void)

Returns: Nothing.

Note: Any memory operation after this barrier will not be speculated before the barrier. This relates to a load-load and load-store barrier or stronger on the target hardware. Specifically, all load opera- tions that occur before the barrier must have completed before any future memory operations commence.

Note: Memory operations that occur before the barrier may become globally visible after the barrier.

Note: This memory barrier is intended to synchronize data in cached memory only. For ordering of writes to I/O resources, see p4_io_write_barrier() (see section 1.35.1.6).

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

440 The PikeOS Kernel API

1.35.1.5 p4_atomic_release_barrier

Release barrier.

Synopsis:

void p4_atomic_release_barrier(void)

Returns: Nothing.

Note: All memory operations before this barrier succeeded and are guaranteed to be globally visible. This relates to a load-store and store-store barrier or stronger on the target hardware. Specifically, all memory operations that occur before the barrier must have completed before any future write operations commence.

Note: Memory operations that occur after the barrier may become globally visible before the barrier.

Note: This memory barrier is intended to synchronize data in cached memory only. For ordering of writes to I/O resources, see p4_io_write_barrier() (see section 1.35.1.6).

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Memory Barriers 441

1.35.1.6 p4_io_write_barrier

Write memory barrier for I/O resources.

Synopsis:

void p4_io_write_barrier(void)

Returns: Nothing.

Note: The write memory barrier enforces ordering of store operations: All store operations to I/O resources before this barrier succeeded and are guaranteed to be globally visible. This relates to a store-load and store-store barrier or stronger on the target hardware.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

442 The PikeOS Kernel API

1.36 Wait Queues

This section describes constants, data types, access macros, and service functions related to the PikeOS user space wait queue API.

1.36.1 Structure Definitions

1.36.1.1 struct P4_waitq_attr_str

Wait queue attribute structure. The function p4_waitq_get_attr() (see section 1.36.4.4) returns the attributes of a wait queue in a data structure of type P4_waitq_attr_t.

Synopsis: struct P4_waitq_attr_str { P4_uint32_t * state; P4_uint32_t num_waiters; P4_uint32_t flags; };

Structure Element Description: state Wait queues associated state variable in user space. num_waiters Number of threads currently waiting on the wait queue. flags Flags and operation mode of the wait queue. Currently, the following flag bits are defined:

           • P4_WAITQ_PRIO
              If set, the set of waiting threads is ordered by thread priority instead of FIFO order.

Associated Data Type

P4_waitq_attr_t Wait queue attribute structure.

1.36.2 Defines

P4_WAITQ_PRIO Value definition for p4_waitq_init()flags parameter. Description: This value indicates to p4_waitq_init() (see section 1.36.4.1) that the wait queue uses priority order rather than FIFO order.

P4_WAITQ_WAIT_PRIO Value definition for p4_waitq_wait()flags parameter. Description: This value indicates to p4_waitq_init() (see section 1.36.4.1) that the waiting thread shall use the given wait priority as scheduling priority while waiting for the wait queue.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Wait Queues 443

P4_WAITQ_WAKE_ALL Value definition for p4_waitq_wake()flags parameter. Description: This value indicates to p4_waitq_wake() (see section 1.36.4.3) that all waiting threads shall be woken up.

1.36.3 Data Type Definitions

P4_waitq_attr_t Wait queue attribute structure. The function p4_waitq_get_attr() (see section 1.36.4.4) returns the attributes of a wait queue in a data structure of type P4_waitq_attr_t.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

444 The PikeOS Kernel API

1.36.4 Functions

1.36.4.1 p4_waitq_init

Initialize a wait queue.

Synopsis:

P4_e_t p4_waitq_init(P4_waitqid_t waitq_id, P4_uint32_t *state, P4_uint32_t flags)

Parameters: waitq_id IN: Wait queue ID state IN: Associated state variable flags IN: Flags and operation mode

Description: This function initializes the wait queue waitq_id and registers the user space state variable state to the wait queue. The flags argument further defines the behaviour of this call:

  • If P4_WAITQ_PRIO is set, the set of waiting threads is ordered by thread priority instead of FIFO order.

Note: Wait queues can be initialized only once. Wait queues remain persistent task objects until task termination.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if waitq_id is not a valid wait queue ID. P4_E_STATE if the wait queue waitq_id is already initialized. P4_E_INVAL if flags contains an unsupported combination of flags. P4_E_INVAL if state is NULL or does not point to a valid address or exceeds the callers virtual address space. P4_E_NOKMEM if there is not enough kernel memory available in the resource partition of the callers task to allocate a wait queue.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Wait Queues 445

1.36.4.2 p4_waitq_wait

Wait on a wait queue.

Synopsis:

P4_e_t p4_waitq_wait(P4_timeout_t timeout, P4_waitqid_t waitq_id, P4_uint32_t compare, P4_prio_t wait_prio, P4_uint32_t flags)

Parameters: timeout IN: Maximum time to wait on the wait queue waitq_id IN: Wait queue ID compare IN: compare value wait_prio IN: Waiting priority flags IN: Flags and operation mode

Description: This function blocks on the wait queue waitq_id with timeout timeout until it is woken up by p4_waitq_wake() (see section 1.36.4.3). wait_prio defines the priority for priority ordered wait queues and is ignored for FIFO ordered wait queues. The flags argument further defines the behaviour of this call:

• If P4_WAITQ_WAIT_PRIO is set, the calling thread changes its scheduling priority to wait_prio while waiting for the wait queue. After wakeup, the calling thread restores its previous scheduling priority again before returning to user space.

Note: When calling this function at maximum priority, setting P4_WAITQ_PRIO in flags and using a dedicated waiting priority allows preemption to be prevented by other threads on the same processor before and after calling this function, while at the same time ensuring the proper scheduling order when the thread is woken up.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if waitq_id is not a valid wait queue ID. P4_E_STATE if the wait queue waitq_id is not initialized. P4_E_STATE if the registered user space state variable does not match compare. P4_E_INVAL if flags contains an unsupported combination of flags. P4_E_PAGEFAULT if the registered user space state variable is not fully mapped in the callers virtual address space. P4_E_BADTIMEOUT if the specified timeout is invalid or in the past. P4_E_TIMEOUT if the specified timeout has expired before the wait queue was signaled by a call to p4_waitq_wake() (see section 1.36.4.3).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

446 The PikeOS Kernel API

P4_E_CANCEL if the function was canceled by another thread, the calling thread was moved to another time partition, or the thread was migrated to another CPU.

                        c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Wait Queues 447

1.36.4.3 p4_waitq_wake

Wakeup threads waiting on a wait queue.

Synopsis:

P4_e_t p4_waitq_wake(P4_waitqid_t waitq_id, P4_uint32_t flags, P4_uid_t *first_woken)

Parameters: waitq_id IN: Wait queue ID flags IN: Flags and operation mode first_woken OUT: UID of first woken thread A NULL pointer indicates that the UID should not be retrieved.

Description: This function unblocks threads blocked on the wait queue waitq_id. The flags argument further defines the behaviour of this call:

• If P4_WAITQ_WAKE_ALL is set, all waiting threads are woken up. Otherwise the first waiting thread only is woken up. Waiting threads are woken up in the wait queues initialized order, e.g. priority order or FIFO order.

If not NULL, first_woken is set to the fully qualified UID of the first thread that was woken up as a consequence of the invocation of p4_waitq_wake() (see section 1.36.4.3). If no threads were waiting on waitq_id, and the function successfully returns, first_woken is P4_UID_INVALID.

Note: The maximum number of woken threads is limited to the maximum number of threads in the task.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if waitq_id is not a valid wait queue ID. P4_E_STATE if the wait queue waitq_id is not initialized. P4_E_INVAL if flags contains an unsupported combination of flags. P4_E_INVAL if first_woken is not a valid address or exceeds the callers virtual address space. P4_E_LIMIT if the number of threads to be woken up exceeds the maximum number of threads in the task. At most the maximum number of threads in the task is woken up. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel does not point to a valid address in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

448 The PikeOS Kernel API

1.36.4.4 p4_waitq_get_attr

Retrieve the attributes of a wait queue.

Synopsis:

P4_e_t p4_waitq_get_attr(P4_waitqid_t waitq_id, P4_waitq_attr_t *attr_p)

Parameters: waitq_id IN: Wait queue ID attr_p OUT: Pointer to a wait queue attribute structure. Upon successful completion, the structure referenced by attr_p will contain the attributes of requested wait queue. A NULL pointer indicates that the attributes should not be retrieved.

Description: This function retrieves the attributes of the wait queue waitq_id in attr_p. For a detailed description of the wait queue attribute structure, refer to the documentation of P4_waitq_attr_t.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_INVAL if waitq_id is not a valid wait queue ID. P4_E_STATE if the wait queue waitq_id is not initialized. P4_E_INVAL if attr_p is not a valid address or exceeds the callers virtual address space. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel is not fully mapped in the callers virtual address space.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 449

1.37 Health Monitoring

This section describes constants, data types, access macros, and service functions related to the PikeOS Health Monitoring Subsystem. (C) Copyright SYSGO AG.

1.37.1 Structure Definitions

1.37.1.1 struct P4_hm_error_str

Health-Monitoring error structure. This structure identifies an HM-error. The function p4_hm_inject() (see section 1.37.4.4) uses this structure to describe an HM-error that can be injected from the userspace.

Note: msg is normally a string that is passed down to the HM subsystem. The kernel does not assume the string be NUL terminated. NULL msg are assumed to have 0 size.

Synopsis: struct P4_hm_error_str { const void * msg; P4_size_t size; P4_hm_type_t type; P4_uint32_t domain; P4_uint32_t id; P4_uint32_t unused; };

Structure Element Description: msg Address of the HM message in the reporter address space size Size of the reported HM message type Type of the health-monitoring reported error domain Health-Monitoring Domain of the component reporting the error id Identifier of the health-monitoring error unused

Associated Data Type

P4_hm_error_t Health-Monitoring error structure.

1.37.2 Defines

P4_HM_MAX_MSG_SIZE 128 Health monitoring maximum message size. Description:

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

450 The PikeOS Kernel API

    This value is currently derived from the A653 Part 1-3 standard.

P4_HM_DOMAIN_RESERVED 0 Health Monitoring kernel-reserved domain. Description: Reserved domain identifier for in-kernel usage only.

P4_HM_DOMAIN_KERNEL 2 Health monitoring kernel domain. Description: Reserved domain identifier for the kernel. This domain is only injected by the kernel and cannot be injected by any kernel API.

P4_HM_DOMAIN_PSP 3 Health monitoring PSP domain. Description: Reserved domain identifier for the PSP. This domain can only be injected by API exported to the PSP.

P4_HM_DOMAIN_SYSTEM_INIT 4 Health monitoring sigma0 initialization domain. Description: Reserved domain identifier for the first user space task. This domain can only be injected if the caller resides in the first user space task and has the ability P4_AB_SYSTEM_HM_ERROR. It will not be injected by the kernel or kernel drivers and is not available to the PSP.

P4_HM_DOMAIN_SYSTEM 5 Health monitoring system domain. Description: Reserved domain identifier for the system task (the first user space task sigma0). This domain can only be injected if the caller has the ability P4_AB_SYSTEM_HM_ERROR. The ability is normally reserved to the first user space task only. It will not be injected by the kernel or kernel drivers and is not available to the PSP.

P4_HM_DOMAIN_PART_INIT 6 Health monitoring partition init domain. Description: Reserved domain identifier for the personality layer of user partitions. This domain can be injected by user partitions without extended HM capabilities. It will not be injected by the kernel or kernel drivers and is not available to the PSP.

P4_HM_DOMAIN_PART 7 Health monitoring partition domain. Description: Reserved domain identifier for the personality layer of user partitions. This domain can be injected by user partitions without extended HM capabilities. It will not be injected by the kernel or kernel drivers and is not available to the PSP.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 451

P4_HM_DOMAIN_USER 8 Health monitoring user domain. Description: Reserved domain identifier for the user application layer of user partitions. This domain that can be injected by user partitions without extended HM capabilities. It will not be injected by the kernel or kernel drivers and is not available to the PSP.

P4_HM_DOMAIN_BUILTIN_DRV_BASE 32 Health monitoring driver builtin base domain. Description: Reserved base domain identifier for builtin drivers. Driver domains can only injected by the kernel driver API and callers that have the ability P4_AB_SYS- TEM_HM_ERROR. They will not be injected by the kernel and are not available to the PSP.

P4_HM_DOMAIN_DRV_BASE 64 Health monitoring driver default domain. Description: Reserved base domain identifier for drivers. All domain identifiers greater than P4_HM_DO- MAIN_DRV_BASE are also considered to be reported by a driver, but of a different domain. Driver domains can only injected by the kernel driver API and callers that have the ability P4_AB_SYS- TEM_HM_ERROR. They will not be injected by the kernel and are not available to the PSP.

P4_HM_FLAG_PANIC Value definition for p4_hm_inject()flags parameter. Description: Setting this value instructs p4_hm_inject() (see section 1.37.4.4) to cause a kernel panic if the injected error was configured to be ignored. The flag is only valid if the caller has the ability P4_AB_SYS- TEM_HM_ERROR and the error was injected in module scope.

P4_PANIC_CAUSE_NULL

     Description:
     Default Panic Cause ID

P4_PANIC_CAUSE_ID_1

     Description:
     Internal Panic Cause ID 1
     error_id:
     P4_E_CONFIG

     msg:
     "HWPTE overcrowded"

     regs:
     NULL

     arg:


                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

452 The PikeOS Kernel API

  0

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_2

  Description:
  Internal Panic Cause ID 2
  error_id:
  P4_E_CONFIG

  msg:
  "HWPTE entry not found"

  regs:
  NULL

  arg:
  0

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_3

  Description:
  Internal Panic Cause ID 3
  error_id:
  P4_E_CONFIG

  msg:
  "Kernel mapping failed"

  regs:
  NULL

  arg:
  0

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_4

  Description:
  Internal Panic Cause ID 4
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 453

     P4_E_CONFIG

     msg:
     "Kernel mapping failure: L2 virt mapping overlaps"

     regs:
     NULL

     arg:
     0

     component:
     ASP-PPC

P4_PANIC_CAUSE_ID_5

     Description:
     Internal Panic Cause ID 5
     error_id:
     P4_E_INVAL

     msg:
     "Wrong exception"

     regs:
     NULL

     arg:
     0

     component:
     ASP-PPC

P4_PANIC_CAUSE_ID_6

     Description:
     Internal Panic Cause ID 6
     error_id:
     P4_E_INVAL

     msg:
     "Unrecoverable access to user space detected (Arg == exnr)"

     regs:
     regs

     arg:
     exnr


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

454 The PikeOS Kernel API

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_7

  Description:
  Internal Panic Cause ID 7
  error_id:
  P4_E_INVAL

  msg:
  "FPU unavail exception in kernelmode"

  regs:
  regs

  arg:
  0

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_8

  Description:
  Internal Panic Cause ID 8
  error_id:
  P4_E_INVAL

  msg:
  "PROGRAM exception in kernelmode"

  regs:
  regs

  arg:
  0

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_9

  Description:
  Internal Panic Cause ID 9
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 455

     P4_E_INVAL

     msg:
     "Machine check exception (Arg == exnr)"

     regs:
     regs

     arg:
     exnr

     component:
     ASP-PPC

P4_PANIC_CAUSE_ID_10

     Description:
     Internal Panic Cause ID 10
     error_id:
     P4_E_INVAL

     msg:
     "Other exception in kernelmode (Arg == exnr)"

     regs:
     regs

     arg:
     exnr

     component:
     ASP-PPC

P4_PANIC_CAUSE_ID_11

     Description:
     Internal Panic Cause ID 11
     error_id:
     P4_E_INVAL

     msg:
     "Unsupported exception (Arg == exnr)"

     regs:
     regs

     arg:
     exnr


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

456 The PikeOS Kernel API

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_12

  Description:
  Internal Panic Cause ID 12
  error_id:
  P4_E_INVAL

  msg:
  "Unrecoverable access to user space detected (Arg == exnr)"

  regs:
  regs

  arg:
  exnr

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_13

  Description:
  Internal Panic Cause ID 13
  error_id:
  P4_E_INVAL

  msg:
  "Critical interrupt exception (Arg == exnr)"

  regs:
  regs

  arg:
  exnr

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_14

  Description:
  Internal Panic Cause ID 14
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 457

     P4_E_INVAL

     msg:
     "Nested machine check exception (Arg == regs->dsisr)"

     regs:
     regs

     arg:
     regs->dsisr

     component:
     ASP-PPC

P4_PANIC_CAUSE_ID_15

     Description:
     Internal Panic Cause ID 15
     error_id:
     P4_E_INVAL

     msg:
     "Machine check exception (Arg == regs->dsisr)"

     regs:
     regs

     arg:
     regs->dsisr

     component:
     ASP-PPC

P4_PANIC_CAUSE_ID_16

     Description:
     Internal Panic Cause ID 16
     error_id:
     P4_E_INVAL

     msg:
     "Unsupported exception (Arg == exnr)"

     regs:
     regs

     arg:
     exnr


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

458 The PikeOS Kernel API

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_17

  Description:
  Internal Panic Cause ID 17
  error_id:
  P4_E_INVAL

  msg:
  "Other exception in kernelmode (Arg == exnr)"

  regs:
  regs

  arg:
  exnr

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_18

  Description:
  Internal Panic Cause ID 18
  error_id:
  P4_E_CONFIG

  msg:
  "More than 256 tasks are not supported on this platform"

  regs:
  NULL

  arg:
  0

  component:
  ASP-PPC

P4_PANIC_CAUSE_ID_19

  Description:
  Internal Panic Cause ID 19
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 459

     P4_E_INVAL

     msg:
     "Prefetch abort exception in kernelmode (Arg == status)"

     regs:
     regs

     arg:
     status

     component:
     ASP-ARM

P4_PANIC_CAUSE_ID_20

     Description:
     Internal Panic Cause ID 20
     error_id:
     P4_E_INVAL

     msg:
     "Prefetch abort exception in user mode (Arg == status)"

     regs:
     regs

     arg:
     status

     component:
     ASP-ARM

P4_PANIC_CAUSE_ID_21

     Description:
     Internal Panic Cause ID 21
     error_id:
     P4_E_INVAL

     msg:
     "Data abort exception in kernelmode (Arg == status)"

     regs:
     regs

     arg:
     status


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

460 The PikeOS Kernel API

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_22

  Description:
  Internal Panic Cause ID 22
  error_id:
  P4_E_INVAL

  msg:
  "Data abort exception in usermode (Arg == status)"

  regs:
  regs

  arg:
  status

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_23

  Description:
  Internal Panic Cause ID 23
  error_id:
  P4_E_INVAL

  msg:
  "Bad exception (Arg == pc)"

  regs:
  NULL

  arg:
  pc

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_24

  Description:
  Internal Panic Cause ID 24
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 461

     P4_E_INVAL

     msg:
     "SError exception (Arg == esr)"

     regs:
     regs

     arg:
     esr

     component:
     ASP-ARM

P4_PANIC_CAUSE_ID_25

     Description:
     Internal Panic Cause ID 25
     error_id:
     P4_E_INVAL

     msg:
     "Data abort exception in kernelmode (Arg == esr)"

     regs:
     regs

     arg:
     esr

     component:
     ASP-ARM

P4_PANIC_CAUSE_ID_26

     Description:
     Internal Panic Cause ID 26
     error_id:
     P4_E_INVAL

     msg:
     "Instruction abort exception in kernelmode (Arg == esr)"

     regs:
     regs

     arg:
     esr


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

462 The PikeOS Kernel API

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_27

  Description:
  Internal Panic Cause ID 27
  error_id:
  P4_E_INVAL

  msg:
  "Exception in kernelmode (Arg == esr)"

  regs:
  regs

  arg:
  esr

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_28

  Description:
  Internal Panic Cause ID 28
  error_id:
  P4_E_INVAL

  msg:
  "Illegal data/instruction abort (Arg == esr)"

  regs:
  regs

  arg:
  esr

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_29

  Description:
  Internal Panic Cause ID 29
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 463

     P4_E_INVAL

     msg:
     "Illegal execution state (Arg == esr)"

     regs:
     regs

     arg:
     esr

     component:
     ASP-ARM

P4_PANIC_CAUSE_ID_30

     Description:
     Internal Panic Cause ID 30
     error_id:
     P4_E_INVAL

     msg:
     "Illegal execution state (Arg == esr)"

     regs:
     regs

     arg:
     esr

     component:
     ASP-ARM

P4_PANIC_CAUSE_ID_31

     Description:
     Internal Panic Cause ID 31
     error_id:
     P4_E_INVAL

     msg:
     "Unsupported FIQ"

     regs:
     regs

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

464 The PikeOS Kernel API

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_32

  Description:
  Internal Panic Cause ID 32
  error_id:
  P4_E_CONFIG

  msg:
  "PSP has wrong CPU architecture for this kernel (Arg == cpu_arch)"

  regs:
  NULL

  arg:
  kglobal.psp->arch.cpu_arch

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_33

  Description:
  Internal Panic Cause ID 33
  error_id:
  P4_E_INVAL

  msg:
  "Prefetch abort exception in kernelmode (Arg == status)"

  regs:
  regs

  arg:
  status

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_34

  Description:
  Internal Panic Cause ID 34
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 465

     P4_E_INVAL

     msg:
     "Prefetch abort exception in usermode (Arg == status)"

     regs:
     regs

     arg:
     status

     component:
     ASP-ARM

P4_PANIC_CAUSE_ID_35

     Description:
     Internal Panic Cause ID 35
     error_id:
     P4_E_INVAL

     msg:
     "Data abort exception in kernelmode (Arg == status)"

     regs:
     regs

     arg:
     status

     component:
     ASP-ARM

P4_PANIC_CAUSE_ID_36

     Description:
     Internal Panic Cause ID 36
     error_id:
     P4_E_INVAL

     msg:
     "Data abort exception in usermode (Arg == status)"

     regs:
     regs

     arg:
     status


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

466 The PikeOS Kernel API

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_37

  Description:
  Internal Panic Cause ID 37
  error_id:
  P4_E_INVAL

  msg:
  "RESET exception"

  regs:
  regs

  arg:
  0

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_38

  Description:
  Internal Panic Cause ID 38
  error_id:
  P4_E_INVAL

  msg:
  "UNDEFINED exception in kernelmode"

  regs:
  regs

  arg:
  0

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_39

  Description:
  Internal Panic Cause ID 39
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 467

     P4_E_INVAL

     msg:
     "Exception NA (not available)"

     regs:
     regs

     arg:
     0

     component:
     ASP-ARM

P4_PANIC_CAUSE_ID_40

     Description:
     Internal Panic Cause ID 40
     error_id:
     P4_E_INVAL

     msg:
     "Unsupported FIQ"

     regs:
     regs

     arg:
     0

     component:
     ASP-ARM

P4_PANIC_CAUSE_ID_41

     Description:
     Internal Panic Cause ID 41
     error_id:
     P4_E_CONFIG

     msg:
     "Invalid VFP state reported by PSP"

     regs:
     NULL

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

468 The PikeOS Kernel API

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_42

  Description:
  Internal Panic Cause ID 42
  error_id:
  P4_E_CONFIG

  msg:
  "Invalid CPU or alternative features provided in the PSP descriptor"

  regs:
  NULL

  arg:
  0

  component:
  ASP-X86

P4_PANIC_CAUSE_ID_43

  Description:
  Internal Panic Cause ID 43
  error_id:
  P4_E_CONFIG

  msg:
  "PSP has wrong CPU architecture for this kernel (Arg == cpu_arch)"

  regs:
  NULL

  arg:
  kglobal.psp->arch.cpu_arch

  component:
  ASP-ARM

P4_PANIC_CAUSE_ID_44

  Description:
  Internal Panic Cause ID 44
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 469

     P4_E_INVAL

     msg:
     "Unsupported number of physical address bits (Arg == pabits)"

     regs:
     NULL

     arg:
     pabits

     component:
     ASP-MIPS

P4_PANIC_CAUSE_ID_45

     Description:
     Internal Panic Cause ID 45
     error_id:
     P4_E_INVAL

     msg:
     "UTLB Exception handler too large"

     regs:
     NULL

     arg:
     0

     component:
     ASP-MIPS

P4_PANIC_CAUSE_ID_46

     Description:
     Internal Panic Cause ID 46
     error_id:
     P4_E_INVAL

     msg:
     "Unexpected exception in kernelmode"

     regs:
     regs

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

470 The PikeOS Kernel API

  component:
  ASP-MIPS

P4_PANIC_CAUSE_ID_47

  Description:
  Internal Panic Cause ID 47
  error_id:
  P4_E_INVAL

  msg:
  "Doublefault exception (Arg == cpu)"

  regs:
  regs

  arg:
  cpu

  component:
  ASP-X86

P4_PANIC_CAUSE_ID_48

  Description:
  Internal Panic Cause ID 48
  error_id:
  P4_E_INVAL

  msg:
  "Unexpected exception (Arg == regs->vector)"

  regs:
  regs

  arg:
  vector

  component:
  ASP-X86

P4_PANIC_CAUSE_ID_49

  Description:
  Internal Panic Cause ID 49
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 471

     P4_E_INVAL

     msg:
     "Exception in kernelmode detected"

     regs:
     regs

     arg:
     0

     component:
     ASP-X86

P4_PANIC_CAUSE_ID_50

     Description:
     Internal Panic Cause ID 50
     error_id:
     P4_E_INVAL

     msg:
     "Unrecoverable access to userspace detected"

     regs:
     regs

     arg:
     0

     component:
     ASP-X86

P4_PANIC_CAUSE_ID_51

     Description:
     Internal Panic Cause ID 51
     error_id:
     P4_E_OOMEM

     msg:
     "There is something wrong with the level-2 table"

     regs:
     NULL

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

472 The PikeOS Kernel API

  component:
  ASP-SPARC

P4_PANIC_CAUSE_ID_52

  Description:
  Internal Panic Cause ID 52
  error_id:
  P4_E_OOMEM

  msg:
  "There is something wrong with the level-1 table"

  regs:
  NULL

  arg:
  0

  component:
  ASP-SPARC

P4_PANIC_CAUSE_ID_53

  Description:
  Internal Panic Cause ID 53
  error_id:
  P4_E_CONFIG

  msg:
  "Could not read sigma0 .text"

  regs:
  NULL

  arg:
  0

  component:
  ASP-SPARC

P4_PANIC_CAUSE_ID_54

  Description:
  Internal Panic Cause ID 54
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 473

     P4_E_CONFIG

     msg:
     "Could not read sigma0 .text"

     regs:
     NULL

     arg:
     0

     component:
     ASP-SPARC

P4_PANIC_CAUSE_ID_55

     Description:
     Internal Panic Cause ID 55
     error_id:
     P4_E_CONFIG

     msg:
     "Missing __p4_start() signature at sigma0"

     regs:
     NULL

     arg:
     0

     component:
     ASP-SPARC

P4_PANIC_CAUSE_ID_56

     Description:
     Internal Panic Cause ID 56
     error_id:
     P4_E_INVAL

     msg:
     "Unrecoverable MMU exception in kernelmode (Arg == trap_type)"

     regs:
     regs

     arg:
     trap_type


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

474 The PikeOS Kernel API

  component:
  ASP-SPARC

P4_PANIC_CAUSE_ID_57

  Description:
  Internal Panic Cause ID 57
  error_id:
  P4_E_INVAL

  msg:
  "Unrecoverable exception in kernelmode (Arg == trap_type)"

  regs:
  regs

  arg:
  trap_type

  component:
  ASP-SPARC

P4_PANIC_CAUSE_ID_58

  Description:
  Internal Panic Cause ID 58
  error_id:
  P4_E_INVAL

  msg:
  "More than 8 SPARC register windows are not supported by this ASP"

  regs:
  NULL

  arg:
  0

  component:
  ASP-SPARC

P4_PANIC_CAUSE_ID_60

  Description:
  Internal Panic Cause ID 60
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 475

     P4_E_CONFIG

     msg:
     "CPU with CASA required"

     regs:
     NULL

     arg:
     0

     component:
     ASP-SPARC

P4_PANIC_CAUSE_ID_61

     Description:
     Internal Panic Cause ID 61
     error_id:
     P4_E_CONFIG

     msg:
     "PSP has too many processors for kernel (Arg == num_cpu)"

     regs:
     NULL

     arg:
     num_cpu

     component:
     KERNEL

P4_PANIC_CAUSE_ID_62

     Description:
     Internal Panic Cause ID 62
     error_id:
     P4_E_INVAL

     msg:
     "Recovertable not sorted"

     regs:
     NULL

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

476 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_63

  Description:
  Internal Panic Cause ID 63
  error_id:
  P4_E_CONFIG

  msg:
  "Invalid p4/kernel/tps_strong_sync property value"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_64

  Description:
  Internal Panic Cause ID 64
  error_id:
  P4_E_CONFIG

  msg:
  "Thread kernel-stack p4/kernel/thrinfo_size too small for ASP"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_65

  Description:
  Internal Panic Cause ID 65
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 477

     P4_E_CONFIG

     msg:
     "Thread kernel-stack p4/kernel/thrinfo_size too large for ASP"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_66

     Description:
     Internal Panic Cause ID 66
     error_id:
     P4_E_CONFIG

     msg:
     "Thread kernel-stack p4/kernel/thrinfo_size not page-size aligned"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_67

     Description:
     Internal Panic Cause ID 67
     error_id:
     P4_E_CONFIG

     msg:
     "Could not start other processor (Arg == cpu)"

     regs:
     NULL

     arg:
     cpu


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

478 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_68

  Description:
  Internal Panic Cause ID 68
  error_id:
  P4_E_OOMEM

  msg:
  "Cannot create first user space task and thread"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_69

  Description:
  Internal Panic Cause ID 69
  error_id:
  P4_E_CONFIG

  msg:
  VARIABLE

  regs:
  NULL

  arg:
  code

  component:
  KDEV

P4_PANIC_CAUSE_ID_70

  Description:
  Internal Panic Cause ID 70
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 479

     P4_E_CONFIG

     msg:
     "drv_poke() before p4_early_init()"

     regs:
     NULL

     arg:
     0

     component:
     KDEV

P4_PANIC_CAUSE_ID_71

     Description:
     Internal Panic Cause ID 71
     error_id:
     P4_E_CONFIG

     msg:
     "Too few or too many memory regions configured"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_72

     Description:
     Internal Panic Cause ID 72
     error_id:
     P4_E_CONFIG

     msg:
     "Memory region ID is too large (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

480 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_73

  Description:
  Internal Panic Cause ID 73
  error_id:
  P4_E_CONFIG

  msg:
  "Memory region type is invalid or inconsistent (Arg == respart)"

  regs:
  NULL

  arg:
  rp_id

  component:
  KERNEL

P4_PANIC_CAUSE_ID_74

  Description:
  Internal Panic Cause ID 74
  error_id:
  P4_E_CONFIG

  msg:
  "Memory region can not be allocated (Arg == respart)"

  regs:
  NULL

  arg:
  rp_id

  component:
  KERNEL

P4_PANIC_CAUSE_ID_75

  Description:
  Internal Panic Cause ID 75
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 481

     P4_E_CONFIG

     msg:
     "Detected overlapping start or zero sized region"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_76

     Description:
     Internal Panic Cause ID 76
     error_id:
     P4_E_CONFIG

     msg:
     "Detected overlapping regions (Arg == (RP1|RP2))"

     regs:
     NULL

     arg:
     a->respart|(b->respart<<8)

     component:
     KERNEL

P4_PANIC_CAUSE_ID_77

     Description:
     Internal Panic Cause ID 77
     error_id:
     P4_E_CONFIG

     msg:
     "Detected wrap-around memory region (Arg == respart)"

     regs:
     NULL

     arg:
     respart


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

482 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_78

  Description:
  Internal Panic Cause ID 78
  error_id:
  P4_E_CONFIG

  msg:
  "Unable to find MultiPartitionHMTable (Arg == respart)"

  regs:
  NULL

  arg:
  rp->id

  component:
  KERNEL

P4_PANIC_CAUSE_ID_79

  Description:
  Internal Panic Cause ID 79
  error_id:
  P4_E_CONFIG

  msg:
  "Invalid number of time partitions configured"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_80

  Description:
  Internal Panic Cause ID 80
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 483

     P4_E_CONFIG

     msg:
     "Invalid number of priorities configured"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_81

     Description:
     Internal Panic Cause ID 81
     error_id:
     P4_E_CONFIG

     msg:
     "Invalid number of threads per task configured"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_82

     Description:
     Internal Panic Cause ID 82
     error_id:
     P4_E_CONFIG

     msg:
     "PSP has too many kernel level devices"

     regs:
     NULL

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

484 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_83

  Description:
  Internal Panic Cause ID 83
  error_id:
  P4_E_CONFIG

  msg:
  "PSP has no device call table"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_84

  Description:
  Internal Panic Cause ID 84
  error_id:
  P4_E_CONFIG

  msg:
  "Too many resource partitions configured"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_85

  Description:
  Internal Panic Cause ID 85
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 485

     P4_E_CONFIG

     msg:
     "MemRegionPartion/MemRegionID are invalid (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id

     component:
     KERNEL

P4_PANIC_CAUSE_ID_86

     Description:
     Internal Panic Cause ID 86
     error_id:
     P4_E_CONFIG

     msg:
     "KMEM allocation from memregion type unprivileged (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id

     component:
     KERNEL

P4_PANIC_CAUSE_ID_87

     Description:
     Internal Panic Cause ID 87
     error_id:
     P4_E_CONFIG

     msg:
     "Cannot allocate KMEM (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

486 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_88

  Description:
  Internal Panic Cause ID 88
  error_id:
  P4_E_CONFIG

  msg:
  "Only one KMEM memory requirement allowed (Arg == respart)"

  regs:
  NULL

  arg:
  rp_id

  component:
  KERNEL

P4_PANIC_CAUSE_ID_89

  Description:
  Internal Panic Cause ID 89
  error_id:
  P4_E_CONFIG

  msg:
  "KMEM cannot be allocated with fixed physical addresses (Arg == respart)"

  regs:
  NULL

  arg:
  rp_id

  component:
  KERNEL

P4_PANIC_CAUSE_ID_90

  Description:
  Internal Panic Cause ID 90
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 487

     P4_E_CONFIG

     msg:
     "MM: Overlapping memory detected (with free) (Arg == start)"

     regs:
     NULL

     arg:
     start

     component:
     KERNEL

P4_PANIC_CAUSE_ID_91

     Description:
     Internal Panic Cause ID 91
     error_id:
     P4_E_CONFIG

     msg:
     "MM: Overlapping memory detected (with tmp) (Arg == start)"

     regs:
     NULL

     arg:
     start

     component:
     KERNEL

P4_PANIC_CAUSE_ID_92

     Description:
     Internal Panic Cause ID 92
     error_id:
     P4_E_CONFIG

     msg:
     "MM: memory test failed (Arg == addr)"

     regs:
     NULL

     arg:
     (P4_address_t)addr


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

488 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_93

  Description:
  Internal Panic Cause ID 93
  error_id:
  P4_E_CONFIG

  msg:
  "MM: Too many tmp entries added (Arg == start)"

  regs:
  NULL

  arg:
  start

  component:
  KERNEL

P4_PANIC_CAUSE_ID_94

  Description:
  Internal Panic Cause ID 94
  error_id:
  P4_E_OOMEM

  msg:
  "Out of memory (Arg == size)"

  regs:
  NULL

  arg:
  size

  component:
  KERNEL

P4_PANIC_CAUSE_ID_95

  Description:
  Internal Panic Cause ID 95
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 489

     P4_E_CONFIG

     msg:
     "Duplicate cookie (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id

     component:
     KDEV

P4_PANIC_CAUSE_ID_96

     Description:
     Internal Panic Cause ID 96
     error_id:
     P4_E_CONFIG

     msg:
     "Callback .prepare_gate failed (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id

     component:
     KDEV

P4_PANIC_CAUSE_ID_97

     Description:
     Internal Panic Cause ID 97
     error_id:
     P4_E_CONFIG

     msg:
     "No such provider (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

490 The PikeOS Kernel API

  component:
  KDEV

P4_PANIC_CAUSE_ID_98

  Description:
  Internal Panic Cause ID 98
  error_id:
  P4_E_CONFIG

  msg:
  "Callback .init_part failed (Arg == respart)"

  regs:
  NULL

  arg:
  rp_id

  component:
  KDEV

P4_PANIC_CAUSE_ID_99

  Description:
  Internal Panic Cause ID 99
  error_id:
  P4_E_CONFIG

  msg:
  "Too many gates"

  regs:
  NULL

  arg:
  0

  component:
  KDEV

P4_PANIC_CAUSE_ID_100

  Description:
  Internal Panic Cause ID 100
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 491

     P4_E_CONFIG

     msg:
     "Callback .init_gate failed (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id

     component:
     KDEV

P4_PANIC_CAUSE_ID_101

     Description:
     Internal Panic Cause ID 101
     error_id:
     P4_E_CONFIG

     msg:
     "Driver does not drv_gate_set_ops (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id

     component:
     KDEV

P4_PANIC_CAUSE_ID_102

     Description:
     Internal Panic Cause ID 102
     error_id:
     P4_E_CONFIG

     msg:
     "Inconsistent VM_O_MOUNT gate perm vs. prov type (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

492 The PikeOS Kernel API

  component:
  KDEV

P4_PANIC_CAUSE_ID_103

  Description:
  Internal Panic Cause ID 103
  error_id:
  P4_E_CONFIG

  msg:
  "Callback .init_prov failed"

  regs:
  NULL

  arg:
  0

  component:
  KDEV

P4_PANIC_CAUSE_ID_104

  Description:
  Internal Panic Cause ID 104
  error_id:
  P4_E_CONFIG

  msg:
  "Callback .init_cpu failed"

  regs:
  NULL

  arg:
  0

  component:
  KDEV

P4_PANIC_CAUSE_ID_105

  Description:
  Internal Panic Cause ID 105
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 493

     P4_E_CONFIG

     msg:
     "Callback .init_complete failed"

     regs:
     NULL

     arg:
     0

     component:
     KDEV

P4_PANIC_CAUSE_ID_106

     Description:
     Internal Panic Cause ID 106
     error_id:
     P4_E_BADTASK

     msg:
     "Request to terminate sigma0 task"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_107

     Description:
     Internal Panic Cause ID 107
     error_id:
     P4_E_CONFIG

     msg:
     "Time partition switcher table mustnt be empty"

     regs:
     NULL

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

494 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_108

  Description:
  Internal Panic Cause ID 108
  error_id:
  P4_E_CONFIG

  msg:
  "Time partition switcher table exceeds maximum size"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_109

  Description:
  Internal Panic Cause ID 109
  error_id:
  P4_E_CONFIG

  msg:
  "UK_NS_PER_TP_TICK must not be zero"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_110

  Description:
  Internal Panic Cause ID 110
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 495

     P4_E_CONFIG

     msg:
     "UK_NS_PER_TP_TICK is not a multiple of UK_NS_PER_TICK or of the minimum tick
         resolution in dyntick mode"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_111

     Description:
     Internal Panic Cause ID 111
     error_id:
     P4_E_TIMEOUT

     msg:
     "TP overtaking: CPUs are out of sync (Arg == cpu)"

     regs:
     NULL

     arg:
     curr_cpu

     component:
     KERNEL

P4_PANIC_CAUSE_ID_112

     Description:
     Internal Panic Cause ID 112
     error_id:
     P4_E_TIMEOUT

     msg:
     "Time partition overrun during sync (Arg == cpu)"

     regs:
     NULL

     arg:


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

496 The PikeOS Kernel API

  cpu

  component:
  KERNEL

P4_PANIC_CAUSE_ID_113

  Description:
  Internal Panic Cause ID 113
  error_id:
  P4_E_CONFIG

  msg:
  "PSP has too many interrupts"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_114

  Description:
  Internal Panic Cause ID 114
  error_id:
  P4_E_NOENT

  msg:
  "Unhandled spurious interrupt (Arg == IRQ)"

  regs:
  NULL

  arg:
  id

  component:
  KERNEL

P4_PANIC_CAUSE_ID_115

  Description:
  Internal Panic Cause ID 115
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 497

     P4_E_CONFIG

     msg:
     "Allocation only allowed at init (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id

     component:
     KDEV

P4_PANIC_CAUSE_ID_116

     Description:
     Internal Panic Cause ID 116
     error_id:
     P4_E_OOMEM

     msg:
     "Out of memory (Arg == total)"

     regs:
     NULL

     arg:
     total

     component:
     KDEV

P4_PANIC_CAUSE_ID_117

     Description:
     Internal Panic Cause ID 117
     error_id:
     P4_E_CONFIG

     msg:
     "Invalid number of tasks configured"

     regs:
     NULL

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

498 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_118

  Description:
  Internal Panic Cause ID 118
  error_id:
  P4_E_CONFIG

  msg:
  "PSP does not support dynamic ticker mode"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_119

  Description:
  Internal Panic Cause ID 119
  error_id:
  P4_E_CONFIG

  msg:
  "SMP PSP does not support dynamic ticker mode"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_120

  Description:
  Internal Panic Cause ID 120
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 499

     P4_E_CONFIG

     msg:
     "UK_NS_PER_TICK must not be zero"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_121

     Description:
     Internal Panic Cause ID 121
     error_id:
     P4_E_CONFIG

     msg:
     "PSP does not support periodic ticker mode"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_122

     Description:
     Internal Panic Cause ID 122
     error_id:
     P4_E_CONFIG

     msg:
     "Invalid ticker mode selected"

     regs:
     NULL

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

500 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_123

  Description:
  Internal Panic Cause ID 123
  error_id:
  P4_E_CONFIG

  msg:
  "Cannot setup ticker for given frequency"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_124

  Description:
  Internal Panic Cause ID 124
  error_id:
  P4_E_CONFIG

  msg:
  "Invalid global romimage"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_125

  Description:
  Internal Panic Cause ID 125
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 501

     P4_E_CONFIG

     msg:
     "Romimage size is larger than partrom area (Arg == respart)"

     regs:
     NULL

     arg:
     respart

     component:
     KERNEL

P4_PANIC_CAUSE_ID_126

     Description:
     Internal Panic Cause ID 126
     error_id:
     P4_E_CONFIG

     msg:
     "Invalid local romimage (Arg == respart)"

     regs:
     NULL

     arg:
     respart

     component:
     KERNEL

P4_PANIC_CAUSE_ID_127

     Description:
     Internal Panic Cause ID 127
     error_id:
     P4_E_CONFIG

     msg:
     "Bad romimage partition id (Arg == respart)"

     regs:
     NULL

     arg:
     respart


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

502 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_128

  Description:
  Internal Panic Cause ID 128
  error_id:
  P4_E_CONFIG

  msg:
  "Property link level exceeds maximum"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_129

  Description:
  Internal Panic Cause ID 129
  error_id:
  P4_E_CONFIG

  msg:
  "Property node has unexpected type"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_130

  Description:
  Internal Panic Cause ID 130
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 503

     P4_E_CONFIG

     msg:
     "Property is missing"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_131

     Description:
     Internal Panic Cause ID 131
     error_id:
     P4_E_CONFIG

     msg:
     "Missing global VMIT (Arg == respart)"

     regs:
     NULL

     arg:
     respart

     component:
     KERNEL

P4_PANIC_CAUSE_ID_132

     Description:
     Internal Panic Cause ID 132
     error_id:
     P4_E_CONFIG

     msg:
     "Invalid VMIT (Arg == respart)"

     regs:
     NULL

     arg:
     respart


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

504 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_133

  Description:
  Internal Panic Cause ID 133
  error_id:
  P4_E_CONFIG

  msg:
  "VMIT for wrong partition (Arg == respart)"

  regs:
  NULL

  arg:
  respart

  component:
  KERNEL

P4_PANIC_CAUSE_ID_134

  Description:
  Internal Panic Cause ID 134
  error_id:
  P4_E_CONFIG

  msg:
  "Expected exactly 1 Partition in local VMIT (Arg == respart)"

  regs:
  NULL

  arg:
  respart

  component:
  KERNEL

P4_PANIC_CAUSE_ID_135

  Description:
  Internal Panic Cause ID 135
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 505

     P4_E_CONFIG

     msg:
     "Mismatch of Partition Identifier in VMIT (Arg == respart)"

     regs:
     NULL

     arg:
     respart

     component:
     KERNEL

P4_PANIC_CAUSE_ID_136

     Description:
     Internal Panic Cause ID 136
     error_id:
     P4_E_CONFIG

     msg:
     "Too many ROM Images defined!"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_137

     Description:
     Internal Panic Cause ID 137
     error_id:
     P4_E_CONFIG

     msg:
     "Unaligned addresses or sizes used for tracing"

     regs:
     NULL

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

506 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_138

  Description:
  Internal Panic Cause ID 138
  error_id:
  P4_E_CONFIG

  msg:
  "Unable to allocate memory buffers for tracing"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_139

  Description:
  Internal Panic Cause ID 139
  error_id:
  P4_E_CONFIG

  msg:
  "Unaligned addresses or sizes used for tracing"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_140

  Description:
  Internal Panic Cause ID 140
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 507

     P4_E_CONFIG

     msg:
     "Trace memory pool too small"

     regs:
     NULL

     arg:
     0

     component:
     KERNEL

P4_PANIC_CAUSE_ID_141

     Description:
     Internal Panic Cause ID 141
     error_id:
     P4_E_INVAL

     msg:
     "Unhandled Partition Error (Arg == respart)"

     regs:
     NULL

     arg:
     rp_id

     component:
     KERNEL

P4_PANIC_CAUSE_ID_142

     Description:
     Internal Panic Cause ID 142
     error_id:
     P4_E_INVAL

     msg:
     "Unhandled Partition Error"

     regs:
     NULL

     arg:
     0


                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

508 The PikeOS Kernel API

  component:
  KERNEL

P4_PANIC_CAUSE_ID_143

  Description:
  Internal Panic Cause ID 143
  error_id:
  P4_E_INVAL

  msg:
  "Unhandle Defer Partition Error (Arg == respart)"

  regs:
  NULL

  arg:
  i

  component:
  KERNEL

P4_PANIC_CAUSE_ID_144

  Description:
  Internal Panic Cause ID 144
  error_id:
  P4_E_CONFIG

  msg:
  "Sigma0 binary not found"

  regs:
  NULL

  arg:
  0

  component:
  KERNEL

P4_PANIC_CAUSE_ID_145

  Description:
  Internal Panic Cause ID 145
  error_id:


                      c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 509

     P4_E_CONFIG

     msg:

     "\"rfs:sigma0\" is not a suitable ELF"

     regs:

     NULL

     arg:

     0

     component:

     KERNEL

P4_PANIC_CAUSE_ID_146

     Description:
     Internal Panic Cause ID 146
     error_id:

     VARIABLE

     msg:

     "Cannot create sigma0 segment"

     regs:

     NULL

     arg:

     0

     component:

     KERNEL

P4_PANIC_CAUSE_MAX_RESERVED

     Description:
     Maximum Internal Panic Cause Identifier.

P4_panic_cause_ALL Iteration macro This macro can be used to iterate all values of the enum type.

P4_HM_LEVEL_MODULE 0

     Description:
     Module Level Error.


                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

510 The PikeOS Kernel API

P4_HM_LEVEL_PARTITION 1

    Description:
    Partition Level Error.

P4_HM_LEVEL_USER 2

    Description:
    User Level Error.

P4_hm_level_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

P4_hm_level_MAX 2

    Description:
    Maximum value of the enum type

P4_HM_MAC_IGNORE 0

    Description:
    Ignore the Module-level error.

P4_HM_MAC_SHUTDOWN 1

    Description:
    The module-level error results in a module shutdown (soft power off).

P4_HM_MAC_POWEROFF 2

    Description:
    The module-level error results in a module power off (hard power off).

P4_HM_MAC_RESET 3

    Description:
    The module-level error results in a module reset (hard reset).

P4_hm_mac_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

P4_hm_mac_MAX 3

    Description:
    Maximum value of the enum type


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 511

P4_HM_PAC_IDLE 0

     Description:
     Set the partition in IDLE state.

P4_HM_PAC_COLD_START 1

     Description:
     Restart the partition with a COLD start.

P4_HM_PAC_WARM_START 2

     Description:
     Restart the partition with a WARM start.

P4_HM_PAC_IGNORE 4

     Description:
     Ignore the error.

P4_hm_pac_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

P4_hm_pac_MAX 4

     Description:
     Maximum value of the enum type

P4_HM_TYPE_UINT 0

     Description:
     Unsigned Integer Error Type.

P4_HM_TYPE_P4_E 1

     Description:
     Error Type that allows a P4_e_t error to be specified as error identifier.

P4_HM_TYPE_TRAP 2

     Description:
     Error Type that allows a P4_trap_code_t code to be specified as error identifier.

P4_HM_TYPE_PERSONALITY 3

     Description:


                                 c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

512 The PikeOS Kernel API

      Personality-related error types. Refer to the personality (e.g., POSIX, APEX, DDK etc.) documentation
      for the description of this HM_TYPE.

P4_hm_type_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

P4_hm_type_MAX 3

      Description:
      Maximum value of the enum type

1.37.3 Data Type Definitions

P4_hm_error_t Health-Monitoring error structure. This structure identifies an HM-error. The function p4_hm_inject() (see section 1.37.4.4) uses this structure to describe an HM-error that can be injected from the userspace.

      Note:
      msg is normally a string that is passed down to the HM subsystem. The kernel does not assume the
      string be NUL terminated. NULL msg are assumed to have 0 size.

P4_panic_cause_t Panic Cause Identifier. P4_hm_level_t Health monitoring Error Level. P4_hm_mac_t Health monitoring Module Action (MAC). P4_hm_pac_t Health monitoring Partition Action (PAC). P4_hm_type_t Health monitoring Error Type.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 513

1.37.4 Functions

1.37.4.1 p4_hm_register_handler

Register per-CPU partition-level health-monitor handler.

Synopsis:

P4_e_t p4_hm_register_handler(P4_uint32_t *u_counter_p)

Parameters: u_counter_p IN: User space counter to be used in race-free event checking.

Description: This function registers the current thread as handler for partition-level health-monitor events on the current CPU. This function is restricted to the PSSW (privileged software with ability P4_AB_SYSTEM_HM_ERROR). One HM-handler per CPU should be registered on all CPUs to be able to receive and manage partition level HM-events. The affinity mask of the current thread should only contain the current CPU; after the registration, the affinity mask of the registered handler thread can no longer be modified. The value of u_counter_p is atomically incremented by the kernel for every processed partition-level health monitor events: the kernel increments the u_counter_p, and atomically sets the partition level action (PAC, as determined by configuration) in the word of u_pac_action (see p4_hm_register_bitmap) at the position corresponding to the resource partition that generated the partition-level error.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_NOABILITY if the caller does not have the P4_AB_SYSTEM_HM_ERROR ability. P4_E_INVAL if the caller has a CPU affinity mask containing more CPUs than just the current one. P4_E_INVAL if the caller is already registered as a partition-level error handler (via p4_hm_register_handler() (see section 1.37.4.1)) or as a tasks deadline handler (via p4_task_hm_register() (see section 1.17.5.6)). P4_E_INVAL if u_counter_p is not a valid address or exceeds the callers virtual address space. P4_E_INVAL if u_counter_p is not aligned to sizeof(P4_atomic_t) P4_E_INVAL if a thread is already registered as partition error handler for the current CPU.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

514 The PikeOS Kernel API

1.37.4.2 p4_hm_wait

Wait for a health-monitor partition-level error.

Synopsis:

P4_e_t p4_hm_wait(P4_uint32_t compare)

Parameters: compare IN: The last seen value of the registered u_counter_p in p4_hm_register_handler() (see section 1.37.4.1).

Description: A call to this function will trigger the notification in the pre-registered bitmap of partition-level errors. Notified errors increase the u_counter_p (see p4_hm_register_handler() (see section 1.37.4.1)). This function checks if compare equals the value in the registered u_counter_p (see p4_hm_register_handler() (see section 1.37.4.1)) on the current CPU. If the comparison succeeds, the currently calling thread is blocked until either a partition-level HM error is received on the current CPU, or threads is deleted. If the comparison does not succeed, a partition-level error has been concurrently signaled, and the calling thread will not block. To be able to receive HM-partition events and to block on this syscall, the calling thread must be the thread previously registered on this CPU via p4_hm_register_handler() (see section 1.37.4.1). This function is restricted to the PSSW (privileged software with ability P4_AB_SYSTEM_HM_ERROR). The function must be actively entered to detect whether deadlines have expired since the last call to the function.

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_NOABILITY if the caller does not have the P4_AB_SYSTEM_HM_ERROR ability. P4_E_STATE if the comparison between compare and the previously registered u_counter_p did not suc- ceed. P4_E_INVAL if the caller is not the registered partition-level error handler for the current CPU. P4_E_PAGEFAULT if the previously registered u_counter_p is not fully mapped into the callers virtual ad- dress space.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 515

1.37.4.3 p4_hm_register_bitmap

Register global communication array for partition-level HM event.

Synopsis:

P4_e_t p4_hm_register_bitmap(P4_atomic_t *u_pac_action, P4_size_t size)

Parameters: u_pac_action IN: Pointer to a global communication array. size IN: Size of the communication array.

Description: This function registers a global communication array (u_pact_action) to communicate to the PSSW (or to privileged software) health-monitor partition level actions. This function is restricted to the PSSW (privileged software with ability P4_AB_SYSTEM_HM_ERROR). The registered area u_pac_action should be large enough to hold one word for each configured resource partition, e.g., P4_atomic_t u_pac_action[kglobal_info.num_respart]. The communication array u_pac_action is used to atomically word-wise signal the partition action (as configured in the HM table) for the partition that generated the health-monitor event. Each word in the bitmap corresponds to a resource partition (incrementally, starting from 0), and each word is managed as OR-bitmap of partition actions (PAC) with little-endian bit semantics. Signaling of a PAC is coupled with the wakeup of a per-CPU handler, registered with the p4_hm_register_handler() (see section 1.37.4.1).

Returns: Upon success, this function returns P4_E_OK, otherwise one of the following error codes is returned to the caller: P4_E_NOABILITY if the caller does not have the P4_AB_SYSTEM_HM_ERROR ability. P4_E_INVAL if size is not large enough to hold one word for each configured resource partition or size is not a multiple of word size. P4_E_INVAL if u_pac_action is not a valid address or exceeds the callers virtual address space.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

516 The PikeOS Kernel API

1.37.4.4 p4_hm_inject

Inject an error in the kernel health-monitor subsystem.

Synopsis:

P4_e_t p4_hm_inject(P4_uid_t uid, const P4_hm_error_t *error, P4_uint32_t flags)

Parameters: uid IN: UID of the faulter (P4_UID_KEEP identifies the caller). error IN: Health-monitoring error being reported flags IN: Additional parameters to control the behavior of the injected error. Currently, the following flags are defined:

           • P4_HM_FLAG_PANIC
             Cause a kernel panic if the configured error was configured to be ignored. Therefore, the caller
             must have the P4_AB_SYSTEM_HM_ERROR ability.

Description: The function injects a P4_hm_error_t error into the kernel HM-subsystem. The error is handled by the kernel according to the rules in the corresponding health-monitoring tables, depending on the values of domain, type, and id, contained in the P4_hm_error_t error. If the caller has the ability P4_AB_SYSTEM_HM_ERROR set the following restrictions apply:

  • The domain in error is restricted to the values P4_HM_DOMAIN_SYSTEM, P4_HM_DOMAIN_SYS-
    TEM_INIT, or a driver domain.
  • The function allows only the report of partition and/or module level errors; only the resource partition
    information specified in uid will be used.

If the caller does not have the ability P4_AB_SYSTEM_HM_ERROR nor the ability P4_AB_HM_INJECT_OTHER set the following restrictions apply:

  • The caller may only inject errors for its own UID (or P4_UID_KEEP).
  • The domain in error is restricted to the values P4_HM_DOMAIN_USER, P4_HM_DOMAIN_PART, and
    P4_HM_DOMAIN_PART_INIT.
  • The flag P4_HM_FLAG_PANIC must not be set in flags.

If the caller has the ability P4_AB_HM_INJECT_OTHER set, in addition to the possibility of reporting errors for its own UID (subject to the same restriction of the callers that do not have P4_AB_SYSTEM_HM_ERROR nor P4_AB_HM_INJECT_OTHER), it can also report HM_DOMAIN_PART and HM_DOMAIN_PART_INIT errors for other resource partitions. In this case, the following restrictions apply:

  • The domain in error is restricted to the values P4_HM_DOMAIN_PART, and P4_HM_DOMAIN_PART_INIT.


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 517

• The function allows only the report of partition errors; only the resource partition information specified in uid will be used. • The flag P4_HM_FLAG_PANIC must not be set in flags.

The maximum size of the msg within the error structure is P4_HM_MAX_MSG_SIZE. Larger msg are capped to this size.

Note: Refer to the PikeOS User Manual for additional information on the HM subsystem.

Returns: Depending on the configured action, the function may not return. If the configured action is to IGNORE the error and P4_HM_FLAG_PANIC is not set in flags, the function returns P4_E_OK on success. If the P4_HM_FLAG_PANIC is set in flags, the function does NOT return, independently of the configuration. Other- wise, one of the following error codes is returned to the caller: P4_E_NOABILITY The uid is not the caller UID (or P4_UID_KEEP) and the task of the caller does not have the P4_HM_INJECT_OTHER ability set. P4_E_NOABILITY The caller does not have the P4_AB_SYSTEM_HM_ERROR ability set, AND P4_HM_FLAG_PANIC is specified in flags, OR in the P4_hm_error_t error the domain is not one of the restricted domains (P4_HM_DOMAIN_PART_INIT, or P4_HM_DOMAIN_PART, or P4_HM_DO- MAIN_USER), OR type refers to a HM trap. P4_E_NOABILITY The caller has the ability P4_HM_INJECT_OTHER set, AND the uid is not the caller UID (or P4_UID_KEEP), but the domain is P4_HM_DOMAIN_USER OR the resource partition specified in uid is respart 0. P4_E_PAGEFAULT if one of the arguments dereferenced by the kernel does not point to a valid address in the callers virtual address space. P4_E_INVAL If uid is set to P4_UID_INVALID P4_E_INVAL The caller has the ability P4_HM_INJECT_OTHER set, AND the resource partition specified in uid is invalid. P4_E_INVAL If the caller has the P4_AB_SYSTEM_HM_ERROR, but the specified domain is not a system or a driver domain. P4_E_INVAL If the P4_HM_FLAG_PANIC is set but the HM-error has NOT module scope (i.e., the partition of the caller is not partition 0). P4_E_INVAL If an invalid flag is set in flags.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

518 The PikeOS Kernel API

1.37.4.5 p4_hm_raise

Raise an error in the kernel health-monitor subsystem.

Synopsis:

P4_e_t p4_hm_raise(P4_hm_type_t type, P4_uint32_t error_id, const void *msg, P4_size_t size)

Parameters: type IN: Type of the health-monitoring reported error error_id IN: Identifier of the health-monitoring error msg IN: Address of the HM message in the reporter address space size IN: Size of the reported HM message

Description: The function raise a HM-error error_id of type type in the kernel HM-subsystem for the caller thread. Parameters msg of size size provide additional information on the error.

Note: The function calls p4_hm_inject() (see section 1.37.4.4) internally, setting the type, error_id, msg, and size in the corresponding P4_hm_error_t structure. The domain is set to P4_HM_DOMAIN_USER; the uid is set to P4_UID_KEEP. See p4_hm_inject() (see section 1.37.4.4) for a description of the function behavior.

Returns: The return behavior of this function depends on p4_hm_inject() (see section 1.37.4.4), in case of an error the return code of p4_hm_inject() (see section 1.37.4.4) is passed.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Health Monitoring 519

1.37.4.6 p4_hm_panic

Raise a panic-error in the kernel health-monitor subsystem.

Synopsis:

P4_e_t p4_hm_panic(P4_uint32_t domain, P4_hm_type_t type, P4_uint32_t error_id, const void *msg, P4_size_t size)

Parameters: domain IN: Domain for the health-monitoring reported error type IN: Type of the health-monitoring reported error error_id IN: Identifier of the health-monitoring error msg IN: Address of the HM message in the reporter address space size IN: Size of the reported HM message

Description: The function raise a panic HM-error error_id of type type in the kernel HM-subsystem for the caller thread. The error-domain is set to domain. Parameters msg of size size provide additional information on the error. The function will result in a panic, even if the behavior specified in the HM-tables is to ignore the error. This function is restricted to privileged software with P4_AB_SYSTEM_HM_ERROR.

Note: The function calls p4_hm_inject() (see section 1.37.4.4) internally, setting the domain, type, error_id, msg, and size in the corresponding P4_hm_error_t structure. The uid is set to P4_UID_KEEP and the flag P4_HM_FLAG_PANIC is set. See p4_hm_inject() (see section 1.37.4.4) for a description of the function behavior.

Returns: The return behavior of this function depends on p4_hm_inject() (see section 1.37.4.4), in case of an error the return code of p4_hm_inject() (see section 1.37.4.4) is passed.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

520 The PikeOS Kernel API

1.38 KDEV User Space API

This section contains the KDEV User Space API functions invoked from user space into the kernel level device driver framework. These functions are implemented in user space to map to P4 system calls (libp4). In the kernel, these prototypes are implemented again as the system call handler. This API contains the API functions invoked from user space into the kernel level device driver framework. These functions are implemented in user space to map to P4 system calls (libp4). This part of the P4 API is used to implement libvm and PSSWs internal access to the KDEV driver framework. User space applications will not make use of these system calls unless in the special case of running the PikeOS kernel without the PSSW. This API is documented here because it is formally part of the libp4 user space API. But because it is primarily an API used for communication of the components PikeOS Kernel and PSSW rather than a general user application API, it is more likely to change between versions of PikeOS.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 521

1.38.1 Functions

1.38.1.1 p4_kdev_alert_module

Synopsis:

P4_e_t p4_kdev_alert_module(P4_bool_t up)

Parameters: up IN: TRUE when the module is currently booting. If it is shutting down, this is FALSE.

Description: Alert the driver of a module mode switch. This is an internal lowlevel function used in the implementation of the PSSW. Naturally, this is invoked post-up and pre-down. This function requires the P4_AB_KDEV_SETUP ability.

Returns: P4_E_OK on success P4_E_NOABILITY if the caller does not have the ability to invoke this functionality

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

522 The PikeOS Kernel API

1.38.1.2 p4_kdev_alert_part

Synopsis:

P4_e_t p4_kdev_alert_part(drv_respart_t part, P4_bool_t up, vm_part_operating_mode_t new_mode)

Parameters: part IN: partition ID for which to raise an alert up IN: TRUE when the partition is currently booting. If it is shutting down, this is FALSE. new_mode IN: the new mode: when up is TRUE, it is the mode we are entering, and when up is FALSE, it is also the new mode that will be used after the boot.

Description: Alert all drivers of a partition mode switch. This is an internal lowlevel function used in the implementation of the PSSW. The up event into IDLE mode will not be notified. This function requires the P4_AB_KDEV_SETUP ability. This is invoked pre-up and post-down, i.e., the partition code itself is executed only in between these calls.

Returns: P4_E_OK on success P4_E_NOABILITY if the caller does not have the ability to invoke this functionality P4_E_INVAL if part is out of range P4_E_INVAL if an unsupported flag is provided in mode

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 523

1.38.1.3 p4_kdev_discover_gate

Synopsis:

P4_e_t p4_kdev_discover_gate(P4_uint32_t respart_id, P4_uint32_t gate_id, char *u_prov_name, char *u_gate_name, P4_prov_type_t *u_prov_type, drv_cookie_t *u_cookie)

Parameters: respart_id IN: Resource partition id (starts at 0). gate_id IN: gate id (starts at 0 in each partition). u_prov_name OUT: provider name. This char array must be of length at least P4_NAMELEN. u_gate_name OUT: gate name. This char array must be of length at least P4_NAMELEN. u_prov_type OUT: size of gate_name and prov_name. u_cookie OUT: gate cookie.

Description: Discover a gate in a partition. This is an internal lowlevel function used in the implementation of the PSSW. The PSSW uses this to query the list of gates per partition. The enumeration works by incrementing part_id from 0...max partition, and for each such part_id, incrementing gate_id (starting at 0) until P4_E_NOENT is returned instead of P4_E_OK. To use this function, the caller must have P4_AB_KDEV_SETUP ability.

Returns: P4_E_OK if a gate was discovered and *prov_name, *gate_name, *prov_type and *cookie are written accord- ingly. P4_E_NOABILITY if the caller has no ability to use this functionality. P4_E_INVAL if any parameter is invalid, e.g., pointers are not valid. P4_E_NOENT if no gate with the given ID was found in the given partition. Since gates are enumerated contiguously starting from 0, in the same partition, no gate with a larger ID exists either in this case. P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

524 The PikeOS Kernel API

1.38.1.4 p4_kdev_ping_syscall

Synopsis:

P4_e_t p4_kdev_ping_syscall(P4_cpureg_t base_sig, P4_cpureg_t version)

Parameters: base_sig IN: Base signature to identify a DRV entry point structure version IN: DRV API version number

Description: Low-level KDEV ping function. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This implements the system call and should not be called directly. Use p4_kdev_ping() (see section 1.38.1.5) instead.

Returns: P4_E_OK if the version numbers agree and KDEV is present P4_E_INVAL if the version numbers do not agree and a HM event was raised.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 525

1.38.1.5 p4_kdev_ping

Synopsis:

__forceinline P4_e_t p4_kdev_ping(void)

Description: Check that the kernel driver exists and speaks the same protocol as the caller does. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. User space passes in the checksum values, which this function will acknowledge if they are equal with the kernel library in use. In case KDEV has a different version than user space, this function will raise a HM event P4_HM_DO- MAIN_PART,P4_HM_TYPE_P4_E,P4_E_INVAL. The debug kernel also prints a descriptive error message containing the mismatching version numbers.

Returns: P4_E_OK if the version numbers agree and KDEV is present P4_E_INVAL if the version numbers do not agree and a HM event was raised.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

526 The PikeOS Kernel API

1.38.1.6 p4_kdev_spawn

Synopsis:

P4_e_t p4_kdev_spawn(P4_uid_t client, P4_uint32_t prov_id, drv_cookie_t cookie, vm_file_access_mode_t flags, drv_handle_t *u_handle)

Parameters: client IN: the UID of the client on behalf of which this request is issued and the new descriptor to be allocated prov_id IN: the provider of the gate cookie IN: the gates ID in that provider flags IN: the access mode to open the gate with. This will be checked against static permissions the driver may have. u_handle OUT: the new gate descriptor handle.

Description: Allocate a descriptor and associate it with a kernel gate descriptor. This is an internal lowlevel function used in the implementation of the PSSW. The kernel will return a handle, which the PSSW will then send back to libvm as part of the user space descriptor. To finalize the opening process, p4_kdev_open() (see section 1.38.1.8) must be invoked. Before p4_kdev_open() (see section 1.38.1.8), only p4_kdev_descend() (see section 1.38.1.9) and p4_kdev_close() (see section 1.38.1.11) can be used on the gate descriptor. After p4_kdev_open() (see section 1.38.1.8), p4_kdev_descend() (see section 1.38.1.9) cannot be used anymore on the descriptor. This function will never block. This function requires the P4_AB_KDEV_SETUP ability.

Returns: P4_E_OK on success P4_E_NOABILITY if the caller has no ability to invoke this function P4_E_PERM if the access is not granted P4_E_OOFILE if there is no more descriptor left to be used P4_E_INVAL if prov_id is an invalid provider ID P4_E_INVAL if client contains an invalid resource partition ID P4_E_NOENT if no gate with cookie was found for the given provider P4_E_INVAL if any other parameter setting is not valid P4_E_INVAL if an unsupported flag is provided in mode P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. Other error codes raised by the driver in its .gd_init callback.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 527

1.38.1.7 p4_kdev_dup

Synopsis:

P4_e_t p4_kdev_dup(drv_handle_t old_handle, P4_uid_t client, drv_handle_t *u_new_handle)

Parameters: old_handle IN: the handle of the gate descriptor to copy client IN: the UID of the client on behalf of which this request is issued and the new descriptor to be allocated, or 0 if it is the current UID u_new_handle OUT: the new gate descriptor handle

Description: Allocate a new descriptor and copy the association with the item from the old one, and also copy state information, if any. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. To finalize the opening process, p4_kdev_open() (see section 1.38.1.8) must be invoked. Before p4_kdev_open() (see section 1.38.1.8), only p4_kdev_descend() (see section 1.38.1.9) and p4_kdev_close() (see section 1.38.1.11) can be used on the gate descriptor. After p4_kdev_open() (see section 1.38.1.8), p4_kdev_descend() (see section 1.38.1.9) cannot be used anymore on the descriptor. This function will never block. If client != 0, then this function requires the P4_AB_KDEV_SETUP ability.

Returns: P4_E_OK on success P4_E_NOABILITY if the caller has no ability to invoke this function P4_E_INVAL if the descriptor is in pre-open mode or being closed, and is used by another thread. P4_E_INVAL if any parameter is invalid, e.g., pointers do not point to user space. P4_E_OOFILE if the framework is out of gate descriptors P4_E_NOTIMPL if the driver does not implement dup functionality P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. Other error codes raised by the driver in its .gd_copy callback.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

528 The PikeOS Kernel API

1.38.1.8 p4_kdev_open

Synopsis:

P4_e_t p4_kdev_open(drv_handle_t handle)

Parameters: handle IN: the handle of the gate descriptor for which to finalize the opening process.

Description: Open a gate and associate it with a kernel gate descriptor. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. The kernel will return a handle, which the PSSW will then send back to libvm as part of the user space descriptor. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE. This function returns P4_E_STATE if an attempt is made to mount a volume twice in the same partition.

Returns: P4_E_OK if the open operation succeeded P4_E_INVAL if the descriptor is not in pre-open state, e.g., if the p4_kdev_open has already been invoked. P4_E_INVAL if the descriptor is in pre-open state but currently being opened by another thread. P4_E_STATE if the descriptor references a mount gate and the mount point has already been opened in the requesting partition. P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .gd_open callback.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 529

1.38.1.9 p4_kdev_descend

Synopsis:

P4_e_t p4_kdev_descend(drv_handle_t handle, const char *u_path, P4_size_t path_len, vm_file_access_mode_t flags)

Parameters: handle IN: the handle of the gate descriptor to modify u_path IN: the name of the path component to use for entering the directory (the name of the subdirectory). path_len IN: the maximum length of the directory name. This must be smaller than or be equal to P4_MAX_EXT_PATHNAME_LEN. The name need not be NUL terminated, because user space may iterate a path without inserting NULs, in which case, the path is / terminated. flags IN: the mode to open the new item with (no check will be performed in this function call, but only in subsequent p4_kdev_descend or p4_kdev_open calls).

Description: Enter a subdirectory relative to the given descriptor. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. On a descriptor after spawn() or dup(), but before open(), this can be used to select an item in the directory and reset the descriptor to that item. u_name need not be NUL terminated within name_len, i.e., it is OK to pass e.g. subpaths and terminating them by setting name_len appropriately. The maximum string size is P4_MAX_EXT_PATHNAME_LEN. This function is the API to implement name service for file names in a driver, by which relative to a given descriptor, the driver can change to another item, i.e., this is like chdir that allows no .. and only a single path component (i.e., no /). The passed handle must have been opened with VM_O_EXEC permissions if the path is non-empty. The passed mode may be checked by the underlying driver callback. Depending on the driver, such access control checks may be delayed until p4_kdev_open() (see section 1.38.1.8), because the driver may not have permission information without blocking. If this function fails (i.e., returns anything but P4_E_OK), the descriptor will be set to an access permission mask of 0 to avoid further usage. In this case, the descend request may only have been fulfilled partially, depending on the driver. A typical cause is a permission check on an intermediate directory path component, in which case the descend stops before entering such a directory. Such partial effects of descend will not be undone. The only thing that should be done with such a descriptor is to close it. This function may block for mount point gates, but will never block for normal gates. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE.

Returns: P4_E_OK if everything is find P4_E_NOCONTAINER if a path component or the root descriptor is not a directory

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

530 The PikeOS Kernel API

P4_E_PERM if any directory that needs to be opened to descend into the subpatch has no VM_O_EXEC permissions P4_E_PERM if the opened file must not be opened with the requested permissions. P4_E_RESTRICTED if mode contains VM_O_WR and the file system this is on is opened in read-only mode. P4_E_INVAL if the string is too long P4_E_INVAL if an unsupported flag is provided in mode P4_E_INVAL if mode contains the VM_O_MOUNT flag P4_E_INVAL if any parameter in invalid, e.g., any pointer does not point to user space P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_NOTIMPL if the driver does not implement descend functionality P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .descend callback.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 531

1.38.1.10 p4_kdev_negotiate

Synopsis:

P4_e_t p4_kdev_negotiate(drv_handle_t handle, drv_cap_type_t ctrl_type, drv_cap_type_t meta_type, P4_bool_t *u_ctrl_used, vm_file_access_mode_t *u_meta_dir)

Parameters: handle IN: the handle of the gate descriptor ctrl_type IN: the type of control data the caller potentially wants to use (it may always pass a NULL pointer to read/write/discard to not use control data). meta_type IN: the type of meta data the caller expects to be transferred alongside data (the meta pointer may also be NULL to not use any meta data). u_ctrl_used OUT: non-false if the provider supports the requested control data. u_meta_dir OUT: the direction in which the provider supports the requested type of meta data. The bits VM_O_RD and VM_O_WR decide for each direction.

Description: Negotiate about the type of control and meta data to use on the given gate. The driver may support several control and meta types, and with this call, the user space tells the framework which one it wants to use. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. If the type is identical to what the gate supports, the supported access direction will be returned. From the returned access direction the user knows which of read or write supports the meta type. The support for the meta type on drv_pstat depends on the query direction. drv_pstats ctrl arguments direction cannot be negotiated in advance with this function. Control data is R/W in both read(), write(), discard(), and pstat() calls. It can be used to pass additional information into the kernel (e.g. for sampling ports to filter the message by age) or to pass a pointer to state information (e.g. a file position). In general, since ctrl data is R/W and the exact usage depends on the driver, it is no error to pass a ctrl pointer to read()/write()/discard()/pstat() functions. It will just be ignored if negotiate fails for the ctrl type. In contrast, since meta data moves together with the message, the user can expect that if the buffer was read, the meta data was read, too, and if buffer was written, so was the meta data. Thus if the negotiation of meta data fails in a given direction, then read()/write() will return an error message if the meta pointer is non-null. This is to protect against false assumptions. In case this function returns an error, the used control or meta data is unchanged from the last negotiation attempt. Immediately after opening, DRV_TYPE_NULL is in use for both control and meta data, until a successful negotiation is performed. This function never blocks.

Returns:

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

532 The PikeOS Kernel API

P4_E_OK on success, i.e., control and meta types could be negotiated, albeit maybe DRV_TYPE_NULL is used instead of what the caller requested, i.e., P4_E_OK does not mean the kernel necessarily agrees on the types. P4_E_INVAL if the descriptor is not open, has the wrong type or cannot be accessed. P4_E_INVAL if a parameter is invalid, e.g., any pointer does not point to user space P4_E_INVAL if the descriptor is a mount point descriptor P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter.

                         c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 533

1.38.1.11 p4_kdev_close

Synopsis:

P4_e_t p4_kdev_close(drv_handle_t handle)

Parameters: handle IN: the handle of the gate descriptor to close

Description: Close a gate. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This frees the kernel gate descriptor and closes the gate. This function may block. The timeout used for blocking is always P4_TIMEOUT_INFINITE, independent from the setting of the VM_O_NONBLOCK flag used to open this descriptor. Note that the .close callback has no error case (returns void), so no error codes additional to the ones listed here may be generated by the driver.

Returns: P4_E_OK on success P4_E_INVAL if there are still other threads using the handle. P4_E_INVAL if handle is not a valid handle. P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

534 The PikeOS Kernel API

1.38.1.12 p4_kdev_pstat

Synopsis:

P4_e_t p4_kdev_pstat(drv_handle_t handle, drv_status_t *u_status, void *u_ctrl, void *u_meta_rd, void *u_meta_wr)

Parameters: handle IN: the handle of the gate descriptor to query the status of u_status OUT: a struct with status information about the underlying gate. It may be NULL if the user is not interested in this kind of data. u_ctrl OUT: the ctrl data that might be the maximum or the default of the descriptor. It may be NULL if the user is not interested in this data. If 0 was returned by kdev_negotiate for the ctrl type, the pointer is ignored and not written, but no error is produced. Check the result of kdev_negotiate instead. u_meta_rd OUT: the meta type of the next message/data that is available. If no data is available, this will not be written. In contrast to read(), if kdev_negotiate return 0 for the meta type, this pointer will be ignored and no data written, but this will not cause an error. This is because the meta data returned in this call is not tied to a message. The meta data pointer may be NULL if the caller is not interested in the meta data. u_meta_wr OUT: like meta_rd in writing direction. In stat, it is the default meta data that is send along the write path if no data is specified. If 0 was returned by kdev_negotiate() for the meta type direction, the pointer is ignored but no error is produced because of this. This pointer can be NULL if the caller is not interested in the meta data.

Description: Retrieve the status of the given gate. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This function works on an open gate and returns both configuration and dynamic status. This function never blocks.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor handle is in pre-open state and used by another thread (e.g., it is being closed or still being opened). P4_E_INVAL if the descriptor is a mount point descriptor P4_E_INVAL if any parameter is invalid, e.g., a pointer does not point to user space. P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes the driver returns from the .pstat callback.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 535

1.38.1.13 p4_kdev_control

Synopsis:

P4_e_t p4_kdev_control(drv_handle_t handle, P4_uint32_t cmd, void *u_data)

Parameters: handle IN: the handle of the gate descriptor to operate on cmd IN: the command ID generated by VM_IOC_* macros to select the funtionality to address. u_data INOUT: additional data to be transferred in/out, dependening on the size bits in the cmd.

Description: Arbitrary unstructured control call. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This function allows the call of custom functionality extensions. Its usage is discouraged when possible, since the call is mostly unstructured, and in most cases it is better to implement an additional control device and use read()/write(). The values passed for cmd must be constructed using the VM_IOC_* macros to allow the kernel to perform some validation on the buffer sizes. Note that the KDEV framework has no permission check for this function. Still, drivers may restrict access to specific commands and return P4_E_PERM. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor handle is not open (pre-open and being opened or being closed by another thread) P4_E_INVAL if the descriptor is a mount point descriptor P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_NOTIMPL if the driver does not implement control functionality P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes the driver returns from the .control callback.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

536 The PikeOS Kernel API

1.38.1.14 p4_kdev_read_syscall

Synopsis:

P4_e_t p4_kdev_read_syscall(drv_handle_t handle, void *u_buff, P4_size_t *u_read_sz, void *u_ctrl, void *u_meta, const P4_timeout_t *u_timeout)

Parameters: handle IN: the handle of the gate descriptor to read from u_buff IN: the pointer to the buffer to be read. u_read_sz INOUT: as an input parameter defines the size of u_buff, and as on output parameter returns the number of bytes read. If *u_to is P4_KDEV_TIMEOUT_INHERIT, then the timeout will be set up according to the VM_O_NONBLOCK flag of the gate descriptor associated with handle. u_ctrl INOUT: possible data to control exactly the read operation u_meta OUT: meta data coming along the read data u_timeout IN: timeout for the operation

Description: Read data from a gate. This callback tries to read buff_sz bytes from the file given by the gate descriptor associated to handle and stores the result in u_buff. the number of bytes read is stored in u_read_sz. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This is an internal function that wraps the system call. Use p4_kdev_read() (see section 1.38.1.27) instead. u_buff_sz is copied in before the actual operation, and copied back out to user space afterwards. Therefore, if this function returns P4_E_PAGEFAULT, it cannot be distinguished by the caller whether the operation was executed or not.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 537

1.38.1.15 p4_kdev_write_syscall

Synopsis:

P4_e_t p4_kdev_write_syscall(drv_handle_t handle, const void *u_buff, P4_size_t *u_write_sz, void *u_ctrl, const void *u_meta, const P4_timeout_t *u_timeout)

Parameters: handle IN: the handle of the gate descriptor to write to u_buff IN: the pointer to the buffer to be written. u_write_sz INOUT: as an input parameter defines the size of u_buff, and as an output parameter returns how many bytes were written. u_ctrl INOUT: possible data to control exactly the read operation u_meta OUT: meta data being sent along the written data u_timeout IN: timeout for the operation

Description: Write data to a gate. This callback tries to write buff_sz bytes taken from the buffer u_buff to the file given by the gate descriptor associated to handle. the number of bytes written is stored in u_read_sz. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This is an internal function that wraps the system call. Use p4_kdev_write() (see section 1.38.1.28) instead. u_buff_sz is copied in before the actual operation, and copied back out to user space afterwards. Therefore, if this function returns P4_E_PAGEFAULT, it cannot be distinguished by the caller whether the operation was executed or not.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

538 The PikeOS Kernel API

1.38.1.16 p4_kdev_map_to

Synopsis:

P4_e_t p4_kdev_map_to(drv_handle_t handle, P4_size_t size, void *u_ctrl, P4_task_t task_no, P4_address_t addr, vm_memory_access_mode_t perm)

Parameters: handle IN: the handle of the gate descriptor to map from size u_ctrl task_no addr perm

Description: Map a region of memory into user space memory. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. The VM_O_MAP permission is required on the file to do this. Unless the invoking thread has the P4_AB_MEM_CREATE ability, task must be equal to P4_TASK_MYSELF, otherwise this function will fail with P4_E_NOABILITY. Perm is the access permissions the memory is to be mapped with. Passing no RD, WR, or EXEC permissions is invalid. Additional to these flags, VM_MEM_ACCESS_EXCL may be passed to prevent overmapping. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE.

Returns: P4_E_OK on success P4_E_NOABILITY if task is not P4_TASK_MYSELF and the calling thread has no P4_AB_MEM_CREATE ability. P4_E_PERM if the descriptor is not opened with VM_O_MAP permissions P4_E_PERM if any of the RD, WR, or EXEC bits are set in perm, but have not been used to open the descriptor. P4_E_INVAL if any unsupported bit is set in perm P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor handle is not open (pre-open and being opened or being closed by another thread) P4_E_INVAL if the descriptor is a mount point descriptor P4_E_INVAL if an unsupported flag is provided in perm P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 539

P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_NOTIMPL if the driver does not implement map functionality P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .map_to callback.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

540 The PikeOS Kernel API

1.38.1.17 p4_kdev_discard_syscall

Synopsis:

P4_e_t p4_kdev_discard_syscall(P4_off_t sz, drv_handle_t handle, const void *u_ctrl_in, void *u_ctrl_out, P4_off_t *u_discard_sz)

Description: Discard data in a gate. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. Use p4_kdev_discard() (see section 1.38.1.30) instead, which is equivalent but has the intended user API. In contrast to overwriting, this can be used to indicate that data shall be totally invalidated. This may be useful for flash devices that may have an internal knowledge of which blocks are in use, and it may also be of use to reset the contents of a sampling port. Depending on the driver, discard operations are either read or write operations, or need special protection. The driver has the responsibility to do permission checking and/or define an additional gate for special access permission handling. u_ctrl may be copied in before the actual operation, and u_discard_sz is copied out to user space afterwards. Therefore, if this function returns P4_E_PAGEFAULT, it cannot be distinguished by the caller whether the operation was executed or not.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 541

1.38.1.18 p4_kdev_test

Synopsis:

P4_e_t p4_kdev_test(drv_handle_t handle, vm_test_mode_t test_mode, P4_uint32_t cmd)

Parameters: handle IN: the handle of the gate descriptor to map from test_mode IN: the mode of the test operation cmd IN: the command of the test operation

Description: Do tests, trigger them asynchronously, or stop them. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. Utility function to access testing functionalities. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor is a mount point descriptor P4_E_INVAL if the descriptor handle is not open (e.g., not yet open, being opened, or being closed by another thread) P4_E_INVAL if an unsupported flag is provided in mode P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_NOTIMPL if the driver does not implement test functionality P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .test callback.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

542 The PikeOS Kernel API

1.38.1.19 p4_kdev_psync

Synopsis:

P4_e_t p4_kdev_psync(drv_handle_t handle)

Parameters: handle IN: the handle of the gate descriptor to sync data on

Description: Synchronize data that is currently in any intermediate data buffer to the underlying medium. Wait until all remaining intermediate buffers have been flushed. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. There is no particular access control to the psync() call: partitions may invoke this on any gate they can access with either read or write permissions. The rationale behind this is that the writing of data itself is never performed by this call - this is done by write() only, but synchronizing to the underlying media may be interesting for readers, too. Drivers are free to implement additional access control, though. This function may block. The timeout used for blocking is always P4_TIMEOUT_INFINITE, independent from the setting of the VM_O_NONBLOCK flag used to open this descriptor.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor is a mount point descriptor P4_E_INVAL if the descriptor handle is not open (e.g., not yet open, being opened, or being closed by another thread) P4_E_NOTIMPL if the driver does not implement map functionality P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .psync callback.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 543

1.38.1.20 p4_kdev_lseek_syscall

Synopsis:

P4_e_t p4_kdev_lseek_syscall(P4_off_t offset, drv_handle_t handle, P4_origin_t origin, P4_off_t *u_filepos_inout, P4_off_t *u_filepos_out)

Description: Compute a new file position based and store in two locations. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. Use p4_kdev_lseek() (see section 1.38.1.29) instead, which is equivalent but has the intended user API.

Returns: Exactly what p4_kdev_lseek() (see section 1.38.1.29) returns.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

544 The PikeOS Kernel API

1.38.1.21 p4_kdev_unlink

Synopsis:

P4_e_t p4_kdev_unlink(drv_handle_t handle, const char *u_path, P4_size_t path_len, P4_uint32_t flags)

Parameters: handle IN: the handle of the gate descriptor of the mounted file system on which to unlink a file. u_path IN: the path of the file relative to the passed root path_len IN: number of characters relevant in u_path flags IN: flag bits to control the exact behaviour of the operation

Description: Delete a file. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor handle is not open (e.g., not yet open, being opened, or being closed by another thread) P4_E_INVAL if any unsupported bits are set in flags P4_E_PERM if the file system driver forbids the operation due to insufficient access permissions on the file or directory P4_E_RESTRICTED if the underlying file system is mounted read-only. P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_NOTIMPL if the driver does not implement dup functionality P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .unlink callback.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 545

1.38.1.22 p4_kdev_rename

Synopsis:

P4_e_t p4_kdev_rename(drv_handle_t handle, const char *u_old_path, P4_size_t old_path_len, const char *u_new_path, P4_size_t new_path_len, P4_uint32_t flags)

Parameters: handle IN: the handle of the gate descriptor of the mounted file system on which to rename a file. u_old_path IN: the old path relative to the passed root old_path_len IN: number of characters relevant in u_old_path u_new_path IN: the new path relative to the passed root new_path_len IN: number of characters relevant in u_new_path flags IN: flag bits to control the exact behaviour of this operation

Description: Rename a file. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor handle is not open (e.g., not yet open, being opened, or being closed by another thread) P4_E_INVAL if any unsupported bits are set in flags P4_E_PERM if the file system driver forbids the operation due to insufficient access permissions on the file or directory P4_E_RESTRICTED if the underlying file system is mounted read-only. P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_NOTIMPL if the driver does not implement this functionality P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .rename callback.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

546 The PikeOS Kernel API

1.38.1.23 p4_kdev_dir_create

Synopsis:

P4_e_t p4_kdev_dir_create(drv_handle_t handle, const char *u_path, P4_size_t path_len)

Parameters: handle IN: the handle of the gate descriptor of the mounted file system on which to create a directory u_path IN: the path and name of the new directory to create path_len IN: number of bytes relevant in u_path

Description: Create a new directory. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor handle is not open (e.g., not yet open, being opened, or being closed by another thread) P4_E_PERM if the file system driver forbids the operation due to insufficient access permissions on the file or directory P4_E_RESTRICTED if the underlying file system is mounted read-only. P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_NOTIMPL if the driver does not implement dup functionality P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .dir_create callback.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 547

1.38.1.24 p4_kdev_dir_read

Synopsis:

P4_e_t p4_kdev_dir_read(drv_handle_t handle, P4_off_t *u_dirpos, P4_dirent_t *u_dirent)

Parameters: handle IN: the handle of the directory to read u_dirpos INOUT: the directory position from which to read and which to update u_dirent INOUT: the directory entry as read from the directory. This must be zeroed by the caller before invoking this function

Description: Iterate a directory entry by entry. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. User space is expected to zero the u_dirent structure before invoking this system call: the kernel (driver) may only partially overwrite the P4_dirent_t structure with relevant information. Note: Generally, if P4_E_OK is returned, the operation was completely executed. u_dirpos is copied in before the actual operation, and copied back out to user space with the updated value afterwards. Therefore, if this function returns P4_E_PAGEFAULT, it cannot be distinguished by the caller whether the operation was executed or not. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE. Note that *u_dirent must be zeroed by the caller before invoking this function. This way, this API becomes compatible with interpreting u_dirent as a pointer to a char array for the name.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor is a mount point descriptor P4_E_INVAL if the descriptor handle is not open (e.g., not yet open, being opened, or being closed by another thread) P4_E_PERM if the descriptor is not opened for reading. P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_NOTIMPL if the driver does not implement dup functionality P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .dir_read callback.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

548 The PikeOS Kernel API

1.38.1.25 p4_kdev_statvfs

Synopsis:

P4_e_t p4_kdev_statvfs(drv_handle_t handle, const char *u_path, P4_size_t path_len, P4_statvfs_t *u_buf)

Parameters: handle IN: the handle of the gate descriptor of the mounted file system to retrieve the status of u_path IN: path into the file system. Should be empty. path_len IN: length of u_path u_buf OUT: status information of the queried mounted file system

Description: Query information about a file system. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE.

Returns: P4_E_OK on success P4_E_NOTIMPL if the driver does not implement this functionality P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .statvfs callback.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 549

1.38.1.26 p4_kdev_close_all

Synopsis:

P4_e_t p4_kdev_close_all(P4_uid_t uid)

Parameters: uid IN: the UID containing partition and optionally task for which to close all descriptors. The resource partition must be set in the UID, even if a task is given. It is not optional. The task is optional, P4_UID_MASK_TASK indicates that all tasks will be affected. The thread part of the UID must be P4_UID_MASK_THREAD.

Description: Close all descriptors of a partition or task. This is an internal lowlevel function used in the implementation of the PSSW. Used by the PSSW to close all descriptors of a partition after a partition goes down. This returns non-OK if any close operation returns non-OK. This should not happen if the PSSW correctly killed all threads in the partition because the descriptors belong to the partition and are not accessible from another partition. P4_E_TRUNC is returned if there were gds that are still in use and could not be locked for closing. In full partition reboots, this should not happen, because a p4_task_terminate() (see section 1.17.5.4) on all tasks should have killed all users of gds in the partition. If a p4_kdev_close_all() (see section 1.38.1.26) targets a single task, however, there is no guarantee that all gds are lockable for close, so this error should be expected in that case. This function does not return which gds where in use. The corresponding gds will be still in fully operation mode after this call returns, i.e., if a non-closable gd is encounted, it is simply ignored by this call. Also note that you cannot use P4_UID_TASK(task) (see section 1.4.1) for the uid parameter to kill a single task, because this function requires the partition to be set in the UID; it does not accept a partition wildcard. Use P4_UID_BUILD(respart, task, P4_UID_MASK_THREAD) (see section 1.4.1) instead. If task is not part of respart, the function will, if there is no other problem, return P4_E_OK, but essentially do nothing, because no matching threads will be found. For killing a partition, using P4_UID(respart) (see section 1.4.1) for uid is recommended. This function requires the P4_AB_KDEV_SETUP ability.

Returns: P4_E_OK on success P4_E_NOABILITY if the caller does not have the ability to invoke this functionality P4_E_INVAL if partition, task, or thread is invalidly set in uid. P4_E_TRUNC if there were gds that are still in use and could not be locked for closing.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

550 The PikeOS Kernel API

1.38.1.27 p4_kdev_read

Synopsis:

__forceinline P4_e_t p4_kdev_read(drv_handle_t handle, void *u_buff, P4_size_t buff_sz, void *u_ctrl, void *u_meta, P4_timeout_t timeout, P4_size_t *u_read_sz)

Parameters: handle IN: the handle of the gate descriptor to read from u_buff OUT: the pointer to the buffer to be read. buff_sz IN: the size of u_buff u_ctrl INOUT: control data. The exact meaning depends on the driver and on the negotiated control data type. u_meta OUT: this is the pointer to meta data transferred alongside the contents. The exact meaning depends on the driver and on the negatiated meta data type. timeout IN: timeout for this request. u_read_sz OUT: pointer to store how much was written into the buffer. This must not be NULL.

Description: Read data from a gate. This callback tries to read buff_sz bytes from the file given by the gate descriptor associated to handle and stores the result in u_buff. the number of bytes read is stored in u_read_sz. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. Meta data may be associated with the buffer that is returned, and depending on driver, different kind of meta data is returned alongside the actual data. Sampling ports return a time stamp as meta data. SAP ports return source and target address. This function may block. The timeout value for blocking is passed as a parameter. As a timeout value, additional to the normal values for P4_timeout_t, the special value P4_KDEV_TIMEOUT_IN- HERIT may be passed, in which case this function uses P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE de- pending on whether the descriptor was opened with VM_O_NONBLOCK. This behaviour then mirrors that of other blocking p4_kdev_* functions that have no timeout parameter.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor is a mount point descriptor P4_E_INVAL if the descriptor handle is not open (e.g., not yet open, being opened, or being closed by another thread) P4_E_PERM if the descriptor is not open for reading. P4_E_TIMEOUT if no data becomes available within the given timeout. P4_E_BADTIMEOUT if the timeout specification is invalid.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 551

P4_E_NOTIMPL if the operation is generally not possible, supported, or implemented. This includes the case that the meta data pointer is non-NULL while no meta data was negotiated for the read operation. Note that in contrast, a ctrl pointer that is non-NULL will not cause any error but will be ignored if it cannot used. P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .read callback.

See also: p4_kdev_write() (see section 1.38.1.28).

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

552 The PikeOS Kernel API

1.38.1.28 p4_kdev_write

Synopsis:

__forceinline P4_e_t p4_kdev_write(drv_handle_t handle, const void *buff, P4_size_t buff_sz, void *u_ctrl, const void *u_meta, P4_timeout_t timeout, P4_size_t *u_written_sz)

Parameters: handle IN: the handle of the gate descriptor to write to buff IN: the pointer to the buffer to be written. buff_sz IN: the size of u_buff u_ctrl INOUT: control data. The exact meaning depends on the driver and on the negotiated control data type. u_meta IN: this is the pointer to meta data transferred alongside the contents. The exact meaning depends on the driver and on the negatiated meta data type. timeout IN: timeout for this request. u_written_sz OUT: pointer to store how much data was actually written. This must not be NULL.

Description: Write data to a gate. This callback tries to write buff_sz bytes taken from the buffer u_buff to the file given by the gate descriptor associated to handle. the number of bytes written is stored in u_read_sz. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. As with read(), meta data may be associated with the written data, and can thus also be passed into this function. E.g. SAP port drivers may transfer the source and target addresses of the message. If *u_to is P4_KDEV_TIMEOUT_INHERIT, then the timeout will be set up according to the VM_O_NONBLOCK flag of the gate descriptor associated with handle. Concerning the buffer size, this function always uses stream/file semantics, i.e., if buff_sz is too large (larger than drv_status_t::config.xfer_size), this function will just reduce the size and try to transfer only xfer_size bytes, i.e., KDEV drivers will never be passed buffer sizes larger than xfer_size. The smaller size will then be returned via u_written_sz. This behaviour is not desirable for most message based drivers, like queuing or sampling ports, which should rather fail instead of transfering only part of a message. This kind of port semantics must be implemented in user space, e.g., by using p4_kdev_pstat() (see section 1.38.1.12) to query the xfer_size and then by failing before calling p4_kdev_write() (see section 1.38.1.28) if the size is too large. libvm implements exactly this in vm_qport_write() and vm_sport_write().

Returns: exactly the same set of error codes as kdev_read and drv_write_t.

See also: kdev_discard()

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 553

1.38.1.29 p4_kdev_lseek

Synopsis:

__forceinline P4_e_t p4_kdev_lseek(drv_handle_t handle, P4_off_t offset, P4_origin_t origin, P4_off_t *u_filepos_inout, P4_off_t *u_filepos_out)

Parameters: handle IN: the handle of the gate descriptor related to the file position offset IN: file offset (positive or negative or 0) to add to the origin file position origin IN: selection of the origin file position: either 0, the given file position (in u_filepos_inout), or the end of the file. u_filepos_inout INOUT: if origin == P4_SEEK_CUR, this is the origin file position relative to which offset operates. In any case, this is also where the driver writes the new file position. u_filepos_out OUT: redundant second location where the new file position is stored.

Description: Compute a new file position based and store in two locations. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. Based on handle, offset, origin, and *u_filepos_in_out a new file position is computed and stored into *u_file_inout and redundantly into *u_file_out. For KDEV drivers, it is generally not necessary to store the file position in the internal gate descriptor state, i.e., the KDEV framework generally assumes that the file position is entirely handled by the caller of this function. For some file systems, however, this function may also arrange the internal state of the descriptor to correspond to the selected file position, i.e., it is not forbidden for a file system to store the file position redundantly in the internal descriptor state. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor handle is not open (pre-open and being opened or being closed by another thread) P4_E_INVAL if the descriptor is a mount point descriptor P4_E_INVAL if origin is unsupported P4_E_INVAL if offset is negative and the resulting file position is negative. P4_E_OVERFLOW if there was an arithmetic overflow or underflow while computing the new file position P4_E_NOTIMPL if origin == P4_SEEK_END but the file does not supported seeking, P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

554 The PikeOS Kernel API

Other error codes raised by the driver in its .lseek callback.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV User Space API 555

1.38.1.30 p4_kdev_discard

Synopsis:

__forceinline P4_e_t p4_kdev_discard(drv_handle_t handle, P4_off_t discard_sz, const void *u_ctrl_in, void *u_ctrl_update, P4_off_t *u_discard_sz)

Parameters: handle IN: the handle of the gate descriptor to discard data from discard_sz IN: the number of bytes to discard u_ctrl_in IN: the file position at which to discard data u_ctrl_update INOUT: if non-NULL and if the value is larger than the new size of the underlying file, this is reset to the size of the file. u_discard_sz OUT: the actual amount of bytes that have been discarded.

Description: Discard sections of a file, e.g., truncate it to a given size. This is an internal lowlevel function used in the implementation of the PSSW and the libvm. This function may block. The timeout for blocking used by this function depends on the open flag VM_O_NONBLOCK, i.e., it is either P4_TIMEOUT_NULL or P4_TIMEOUT_INFINITE.

Returns: P4_E_OK on success P4_E_INVAL if handle is not a valid handle. P4_E_INVAL if the descriptor handle is not open (pre-open and being opened or being closed by another thread) P4_E_INVAL if the descriptor is a mount point descriptor P4_E_TIMEOUT if the operation needed to block, but cannot finish before the timeout runs out P4_E_PAGEFAULT if a pagefault occured during the attempt to copy data in or out via a pointer parameter. P4_E_NOTIMPL if the driver does not implement discard functionality P4_E_CANCEL if the operation was terminated by the kernel while blocking (for the reasons the kernel defines). This only happens if the function actually blocks. Other error codes raised by the driver in its .discard callback.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

556 The PikeOS Kernel API

1.38.1.31 p4_kdev_discover_prov

Synopsis:

P4_e_t p4_kdev_discover_prov(P4_uint32_t *u_prov_id, char *u_name, P4_size_t name_sz)

Parameters: u_prov_id INOUT: Last processed provider id or 0 if PSSW starts and has just not processed any provider. u_prov_id will be increased to the next valid provider id. u_name OUT: provider name matching to the out value of u_prov_id. name_sz IN: size of char array u_name.

Description: Discovery of providers in the kernel. This is an internal lowlevel function used in the implementation of the PSSW. The PSSW uses this to query the list of providers from the kernel. The PSSW starts by passing a pointer to a provider id of 0. The kernel will then update the provider ID and name to the next ID that is valid and return P4_E_OK. If there is no provider ID greater than or equal to the passed ID, it will return P4_E_INVAL. If a call was successful, the next call should be done with the incremented id passed back in. IDs are not in a contiguous range. This function returns IDs in ascending numeric order. None of the parameters may be NULL or 0. This function requires the P4_AB_KDEV_SETUP ability.

Returns: P4_E_OK on success P4_E_NOABILITY if the caller has no ability to use this functionality. P4_E_INVAL if there is no provider ID greater than or equal to the passed ID. OUT parameters may be invalid.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV Definitions 557

1.39 KDEV Definitions

This section contains the KDEV definitions relevant for the KDEV User Space API.

1.39.1 Structure Definitions

1.39.1.1 struct drv_gate_config_t

Gate configuration information. It is the static configuration of the gate that is directly supported by the system.

Synopsis:

struct drv_gate_config_t { drv_cookie_t cookie; P4_size_t xfer_size; P4_uint32_t queue_length; unsigned perm; };

Structure Element Description: cookie The cookie is an arbitrary identifier of a gate. This is set according to configuration by the PSSW. A driver may use this as a way to identify the gate. This is set by the framework. xfer_size The maximum amount of data that can be transferred in a single read/write. For ports, this is also the size of a message. For packet based drivers, this is the maximum packet size, or, if block_unit is smaller, a multiple of block_unit if bursts of transferring multiple packets is supported. This is initialized to "~0UL" by the framework. The driver may reset this to its configured value (if different, in prepare_gate or init_gate). This must be constant. queue_length Size of the gates underlying object (in units of xfer_size). This is the queue depth for queuing ports. For sampling ports, this is 1. For HW devices with no queue, this may have no meaning, and shall then be 0. For block devices, this should be the size of a buffer, if any, otherwise, it should be 0. For network adapters, this is the number of hardware buffers and xfer_size is the maximum size of each buffer (similar to ports). Note that a device can also define a granularity of the underlying hardware using drv_gate_t::block_unit. This is useful for block devices driving hard disks etc. In that case, xfer_size should be a multiple of block_unit. queue_length is still the size of the underlying queue in units of xfer_size (not block_size). This is static information, not dynamic. It is not the size of a file or device of seekable devices. Such a size is transferred as the ctrl data of pstat() just as the file position is transferred as ctrl data. It is generally dynamic, as the size may change when writing. The queue_length, however, does not change dynamically. Note also that queue_length may not be large enough to store a file position. The size of a file/device etc. is returned by drv_pstat as ctrl information. This is initialized to 1 by the framework. The driver may reset this to its configured value (in prepare_gate or init_gate).

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

558 The PikeOS Kernel API

perm Maximum access mode of the gate. Stored as uint to be sure of the size. The underlying type is vm_file_access_mode_t, but also bits from vm_file_access_right_t might be stored here, e.g. VM_O_LOCAL_ADDR for SAP ports. This is set up by the framework to the configured info in the partitions gate configuration. Drivers may restrict this in a .pstat() callback if they have additional access permission checks. If a driver uses .descend(), they must set this in .pstat(), because the framework will only set this as specified for the root gate.

1.39.1.2 struct drv_status_t

Gate status information. This is used to store current status information about a gate retrieved via vm_stat/vm_fstat as well as vm_qport_stat/pstat/iterate. This means that this structure contains both static information (like block sizes) as well as dynamic information (like available space).

Synopsis: struct drv_status_t { drv_gate_config_t config; P4_uint32_t block_unit; P4_uint32_t read_avail_count; P4_uint32_t write_avail_count; P4_uint32_t waiter_count; drv_cap_type_t ctrl_cap[1]; drv_cap_t meta_cap[1]; drv_cap_type_t cur_ctrl; drv_cap_t cur_meta; unsigned perm; P4_uint32_t cond; P4_uint32_t file_type; P4_uint32_t device; P4_uint32_t inode; P4_uint32_t change_count; P4_uint32_t write_error_count; };

Structure Element Description: config The static configuration record of the gate.

       See also:
       drv_gate_config_t

block_unit Size of each transfer unit. Unit of reporting the queue population in pstat() and for seeking (if that is supported). Devices that support byte-wise seek should have 1 here. All other devices are expected to be block-oriented, each block having a potential size up to block_unit. A driver should set this up according to its way of reporting the queue population or underlying hardware. Ports should set this to config.xfer_size. Block devices should set this to the underlying block size. Packet based drivers (like port drivers) should set this equal to config.xfer_size.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV Definitions 559

     The default, if the driver does not set this up, the framework will set this to 1.

read_avail_count Number of available blocks for reading before running empty. This is only available from pstat(), not from stat(). Devices that never block should set this to "(P4_uint32_t)0". For gates not open for reading, this value is undefined. write_avail_count Number of available blocks for writing before running empty. This is only available from pstat(), not from stat(). Devices that never block should set this to "(P4_uint32_t)0". For gates not open for writing, this value is undefined. waiter_count Number of threads currently waiting for the gate. Note that this number excludes the stat thread, since it is not currently waiting, but processing the gate. ctrl_cap Type of ctrl information attached to transfers. This defines which type of ctrl data the gate can transceive in read(), write(), and discard() requests. This also contains information on which direction the transfer is supported. This array contains all possible (non-DRV_CAP_TYPE_NULL) types the driver supports. If there are less types available than this array, some elements may contain DRV_CAP_TYPE_NULL. When reading this, check the size of the array with p4_countof() (see section 1.2.1). meta_cap Type of meta information attached to transfers. This defines which type of meta data the gate can transceive in read() and write() requests. This also contains information on which direction the transfer is supported. It is a value composed of drv_cap_type_t | vm_file_access_mode_t. Must not be written by a provider. This array contains all possible (non-DRV_CAP_TYPE_NULL) types the driver supports. If there are less types available than this array, some elements may contain DRV_CAP_TYPE_NULL. When reading this, check the size of the array with p4_countof() (see section 1.2.1). cur_ctrl Which ctrl type and direction is currently used. This has the same data format as ctrl_cap. It shows what ctrl type was successfully negotiated with the driver. This is only available from pstat(), not from stat(). cur_meta Which meta type and direction is currently used. This has the same data format as meta_cap. It shows what meta type was successfully negotiated with the driver. This is only available from pstat(), not from stat(). perm Current access permissions (0 if gate is not open). Stored as uint to be sure of the size. The underlying type is vm_file_access_mode_t, but only VM_O_RD and VM_O_WR flags are actually dynamic. The rest is copied from config.perm. This also contains the VM_O_NONBLOCK and VM_O_PRIORITY flags, if set at open(). cond Additional status conditions, see DRV_STATUS_* of the vm_status_cond_t type. file_type Type of file. This defaults to P4_FILE_T_DEVICE but can be reset by the driver is the pstat callback. The actual type of this is P4_file_type_t.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

560 The PikeOS Kernel API

device For volume providers: device ID of the file. An integer id unique in the system to identify the device the file is on. inode For volume providers: inode ID of the file. An integer id unique in the device to identify the file on a device. change_count Number of changes to file. For providers that count this: the number of write operations for this file. write_error_count Number of write errors for this file. For providers that count this: the number of write errors for this file.

1.39.2 Defines

DRV_DIV_UP (X, Y)

      Description:
      Divide and round up to next integer (for unsigned numbers only).

DRV_PAD_SIZE (A, N)

      Description:
      The amount of padding needed given an alignment and a size.

DRV_IO_ENDIAN_BIG

      Description:
      Target endianness: big endian

DRV_IO_ENDIAN_LITTLE

      Description:
      Target endianness: big endian

DRV_BASE_SIG

      Description:
      Base signature to identify a DRV callback structure.
      This is a 24 bit integer used internally to identify a drv_info_t.

      See also:
      drv_info_t

      See also:
      drv_sig_t (see section 1.39.3)

DRV_MEMPORT_COOKIE_SHIFT

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV Definitions 561

     Description:
     For std memory queuing port and sampling port cookies: shift amount.
     This is the bit position in the cookie where the array idx into VMITs Partition/QueuingPortTable/Queu-
     ingPort starts. All lower bits are the partition number, bits from this one are the idx.
     Also for SampingPortTable/SamplingPort

DRV_AUTOGEN_COOKIE_SHIFT

     Description:
     Shift amount for auto-generated cookie numbers.
     If -1ULL is used as cookie number in the VMIT, this define is used to generate a unique cookie number
     using the following formula:
     cookie = part | ((idx + 1) « DRV_AUTOGEN_COOKIE_SHIFT);
     where:

        • part is the PartitionID of the VMIT the cookie has been defined
        • idx is the index in the gate table for the provider in that VMIT
     Cookie numbers below (1 « DRV_AUTOGEN_COOKIE_SHIFT) are preserved for hard- coded numbers.

DRV_COOKIE_RESERVED

     Description:
     Cookie value reserved to KDEV framework.
     The value ~0ULL is reserved to the KDEV framework and must not be assigned as a cookie by KDEV
     drivers. E.g., it is used in the configuraton to trigger automatic cookie enumeration.

DRV_CAP_GET_KIND (TYPE)

     Description:
     Extract the indicator/base type of a type.

DRV_CAP_GET_SIZE (TYPE)

     Description:
     Extract the maximum size of a given types.
     Note that also the lowest two bits are discarded, because in drv_cap_t, they are reserved for storing
     RD/WR bits.

DRV_CAP_GET_TYPE (X)

     Description:
     Extract the type part from a drv_cap_t value

DRV_CAP_GET_ACCESS (X)

     Description:
     Extract the access part from a drv_cap_t value


                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

562 The PikeOS Kernel API

DRV_CAP_TYPE_NULL

  Description:
  No meta data. This is used by qport drivers and many generic drivers.
  Type: drv_cap_type_t

DRV_CAP_TYPE_TIMESTAMP

  Description:
  A time-stamp. This is used by sport drivers in read() to indicate message age.
  Type: drv_cap_type_t

DRV_CAP_TYPE_FPOS

  Description:
  A file position.
  Type: drv_cap_type_t

DRV_CAP_TYPE_SOCKADDR_PAIR

  Description:
  This is the type of one or two vm_sockaddr_storage_t to be transferred.
  The type is compatible with both ways: a pointer to a single sockaddr and a pair of sockaddrs.

  See also:
  vm_sockaddr_t (see section 1.42.3), vm_sockaddr_storage_t (see section 1.42.3).
  If general, if two sockaddrs are transferred, the second has to be in memory just behind the first one.
  The first sockaddr will then be interpreted as the remote address, the second one as the local address.
  If two sockaddrs are passed, the first one be sizeof(drv_sockaddr_storage_t), or better, the second one
  must start at that offset relative to the beginning of the first one, i.e., the driver assumes an array of
  vm_sockaddr_storage_t where the irrelevant tail of the last entry may not be passed.
  The exact size of the passed array is passed as ctrl data when using this type of meta data.
  This value can be used to compare a type returned from DRV_CAP_GET_KIND() (see section 1.39.2).
  Note that for this type, the encoded size is the maximum size, not the exact size, which is encoded in
  the sockaddr struct itself, and the array size is passed as ctrl info.
  Type: drv_cap_type_t

DRV_CAP_TYPE_SOCKADDR_SIZE

  Description:
  The size of a sockaddr_pair.
  Type: drv_cap_type_t

P4_KDEV_TIMEOUT_INHERIT

  Description:


                        c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV Definitions 563

     Special timeout value that can be used in p4_kdev_read() (see section 1.38.1.27) and p4_kdev_write()
     (see section 1.38.1.28) to select the timeout value based on the descriptors VM_O_NONBLOCK flag.
     From the PikeOS kernels point of view, this is an illegal timeout. The value only has a special meaning
     to the functions mentioned above.

DRV_PROV_FIRST_USER_ID

     Description:
     Start of user defined driver IDs.

DRV_PROV_FIRST_DYNAMIC_ID

     Description:
     Start of dynamic provider IDs. This is also the number of providers with fixed ID, which are enumerated
     0..DRV_PROV_FIRST_DYNAMIC_ID-1.

DRV_NUM_PROV

     Description:
     Total maximum number of providers in the KDEV system. Note that due to HLRQ-20963, this must be
     enought for at least 128 external file providers. This also includes volume prefixes. We add the number
     of providers with fixed ID, plus 32 KDEV providers. This will cause DRV_NUM_PROV drv_prov_t
     structures to be statically allocated in the kernel, because the kernels allocator is not initialised when
     this array is needed.

DRV_PROV_ID_EVQ

     Description:
     System eventq provider. This is never accessed by ID but only by name, but DRV_DECLARE_PROV
     requires an ID.

DRV_PROV_ID_SPORT

     Description:
     System sampling port provider

DRV_PROV_ID_QPORT

     Description:
     System queuing port provider

DRV_PROV_ID_SCHEDULE

     Description:
     System scheduler plugin


                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

564 The PikeOS Kernel API

DRV_PROV_ID_TRACE

  Description:
  System trace provider

DRV_PROV_ID_CONSOLE

  Description:
  System console provider

DRV_PROV_ID_MON

  Description:
  Monitor provider

DRV_PROV_ID_PCI_MGR

  Description:
  PCI Manager provider

DRV_PROV_ID_PSP_X86_ACPI

  Description:
  X86 PSP ACPI provider

DRV_PROV_ID_CLOCK

  Description:
  Clock manager provider

DRV_PROV_ID_SYSCALL_TRACE

  Description:
  Provider for tracing system call arguments and exit codes

DRV_PROV_ID_LWT

  Description:
  Light-weight tracing provider

DRV_PROV_ID_KSE

  Description:
  Kernel SE management driver

DRV_POKE_CONSOLE_WRITE

  Description:


                       c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

KDEV Definitions 565

      Function for DRV_PROV_ID_CONSOLE: write a character

DRV_SYSCALL_TRACE_ENTRY

      Description:
      Function for DRV_PROV_ID_SYSCALL_TRACE: trace a system call entry Data arguments:

         • data[0]: current thread UID
         • data[1]: current CPU ID
         • data[2]: system call number (sanitized, range 0 <= num <= P4_SYSCALL_NUM)
         • data[3]: pointer to array of up to 6 syscall arguments of type P4_cpureg_t

DRV_SYSCALL_TRACE_EXIT

      Description:
      Function for DRV_PROV_ID_SYSCALL_TRACE: trace a system call exit Data arguments:

         • data[0]: current thread UID
         • data[1]: current CPU ID
         • data[2]: return code

1.39.3 Data Type Definitions

drv_sig_t Integer for representing API signatures. drv_io_endian_t Endianness on the target. Instead of an enum, this is an int type. The DRV_IO_ENDIAN_* values belong to this. drv_cookie_t An arbitrary identifier used for gates and providers. This is used by drivers to identify their gates. It can be an arbitrary number. Each driver has its own conventions of how to identify its names. Neither PSSW nor framework typically care, except maybe for a few pre-defined providers like "qport" and "sport". This can be used by the driver to recognize the gate, e.g. to map it to a given PCI ID etc. Cookies must never have the value ~(drv_cookie_t)0, i.e., 0xffffffffffffffff. This single value is reserved. drv_cap_type_t Type of meta data managed by the driver on a gate. Meta data is additional data associated with a message, transferred by drv_read() and drv_write() alongside the main buffer. Different types of APIs may expect different types of meta data. This setting is inherent to each gate, and thus part of the drivers capability announcement, so the Configurator and the PSSW are both able to detect mismatches early. A driver may only handle meta data in either read() and write() calls, but only in one of them. This is not reflected here, but is part of the general documentation of the driver. In write(), a driver may chose to either ignore meta data or raise an error. In read() and pstat(), if the driver cannot handle meta data, it shall return the generic zero value of the given type of meta data (e.g. 0 for time-stamps and DEV_ADDRESS_NONE for addresses). Each drv_open() states which kind of meta data is expected from the gate. If there is a mismatch, the open will will reset the meta data type to DRV_CAP_TYPE_NULL to inform the open() caller of the type mismatch.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

566 The PikeOS Kernel API

        Specifying DRV_META_NULL in drv_open() or having a mismatch does not prevent open() from suc-
        ceeding, but it will be expected that read(), write() and pstat() will be passed NULL for the meta data
        pointer, otherwise they will fail.
        The meta type is used to prevent data type mismatches in C, so no bad type casting can happen silently.
        To also have a semantic match when adding new types, do not make the type too general, but encode
        what the data type is used for. As an example, DRV_CAP_TYPE_FPOS shows that were talking not
        only about P4_off_t, but that it is used as a file position.
        The size that is transferred must be a multiple of 4.

drv_cap_t A drv_cap_type_t with additional information about direction. This can be composed by using DRV_CAP_... | VM_O_... (only VM_O_RD, VM_O_WR and VM_O_RD_WR) constants. drv_handle_t Handle of a descriptor in user space. This is allocated by the driver framework per partition. The user space uses this to refer to one of the partition descriptors. Each handle corresponds exactly to one descriptor.

1.39.4 Function Type Definitions

1.39.4.1 drv_int_handler_t

Synopsis:

typedef void drv_int_handler_t(void *priv_data, P4_intid_t int_id)

Description: Interrupt handlers callback. This is a mirror of P4_inthandler_t.

Parameters: priv_data Private data as passed to drv_int_attach(). int_id The number of the interrupt that is being handled.

Returns: nothing

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Processor Speculation Fences 567

1.40 Processor Speculation Fences

This section describes access macros related to the PikeOS API to mitigate processor vulnerabilities due to speculative execution.

1.40.1 Defines

P4_FENCE_INDEX (index, limit) Speculation fence for bounded access to an array element. Description: This macro creates an internal data dependency on the index value to prevent the CPU to speculatively load an array element which is beyond the array limit. If the index exceeds the array limit, the fence takes care to speculate to index zero of the array.

       Note:
       This fence acts as a mitigation for the Spectre v1 "Bounds Check Bypass" processor vulnerability. The
       usage scenario is:
       if (index < limit) {
           index = P4_FENCE_INDEX(index, limit);
           element = array[index];
       }

       Parameters:
               IN index: array index value
               IN limit: array size or upper limit
       Returns:
       The value of index when within the array limit, or zero otherwise.


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

568 The PikeOS Kernel API

1.41 Psp_kdev_decl

1.41.1 Structure Definitions

1.41.1.1 struct P4_romboot_anchor_str

ROM anchor data structure. Purpose of the ROM anchor is to be embedded into binary startup code at the beginning of the ROM image. The ROM anchor points to the ROM header data structure which marks the beginning of structured ROM content. Usually, the PSP binary image and other platform specific headers, signatures or code is placed before the ROM content. The ROM anchor structure shall be placed in the first 4156 bytes of the binary image, i.e. signature shall be placed in the first 4096 bytes of the image. The ROM anchor structure must be aligned to a 4 byte boundary. Usage of a ROM anchor to locate the ROM header is optional, when no ROM anchor is used, the ROM image must start with the ROM header. Except for signature, kernel_build_type, and kernel_build_id, all other entries are patched into the binary when the ROM image is generated. Currently, the romboot header does not distinguish 32bit or 64bit the format is the same. But the embedded parts like the property config nodes may be different for different word widths. They have their own headers to indicate this.

Synopsis:

struct P4_romboot_anchor_str { P4_uint32_t signature; P4_uint32_t romboot_version; P4_size_t payload_offset; P4_size_t kernel_build_type; P4_size_t kernel_build_id; P4_size_t psp_build_id; P4_size_t _ftext_start_rel; P4_size_t _kdev_drv_table_fpos; P4_size_t _kdev_prov_table_fpos; P4_uint32_t _reserved1[2]; };

Structure Element Description: signature Signature, must be P4_ROMBOOT_ANCHOR_SIGNATURE. romboot_version Version number of ROM Boot Anchor. Currently, this is 1, see P4_ROMBOOT_AN- CHOR_DATA. payload_offset Offset to ROM header.

        Note:
        The offset is relative to the start of the ROM image.

kernel_build_type Offset to kernel build type (NUL-terminated string).

        Note:
        The offset is relative to the start of ROM anchor.


                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Psp_kdev_decl 569

kernel_build_id Offset to kernel build ID (NUL-terminated string).

      Note:
      The offset is relative to the start of ROM anchor.

psp_build_id Offset to PSP build ID (NUL-terminated string).

      Note:
      The offset is relative to the start of ROM anchor.

_ftext_start_rel Relative pointer to beginning of text segment. This is mainly for romdump and should not be used from C. _kdev_drv_table_fpos File position of array of KDEV drivers, relative to start of text segment. This is mainly for romdump and should not be used from C, where a symbol for this table is available. _kdev_prov_table_fpos File position of array of predefined KDEV providers, relative to start of text segment. This is mainly for romdump and should not be used from C, where a symbol for this table is available. _reserved1 Reserved, should be set to zero.

Associated Data Type

P4_romboot_anchor_t ROM anchor data structure.

1.41.2 Defines

P4_ROMBOOT_ANCHOR_SIGNATURE_32 ROM anchor signature (ILP32 model) Description: This value indicates the start of the ROM anchor data structure. The ROM anchor signature reads PSP2 in big endian encoding and 2PSP in little endian encoding.

P4_ROMBOOT_ANCHOR_SIGNATURE_64 ROM anchor signature (LP64 model) Description: This value indicates the start of the ROM anchor data structure. The ROM anchor signature reads PSP3 in big endian encoding and 3PSP in little endian encoding.

P4_ROMBOOT_ANCHOR_SIGNATURE

1.41.3 Data Type Definitions

P4_romboot_anchor_t ROM anchor data structure. Purpose of the ROM anchor is to be embedded into binary startup code at the beginning of the ROM image. The ROM anchor points to the ROM header data structure which marks the beginning of structured ROM content. Usually, the PSP binary image and other platform specific headers, signatures or code is placed before the ROM content.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

570 The PikeOS Kernel API

  The ROM anchor structure shall be placed in the first 4156 bytes of the binary image, i.e. signature
  shall be placed in the first 4096 bytes of the image. The ROM anchor structure must be aligned to a 4
  byte boundary.
  Usage of a ROM anchor to locate the ROM header is optional, when no ROM anchor is used, the ROM
  image must start with the ROM header.
  Except for signature, kernel_build_type, and kernel_build_id, all other entries are patched into the binary
  when the ROM image is generated.
  Currently, the romboot header does not distinguish 32bit or 64bit the format is the same. But the
  embedded parts like the property config nodes may be different for different word widths. They have
  their own headers to indicate this.


                        c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

File_system 571

1.42 File_system

1.42.1 Structure Definitions

1.42.1.1 struct _vm_sockaddr_reserved_vector_t

Vector of _vm_sockaddr_reserved_t

Synopsis:

struct _vm_sockaddr_reserved_vector_t { _vm_sockaddr_reserved_t * data; unsigned long size; };

Structure Element Description: data array of size entries; NULL if empty. size number of entries in data array

1.42.1.2 struct vm_sockaddr_vector_t

Vector of vm_sockaddr_t

Synopsis:

struct vm_sockaddr_vector_t { vm_sockaddr_t * data; unsigned long size; };

Structure Element Description: data array of size entries; NULL if empty. size number of entries in data array

1.42.1.3 struct vm_sockaddr_ip4_vector_t

Vector of vm_sockaddr_ip4_t

Synopsis:

struct vm_sockaddr_ip4_vector_t { vm_sockaddr_ip4_t * data; unsigned long size; };

Structure Element Description: data array of size entries; NULL if empty. size number of entries in data array

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

572 The PikeOS Kernel API

1.42.1.4 struct vm_sockaddr_ip6_vector_t

Vector of vm_sockaddr_ip6_t

Synopsis: struct vm_sockaddr_ip6_vector_t { vm_sockaddr_ip6_t * data; unsigned long size; };

Structure Element Description: data array of size entries; NULL if empty. size number of entries in data array

1.42.1.5 struct vm_sockaddr_storage_vector_t

Vector of vm_sockaddr_storage_t

Synopsis: struct vm_sockaddr_storage_vector_t { vm_sockaddr_storage_t * data; unsigned long size; };

Structure Element Description: data array of size entries; NULL if empty. size number of entries in data array

1.42.1.6 struct _vm_sockaddr_reserved

Generic place holder for an arbitrary sockaddr structure. This structure reserves enough space to be used for any type of sockaddr supported by PikeOS. The structure also enforces alignment to 64 bits so that any entries are aligned as such. This is an internal auxiliary type. See vm_sockaddr_storage.

Synopsis: struct _vm_sockaddr_reserved { unsigned long long reserved[4]; };

Structure Element Description: reserved Currently, 32 bytes are reserved. We support IPv4 and IPv6, which both fit into this amount of storage.

Associated Data Type

_vm_sockaddr_reserved_t

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

File_system 573

1.42.1.7 struct vm_sockaddr

Generic sockaddr type that works for all address types. This is the most generic type defining only the raw packet format. This type is often used to transfer two addresses, a sockaddr_pair, in which case the second address will be just after the first one. To indicate that there is a second socket address, the length of the first packet will be set to +1 of the original length, making the length field odd, since it is otherwise aligned.

Synopsis: struct vm_sockaddr { unsigned char length; unsigned char family; char _pad1[6]; };

Structure Element Description: length The length of the address in bytes. The lowest bit is used to indicate that a second sockaddr follows, if this is used in is a SOCKADDR_PAIR. family The family type of the sockaddr structure. This is of type vm_sa_family_t, but stored as u8 to ensure the correct padding. _pad1

Associated Data Type

vm_sockaddr_t

1.42.1.8 struct vm_sockaddr_ip4

IPv4 address of a port/gate/socket, i.e. for UDP/IPv4 or TCP/IPv4. Initially for A653 Part 2 SAPs, but supported by device drivers natively. This is modeled after the POSIX sockaddr_in type and the A653 type SAP_ADDRESS_TYPE. Like POSIX, the size is not stored inside the struct but is passed as a parameter. This structure must share all initial entries in the same order and type with vm_sockaddr_t. Since A653 has a length inside the structure, we use the BSD4.4 definition of this structure that has a sin_len entry at the beginning not mentioned in POSIX. This will also save some parameters in the vm function API for SAP ports, since the length does not need to be passed by parameter.

Synopsis: struct vm_sockaddr_ip4 { unsigned char length; unsigned char family; unsigned short port; unsigned address; };

Structure Element Description:

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

574 The PikeOS Kernel API

length The length of the address in bytes. The lowest bit is used to indicate that a second sockaddr follows, if this is used in is a SOCKADDR_PAIR. family The family type of the sockaddr structure. This is of type vm_sa_family_t, but stored as u8 to ensure the correct padding. When using this variant of a sockaddr, this must be equal to VM_AF_INET4. port The addressed UDP port in network byte order (big endian). address The IPv4 address in network byte order (big endian).

Associated Data Type

vm_sockaddr_ip4_t

1.42.1.9 struct vm_sockaddr_ip6

IPv6 address of a port/gate/socket, i.e. for UDP/IPv6 or TCP/IPv6. This is an extension of the usual A653 types to support the IPv6 protocol. It is fully compatible with POSIX data structure layout. This structure must share all initial entries in the same order and type with vm_sockaddr_t. When using this variant of a sockaddr, family must be equal to VM_AF_INET6.

Synopsis:

struct vm_sockaddr_ip6 { unsigned char length; unsigned char family; unsigned short port; char _pad2[4]; unsigned long long _align_to_64_bit; unsigned address[4]; };

Structure Element Description: length The length of the address in bytes. The lowest bit is used to indicate that a second sockaddr follows, if this is used in is a SOCKADDR_PAIR. family The family type of the sockaddr structure. This is of type vm_sa_family_t, but stored as u8 to ensure the correct padding. port The addressed UDP port in network byte order (big endian). _pad2 _align_to_64_bit Dummy entry to enforce alignment of address to 64 bits. Always keep this 0. Fixed value 0. address The IPv6 address in network byte order (big endian), stored as four integers. This entry is aligned to 64 bits.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

File_system 575

Associated Data Type

vm_sockaddr_ip6_t

1.42.1.10 struct vm_sockaddr_storage

Generic place holder for an arbitrary sockaddr structure. This structure reserves enough space to be used for any type of sockaddr supported by PikeOS. The structure also enforces alignment to 64 bits so that any entries are aligned as such. This is also a union of the typical sockaddrs that may be in used so that access is available with out casting pointers.

Synopsis: struct vm_sockaddr_storage { _vm_sockaddr_reserved_t _reserved[1]; vm_sockaddr_t header[1]; vm_sockaddr_ip4_t ip4[1]; vm_sockaddr_ip6_t ip6[1]; union vm_sockaddr_storage::@7 u; };

Structure Element Description: _reserved header ip4 ip6 u

Associated Data Type

vm_sockaddr_storage_t

1.42.2 Defines

VM_IOC_MAX_PARAM_SIZE

         Description:
         Maximum length, in bytes, of user parameter passed to and received from the vm_ioctl() service call.

VM_IOC_PARAM_OUT (n)

         Description:
         Declare n bytes for output

         Note:


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

576 The PikeOS Kernel API

  The maximum size of a parameter is VM_IOC_MAX_PARAM_SIZE (currently 0x7f).

  Parameters:
          n IN: output byte count

VM_IOC_PARAM_IN (n)

  Description:
  Declare n bytes for input

  Note:
  The maximum size of a parameter is VM_IOC_MAX_PARAM_SIZE (currently 0x7f).

  Parameters:
          n IN: output byte count

VM_IOC_GET_PARAM_OUT (cmd)

  Description:
  Get command-specific output parameter size.

  Parameters:
      cmd IN: output parameter size.

VM_IOC_GET_PARAM_IN (cmd)

  Description:
  Get command-specific input parameter size.

  Parameters:
      cmd IN: output parameter size.

VM_IOC_CMD (cmd_id)

  Description:
  Command ID is in upper bits

  Parameters:
      cmd_id IN: Command ID is in upper bits

VM_IOC_GET_CMD (cmd)

  Description:
  Command ID is in upper bits

  Parameters:
      cmd IN: Command ID is in upper bits

VM_AF_NULL 0

                       c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

File_system 577

VM_AF_INET4 2

VM_AF_INET6 28

vm_sa_family_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

vm_sa_family_MAX 28

     Description:
     Maximum value of the enum type

VM_STATUS_DROP 1

     Description:
     Since the last read operation, there was packet drop. This is maintained and set by the underlying driver

vm_status_cond_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

vm_status_cond_MAX 1

     Description:
     Maximum value of the enum type

VM_TEST_INIT 0

VM_TEST_SINGLE 1

VM_TEST_START_SINGLE 2

VM_TEST_START_CONTINUOUS 3

VM_TEST_STOP 4

vm_test_mode_ALL Iteration macro This can be used to iterate all values of the corresponding enum type: define macro EACH(x), then use the _ALL macro to invoke EACH once for each enum value of the type.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

578 The PikeOS Kernel API

vm_test_mode_MAX 4

   Description:
   Maximum value of the enum type

VM_IOC (cmd_id)

   Description:
   Build an ioctl command cmd with no input and no output parameter.

   Parameters:
       cmd_id IN: IO command ID

VM_IOC_IN (cmd_id, type)

   Description:
   Build an ioctl command cmd_id with an input parameter of type and no additional output parameter.

   Note:
   The maximum size of a parameter is VM_IOC_MAX_PARAM_SIZE (currently 0x7f).

   Parameters:
       cmd_id IN: Command ID
       type IN: Input parameter type

VM_IOC_OUT (cmd_id, type)

   Description:
   Build an ioctl command cmd_id with an output parameter of type and no additional input parameter.

   Note:
   The maximum size of a parameter is VM_IOC_MAX_PARAM_SIZE (currently 0x7f).

   Parameters:
       cmd_id IN: Command ID
       type IN: Input parameter type

VM_IOC_INOUT (cmd_id, itype, otype)

   Description:
   Build an ioctl command cmd_id with an output parameter of otype and an input parameter of itype.

   Note:
   The maximum size of a parameter is VM_IOC_MAX_PARAM_SIZE (currently 0x7f).

   Parameters:
       cmd_id IN: Command ID
       itype IN: Input parameter type
       otype IN: Output parameter type


                        c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

File_system 579

1.42.3 Data Type Definitions

vm_sa_family_t vm_status_cond_t Type for reporting additional conditions on a gate/port/file. This type is used in the result values of the pstat/fstat/stat calls on file and ports to report additional special conditions on the port. vm_test_mode_t Do not use this type, use vm_test_mode instead. _vm_sockaddr_reserved_t typedef for struct _vm_sockaddr_reserved vm_sockaddr_t typedef for struct vm_sockaddr vm_sockaddr_ip4_t typedef for struct vm_sockaddr_ip4 vm_sockaddr_ip6_t typedef for struct vm_sockaddr_ip6 vm_sockaddr_storage_t typedef for struct vm_sockaddr_storage

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

580 The PikeOS Kernel API

1.42.4 Functions

1.42.4.1 p4_perm_ok

Synopsis:

__forceinline P4_bool_t p4_perm_ok(vm_file_access_mode_t request, vm_file_access_mode_t condition)

Parameters: request IN: requested permission condition IN: given permission

Description: Permission check. Whether permissions should be granted, based on a permission mask and a request mask. The order of params is such that the requested value comes first, similar to a == operator used for checking, where youd write x == 5. So here, youll write perm_ok(x, VM_O_RD). (That is, this tries to avoid a Yoda condition.) This function is for open style permission checks, i.e., for checking whether requesting a given set of permissions for future operations is OK. This function is not directly suitable for checking concrete single bit permissions when an access is done, because the VM_O_FORCE_MASK checks will typically interfere (the perm check will fail if e.g. the VM_O_MOUNT flag is set and the caller just wants to see whether VM_O_RD is allowed). E.g., checking whether VM_O_RD is allowed in a concrete read operation should be done using (perm AND VM_RD) != 0 instead of using this function to avoid false rejections. Note that some concrete operation checks (like map) may need multiple bits to be checked. For this, the bits of interest can be masked from both request and condition. E.g., to check for only VM_O_RD_WR | VM_O_EXEC | VM_O_MAP permissions, you could use the following code. P4_uint32_t mask = VM_O_RD_WR | VM_O_EXEC | VM_O_MAP; if (!p4_perm_ok(mapflags & mask, drv_gd_get_perm(gd) & mask)) { ...P4_E_PERM... }

.This approach also works for the afforementioned single bit checks.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

2 Kernel Parameters

Kernel (and PSP) parameters are defined in the XML file describing the ROM image. Please note that the UK_TPS_PANIC_MODE tag that was used in older version of PikeOS to control the kernel behavior in case of a Time Partition Double Overrun has been removed. Instead a health monitor event of type P4_HM_TYPE_P4_E with value P4_E_TIMEOUT is raised in this case, which can be configured to be ignored (see PikeOS User Manual, Health Monitoring, for additional information on the configuration). The configurable kernel parameters are described in table section 8, page 583:

Path Type Default p4/kernel/ticker_mode uint32 0 System ticker mode implementation. Setting to 0 chooses the PSP default implementation. Setting to 1 chooses the periodic ticker mode implementation. Setting to 2 chooses the dynamic ticker mode implemen- tation.

p4/kernel/ns_per_tick uint32 10000000 System tick timer period in nanoseconds. Used only in periodic ticker mode and defines the granularity of timeouts handled by the kernel. The time partition switching period is also derived from this clock.

p4/kernel/ns_per_tp_tick uint32 10000000 Minimum duration of a time partition window in nanoseconds. In periodic ticker mode, this value must be a multiple of psp/p4/ns_per_tick

p4/kernel/ns_tp_watchdog uint32 0 Time partition switch watchdog period in nanoseconds used for the detection of time partition switch over- runs. The default value of 0 lets the kernel use the system tick duration set by ns_per_tp_tick to play safe on architectures without fine granular timing.

p4/kernel/tps_strong_sync uint32 0 Strong time partition switching synchronization at major time frame. The parameter controls the use of strong time partition synchronization at every major time frame occurrence. When enabled (set to 1), CPUs will syn- chronize time partition switching at every major time frame using a strong busy-wait barrier semantics. Such strong behavior is needed when using the alarm_timepart() KDEV callbacks and VM_SCF_SYNC synchro- nization flags. The strong behavior is also needed to enable the behavior of P4_TIMEPART_SWITCH_MA- JOR in the p4_timepart_switch() API. When disabled (set to 0, default), PikeOS will strongly synchronize time partition switching only during a schema switch. Major time frames are implicitly synchronized by rely- ing on synchronized timing across CPUs. In both synchronization modes, time partition switching does not drift.

p4/kernel/respart0_pages uint32 0

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

582 Kernel Parameters

Path Type Default Number of pages in the page pool for resource partition 0. Setting this value will make the given number of pages available as initial kernel memory for resource partition 0. Note: the allocator allocates blocks of size thrinfo_size. The number of allocated pages may be up to (thrinfo_size/page_size - 1) pages higher than respart0_pages. Note: if this value is set to zero, kernel memory for resource partition 0 will be only restricted by the physical memory region configuration for partition 0.

p4/kernel/num_timepart uint32 255 Number of time partitions, at least one must exist. Currently the maximum allowed value is 255.

p4/kernel/num_respart uint32 255 Number of resource partitions, at least one must exist. Currently the maximum allowed value is 255.

p4/kernel/num_task uint32 1023 Maximum number of tasks in the system in the range 2 .. 1023. Note that most architecture impose a limit on the maximum number of tasks in the system.

p4/kernel/num_thread uint32 4095 Maximum number of threads per task in the range 1 .. 4095.

p4/kernel/num_prio uint32 256 Maximum number of scheduling priority levels. Allowed values: 32, 64, 128, 256.

p4/kernel/num_cpu uint32 0 Number of configurable processors. This value is used to limit the number of processors to the given limit. It must not exceed the real number of available processors. Setting to 0 allows the kernel to use all detected processors.

p4/kernel/tptable_max_windows uint32 256 Number of windows in the time partition switcher table. Sum of all windows in all schemes.

p4/kernel/num_mem_region uint32 1 Set the maximum number of memory regions per partition. The maximum allowed value is P4_NUM_MEM- REG (2048).

p4/kernel/thrinfo_size uint32 0 Size of threads system/kernel stack: it must be page-aligned; the minimum and maximum configurable size is architecture dependent. Setting to 0 (default) selects the minimum architecture-dependent configurable stack size.

p4/kernel/boot_message uint32 2 Let kernel, PSPs, and KDEV display messages on startup. Setting to 0 disables any boot message. Setting to 1 enables basic boot messages from kernel and PSP (version, build IDs, and enabled features). Setting to 2 or higher enables statistics on the current configuration and memory usage of the system. Note that kernel, PSPs, and KDEV should not print at runtime to prevent possible timing interferences via the console.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.
                                                                                                            583

Path Type Default p4/kernel/log_level uint32 3 Setting this parameter to values greater than 0 controls whether the kernel will print on the console Health- Monitoring module-level errors. Note that this parameter controls the verbosity of the PSSWs console output (including Health-Monitoring console reporting for non-module level actions). Please refer to PSSW reference manual for the list of verbosity levels.

p4/trace/mem_size uint32 0 Size of the tracer-memory-pool, up to 4 GB. Setting this value to zero disables tracer support at all. Only multiples of P4_PAGESIZE are accepted. Note: to utilize this feature, a kernel with tracer support is needed.

p4/trace/mem_phys uint32 0xffffffff Physical start address of the trace-memory-pool. The memory must not be used and the start address must be a multiple of P4_PAGESIZE. Set to 0xffffffff to allocate the next best chunk. The trace-memory-pool must start in the first 4 GB of the physical address space.

p4/trace/post_mortem uint32 0 Enable post mortem debugging. Setting to 0 disables post mortem tracing at all and zeros the tracer- memory-pool. Setting to 1 enables post mortem tracing and tries to validate a previous tracer-memory-pool.

p4/trace/control_size uint32 0 Size of the trace control page, must be a multiple of P4_PAGESIZE. Mustnt be set to zero if tracing shall be enabled.

p4/trace/default_buffer_size uint32 0 Default size of a single trace-buffer, multiple of P4_PAGESIZE. Setting this value to zero disables tracing until the trace server sets a valid default buffer size.

p4/trace/kernel_buffer_size uint32 0 Size of the trace-buffer for the kernel. If zero, tracing of the kernel is disabled.

p4/trace/start_kernel_tracing uint32 0 Control whether kernel tracing will be enabled at boot time or later by the trace server.

p4/kernel/test_flags uint32 0 Activate testing-only settings. The parameter should be set to a non-default value only by test systems that require dedicated Kernel support to trigger a defined testing behavior. Setting to 1 allows the installation of sigma0-level HM error handlers for the PSSW/Sigma0 partition. These errors normally directly result in a module-level action. The behavior for unhandled errors is not modified (therefore, unhandled Sigma0 errors will anyway result in a module-level action.

                                    Table 8: Configurable Kernel Properties.

PSPs are also configured using the property file system, refer to the according platform manual for the exact definition of the PSP parameters.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

A The ROM Images

A PikeOS system is started from one or more ROM images. In the traditional one-image approach, the image contains all major parts of a PikeOS system:

• Platform Support Package (PSP) linked with the kernel, typically placed at the beginning of the image,

• a property tree,

• the root task, and

• other files.

All items except the last are mandatory to bring up the system. In the new multiple-images approach, which is designed to be suitable for modular configuration, there is one core image, the so called Global ROM Image, containing:

• OS binaries (BSP-specific Kernel and PSSW)

• ROM Function Supplier (defined in project4.rbx)

• Global property file system (defined in project4.rbx)

• Partition Function Supplier reference table (defined in project4.rbx)

• Global configuration table (vmit.mod)

      - System Extensions
      - Partition Table
      - Shared Memory
      - Multiple Partition HM tables
      - Module HM table
      - Module Schedule Table

• Module level driver configuration (XML files for each driver validated against XSD)

The application binaries as well as information with partition-local impact, are kept in separate per-partition images, the so called Application ROM Images. The Application ROM Images contains:

• Application binary (app)

• Partition local property file system (defined in project4.rbx)

• Partition local file system (defined in project4.rbx)

• Application usage configuration table (vmit.mod)


                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Building the ROM Image 585

        - Segmentation of provided memory regions
        - Allocation of file descriptors
        - Allocation of local ports
        - Allocation of discoverable driver gates
        - Communication channels between local ports and remote ports
        - Processes
        - Partition HM table
        - Adjustments to the assigned time partition windows

• Client definable configuration table for drivers assigned to the partition (BIN file)

A.1 Building the ROM Image

The bootable binary ROM images are built by the configconv tool. It reads XML image specification files to identify as well as to locate the different software components and assembles them together to form the ROM image output files.

A.1.1 RBX Description

The XML file parsed by configconv is called ROM boot XML or short RBX file. Typically, it will be generated and modified by the PikeOS development tools, but can be edited manually with a text or XML editor as well. The following points should be noted when creating a RBX file:

• The XML document prologue must contain the following XML declaration:

• Within the XML file, only characters from the US-ASCII character set are allowed. This also applies to characters used in comment sections.

    NOTE: Characters with accent or dieresis are not part of the US-ASCII character set.

• All XML-element and attribute names are case-sensitive.

• All configuration data is stored in XML-attribute nodes. Text nodes are not used in the XML file.

• The order in which attributes appear is important, however a special parsing rule applies.

A.1.1.1 Basic Data Types

Integer - An integer data type is noted as decimal or hexadecimal value. Hexadecimal values must start with a leading 0x or 0X, all other digits being represented by the characters {0...9, a...f, A...F}.

Boolean - The boolean data type has two values, true or false. The evaluation is not case-sensitive.

String - Stings may contain any characters from the character set.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

586 The ROM Images

Resource - A resource data type is a string containing a path to a file in the local file system. The file names may contain relative or absolute paths, and the expansion of environment variables is supported. Environment variables are preceded by a dollar sign and an opening bracket, the case-sensitive name of the variable and a closing bracket, like $(ENV_VAR).

Other more specific data types are used where necessary.

A.1.1.2 The RBX Root Element

The following code example shows the first level of an RBX file:

<properties ...> <files ...> <memregions ...> <partroms ...> <psp ...> <sigma0 ...>

The RBX root element consists of multiple instances of the following elements. These elements can appear in any order in the files. The attribute partition specifies whether this is the global ROM image (value = 0) or a partition ROM image (value ≥ 0). The first five elements are container elements which can appear multiple times and may be empty:

properties - elements are the root of the property file system. It contains of nested named directories <prop_dir> with properties of different types.

files - elements consist of sub-elements which instruct configconv to include a file into the ROM image.

memregions - elements consist of  sub-elements that are used to configure per- partition memory regions with fixed physical address and size. A memregion is independent from the MemoryRequirements that are specified in the VMIT, and can be used, for example, to allow a kernel level driver to allocate partition specific and module-global memory.

partroms - elements consist of  sub-elements that are used to include local ROM images separately from the global ROM image with fixed physical address and size. For each partition, exactly one entry maybe specified in the global ROM image. It is not possible to define partition ROM regions recursively in the local partition ROM images. Therein, the section must be missing, because the section is a global only list.

The last two elements are needed to boot from a ROM image. The elements are not containers, so they must not be empty.

psp - The element refers to a PSP to include into the ROM image.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Building the ROM Image 587

sigma0 - The element points to the root task to be started by the kernel.

The exact format of the elements is described in the following sections.

A.1.1.3 Files

The sections refer to binary files to be included into the final image:

<romimage ...> ...

There can be any number of entries in a section. Files are included in the order of their appearance, files included from scripts are preferred. The following attributes are defined for a entry:

name Type / Constraints Description name string This mandatory attribute specifies the internal name of the file, which must be unique in the image and must not exceed 16 characters.

data string This mandatory attribute specifies the name of the file in the local file system. Absolute and relative filenames can be used and environment variables are expanded.

A.1.1.4 Memregions

The section consists of elements, which define physical memory regions and will be used for manual memory partitioning. For detailed information about defining memory regions, refer to A.2.

A.1.1.5 Partroms

The section consists of elements, which define partition local ROM images and must be part of the global ROM image.

A.1.1.6 The Root Task

The entry refers to the root task, i.e., the first task that is started at boot time, which is generally the PSSW.

<romimage ...>

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

588 The ROM Images

Only one entry is allowed in a ROM image. The following attributes are defined for a entry:

name Type / Constraints Description file string This mandatory attribute specifies the file the mapping shall be taken from. The name of the file refers to an internal file name and the file must exist in the ROM image.

copy string, must be "true" or "false" This optional attribute specifies that the segment shall be mapped directly from the ROM image ("false") instead of providing a copy ("true").

A.1.1.7 PSP

The entry refers to the PSP to include into the ROM image. An image including a PSP is called an embedded ROM, an image without a PSP is a standalone ROM. There can be only one PSP in an image, and the PSP to placed at the beginning of the image.

<romimage ...>

The following attributes are defined for the entry:

name Type / Constraints Description data string This mandatory attribute specifies the name of the file in the local file system. Absolute and relative filenames can be used and environment variables are expanded.

A.1.1.8 Properties

The container refers to a property tree. The tree consist of <prop_dir> elements containing typed properties. The property tree can be accessed via the property file system.

<romimage ...> <prop_dir name="branch"> <prop_dir name="subbranch1"> <prop_uint32 name="my_tag" data="12345"/> ... </prop_dir> <prop_dir name="subbranch2"> <prop_uint32 name="my_other_tag" data="6789"/> <prop_dir name="subbranch3"> <prop_uint32 name="sub_sub_tag" data="10"/> ... </prop_dir> </prop_dir> </prop_dir>

                                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Building the ROM Image 589

There can be any number of <prop_dir> entries in a container. A <prop_dir> has the following attribute:

name Type / Constraints Description name string This mandatory attribute specifies the name of the node. Entries for direc- tories must have unique names and must be expanded to the full tree. This means that the two directories subbranch1 and subbranch2 from above are siblings and each property directory is a unique node in the tree.

A node itself consists of any number of sub <prop_dir> entries and properties. A example with all tags is given below:

<prop_dir name="somebranch"> <prop_bool name="my_bool" data="true"/> <prop_uint32 name="my_uint32" data="12345"/> <prop_uint64 name="my_uint64" data="123457890"/> <prop_string name="my_string" data="Some string"/> <prop_addr name="my_addr" data="0x1234"/> <prop_size name="my_size" data="0x1234"/> <prop_bin name="my_binary_hex" data="0x12, 0x13"/> <prop_bin name="my_binary_dec" data="1, 2"/> <prop_link name="my_linked" data="somebranch/my_bool"/> <prop_interrupt name="my_int" data="5"/> <prop_device name="my_dev" data="7"/> <prop_memmap name="my_map"> </prop_memmap> <prop_portmap name="my_port"> </prop_portmap> <prop_dir/>

All properties have a common name attribute:

name Type / Constraints Description name string This mandatory attribute specifies the name of the property. The name must be unique in the directory.

In addition to the name and depending on the type, a property has further sub-elements, attributes, and meanings:

prop_bool - Boolean data type

 name               Type / Constraints               Description


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

590 The ROM Images

  data              string, must be "true" or "false"   This mandatory attribute specifies the value of the property.

prop_uint32 - 32-bit integer data type

  name              Type / Constraints                  Description
  data              integer                             This mandatory attribute specifies the value of the property.

prop_uint64 - 64-bit integer data type

  name              Type / Constraints                  Description
  data              integer                             This mandatory attribute specifies the value of the property.

prop_string - String data type

  name              Type / Constraints                  Description
  data              string                              This mandatory attribute specifies the value of the property.

prop_addr - Address data type

  name              Type / Constraints                  Description
  data              integer                             This mandatory attribute specifies the value of the property.

prop_size - Size data type

  name              Type / Constraints                  Description
  data              integer                             This mandatory attribute specifies the value of the property.

prop_bin - Binary data type

  name              Type / Constraints                  Description
  data              character array                     This mandatory attribute specifies the value of the property.

prop_ipv4 - IPv4 address data type

  name              Type / Constraints                  Description
  data              character array                     This mandatory attribute specifies the value of the property.

prop_mac - MAC address data type

  name              Type / Constraints                  Description
  data              character array                     This mandatory attribute specifies the value of the property.

prop_file - Data file reference type

  name              Type / Constraints                  Description
  data              character array                     This mandatory attribute specifies the value of the property.


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Physical Memory Partitioning 591

   The file reference type is similar to prop_bin, but payload data is read from the file whose URL is provided
   in the data attribute.

prop_link - Link

  name               Type / Constraints                 Description
  data               string                             This mandatory attribute specifies the value of the property.


   Links point to other attributes in the property tree. The link automatically adapts to the type of the pointed
   to element.

prop_interrupt - Interrupt identifier data type

  name               Type / Constraints                 Description
  data               integer                            This mandatory attribute specifies the value of the property.

prop_device - Kernel level device driver identifier data type

  name               Type / Constraints                 Description
  data               integer                            This mandatory attribute specifies the value of the property.

prop_memmap - Memory mapping data type Each <prop_memmap> entry has one sub-element entry. The following attributes are defined for this entry:

  name               Type / Constraints                 Description
  poffset            integer                            This mandatory attribute specifies an offset to the physical base address.

  psize              integer                            This mandatory attribute specifies the size of the mapping.

  perm               vm_memory_access_mode_t             This optional attribute specifies which access permissions the memory
                                                        mapping should have (RD, WR, EXEC). The default is RD and WR. The
                                                        bit VM_MEM_ACCESS_EXCL is not allowed here, and the behavior of set-
                                                        ting the bit is undefined.

  cache              vm_memory_cache_mode_t             This optional attribute specifies which cache attributes the memory map-
                                                        ping should have (WT, CB, INHIBIT). The default is INHIBIT.

prop_portmap - I/O port mapping data type Each <prop_portmap> entry has one sub-element entry. The following attributes are defined for this entry:

  name               Type / Constraints                 Description
  paddr              integer                            This mandatory attribute specifies the base address of the port mapping.

  psize              integer                            This mandatory attribute specifies the size of the mapping.

A.2 Physical Memory Partitioning

In PikeOS, the physical memory can be separated in multiple physical memory regions (in short memory re- gions in this section) that are used to serve per-partition allocations (including kernel resources e.g., thread/task descriptors). Please refer to the PikeOS User Manual for more information about the memory region concept.

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

592 The ROM Images

In order to support strict partitioning even for configuration data, the physical memory partitioning configuration can also be (physically) partitioned among per-partition configuration files. The following sections present the information needed to configure memory regions within a ROM Image.

A.2.1 Partition ROM Regions

Partition local ROM images may be included separately from the global ROM image which PikeOS uses for booting. To make the kernel and the PSSW aware of these ROM images, the memory areas where these ROMs reside must be defined in the global RBX file. The following is a definition of the format that is used.

<xsd:element name="partroms"> xsd:complexType xsd:sequence <xsd:element minOccurs="0" maxOccurs="unbounded" ref="partrom"/> </xsd:sequence> </xsd:complexType> </xsd:element>

<xsd:element name="partrom"> xsd:complexType <xsd:attribute name="part" type="ri:stdNum" use="required"/> <xsd:attribute name="paddr" type="ri:stdNum" use="required"/> <xsd:attribute name="size" type="ri:stdNum" use="required"/> </xsd:complexType> </xsd:element>

For each partition, exactly one entry may be specified. If there are duplicate entries, the kernel will panic. It is not possible to define partition ROM regions recursively in the partition ROM images: there, the section must be missing. ri:stdNum is an integer type also allowing hexadecimal notation (prefixed with 0x).

A.2.2 Memory Regions

The list of memory regions associated to a memory pool is included in the ROM Image of a partition. The element may contain a list of memory pool configurations.

<xsd:element name="memregions"> xsd:complexType xsd:sequence <xsd:element minOccurs="0" maxOccurs="unbounded" ref="memregion"/> </xsd:sequence> </xsd:complexType> </xsd:element>

<xsd:element name="memregion"> xsd:complexType <xsd:attribute name="id" type="ri:stdNum" use="required"/>

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Physical Memory Partitioning 593

    <xsd:attribute name="paddr" type="ri:stdNum" use="required"/>
    <xsd:attribute name="size" type="ri:stdNum" use="required"/>
    <xsd:attribute name="type" type="ri:P4_mem_type"/>
</xsd:complexType>

</xsd:element>

The same memory region id can be specified multiple times to add more memory to the same memory region to create a non-contiguous region. Enumeration of the memory regions is per partition:

• memory region IDs specified in the global romimage implicitly refer to partition 0. Region(s) with ID 0 in the global romimage contribute to the global region.

• memory region IDs specified in a per-partition romimage refer to that partition.

• a memory requirement in the VMIT can specify a partition ID alongside with a memory region ID to uniquely identify the memory region ID coming either from the global or a per-partition romimage.

• neither the kernel nor the PSSW impose any restrictions as to which partition uses which other partitions memory regions: Restrictions must be part of the offline budget checking.

The macros P4_MEMREG* are used at API level to build a unique memory region ID from a resource partition ID and the ID specified in the configuration (i.e., for kernel and PSSW, a memory region ID is internally represented by the couple (partition_id, configuration_id)). The attribute type is optional, and may be given the value P4_MEM_TYPE_UNPRIVILEGED to indicate that a memory region will be used to serve memory for unprivileged software. The default state is to serve memory for privileged software. MCE/ECC double fault impacting a memory region marked as unprivileged can result in a partition level health monitoring event, while those happening on a memory region marked as privileged will always result in a module level health monitoring event. PSPs and KDEV drivers can use the kernel service p4_kernel_get_mem_type() to retrieve the type of the physical memory region associated with a physical address. As detailed in PikeOS User Manual, the memory regions with id = 0 in the global romimage RBX contribute to a global memory regions that is used by PikeOS at boot-time and at run-time to serve requests from resource partition 0 if p4/kernel/respart0_pages is different from 0.

A.2.3 Interactions with PSP-defined Memory Regions

As detailed in the PSP Development Guide, PSPs may define different memory regions depending on specific board requirements: for example, not all memory on the board may be usable as RAM, some memory may be reserved for IO devices, and some memory is reserved for the PSP and Kernel memory. The PSP-defined system memory (by p4_kernel_assign_mem() and p4_kernel_assign_tmp()) define a superset of the physical memory in the system. At early boot time, both PSP and kernel can use this PSP-defined system memory for memory allocations to setup internal kernel data structures independent of the system configuration. However, during later kernel initialization, the memory region allocator becomes available and the physical memory blocks described by the memory regions are allocated from the PSP-defined system memory. Therefore, memory regions are a strict subset of the PSP-defined system memory. By this, the kernel also ensures that memory regions do not overlap and that all memory regions are fully accessible to the kernel. Overlapping or references to inaccessible memory will cause a panic at boot time.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

594 The ROM Images

Note that any remaining system memory not covered by memory regions becomes inaccessible in the system configuration and will not be used by PikeOS. Also, memory regions can not use any temporary RAM used during boot by the PSP (see p4_kernel_assign_tmp()). This memory is implicitly marked as privileged memory of partition 0.

A.2.4 Considerations on num_respart and num_mem_region

Systems that requires a physical memory layout independently from the number of resource partition and memory regions possibly provided by these partitions (e.g., IMA systems) should always configure the max- imum foreseen number of resource partitions and memory regions in the psp/kernel/num_respart and psp/kernel/num_mem_region properties. This ensures that the same amount of memory is reserved for the Kernel management of the memory regions independently from the actual system configuration.

A.2.5 Memregions in Partition Memory Requirements

Partitions can be configured to use specific memory regions to satisfy different Memory Requirements. The following listing shows an example how a memory region is assigned to a memory pool inside the VMIT:

<MemoryRequirement MemRegionID="" MemRegionPartition=""

    Name="_NET_MALLOC_"
    Type="VM_MEM_TYPE_RAM"
    Size="0x30000"
    PhysicalAddress="-1"
    Alignment="-1"
    Contiguous="true"
    CacheMode="VM_MEM_CACHE_CB"
    AccessMode="VM_MEM_ACCESS_RD VM_MEM_ACCESS_WR VM_MEM_ACCESS_EXEC"
    IsPool="true"/>

The MemRegionID and the MemRegionPartition allow the connection of a partition memory requirement to a memory region with the specified ID. If neither MemRegionID nor MemRegionPartition are specified, the default (0,0), addressing a single, global memory region will be used. If MemRegionID is specified, but MemRegionPartition is not, then the MemRegionPartition will take the value of the partition ID of the VMIT where the memory requirement is found. MemRegionID/MemRegionPartition must agree with the maximum values specified in num_mem_region and num_respart kernel properties. Invalid MemRegionID/MemRegionPartition configurations produce a panic at boot time.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Physical Memory Partitioning 595

A.2.5.1 Shared Memory Objects

A MemoryRequirement can use an ID from the same or from a different partition, i.e., there is no restriction. This is to allow configuration of groups of partitions that share the same memory region. Health monitoring exceptions deriving from unsuccessful memory allocation from the memory region specified by MemRegionID and MemRegionPartition will cause global HM events.

A.2.5.2 Partition Cold / Warm Start

Memory requirements are allocated from memory pools by the PSSW only. On partition reboot the same memory will be mapped again in the partition.

A.2.6 Defining Memory Regions

Memory regions separate the physical memory on a system. On platforms with an unknown layout it could be problematic to find suitable memory chunks for the allocation of memory regions. A quick way to identify suitable memory areas for the configuration of memory regions on the PSPs with unknown physical memory layout is to boot PikeOS with p4/kernel/boot_message property set to a value greater than 4. Relevant information will appear in the kernel boot messages. The boot messages should contain a section like the following one:

... MM: assigning free memory 0x0000000040246000 -- 0x0000000040265fff MM: assigning tmp memory 0x0000000040007000 -- 0x000000004007ffff ... MM: assigning free memory 0x0000000040266000 -- 0x0000000047ffffff ...

This is the system memory that the PSP defines. Memory declared as free memory is immediately available for allocations, while memory declared as tmp memory is temporarily used at boot time and later reclaimed by the kernel. The largest of those, i.e.

MM: assigning free memory 0x0000000040266000 -- 0x0000000047ffffff

in the above example, is the free RAM which can be used to define memory regions. The start address might be a little variable depending on how large the PSP/kernel/global ROM image are, so it is good practice to allow some buffer at the beginning and probably also at the end. For each partition ROM image, there may be a definition in the global RBX file. These are defined by the section. Each partition ROM may in turn have a list (but no list, which is a global list only). Enumeration of the memory regions is per partition, i.e., in a memory requirement in the VMIT, a partition number must be specified alongside the memory region ID to refer to a memory region. Neither the kernel nor the PSSW impose any restrictions such as which partition uses which other partitions memory regions: restrictions must be part of the offline requirement checking. If the memory region definition of the global RBX file is empty, then this global region will be used as the only region, which means the system will fall back to a global memory configuration.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

596 The ROM Images

A.2.6.1 Modular Configuration Considerations

For each partition, the modular configuration requires an own integration project. This can be cloned and stripped down manually, as the per-partition romimage configurations should only contain those parts related to the partition local information. Specifically, the kernel-psp binaries information should not be included in the partition local RBX. The following example snippet adds the application binary and the partition local VMIT. It also adds another memory region for testing purpose. NOTE the partition ID (1 in this case), specified as attribute of romimage.

Since only a default memory region for the partition is provided (memregion 0), the VMIT for the corresponding partition with ID 1 can avoid specifying the MemRegionID and MemRegionPartition, and will therefore use the memory region 0.

[...] <Partition ... >

                  <MemoryRequirement AccessMode="VM_MEM_ACCESS_RD
                   VM_MEM_ACCESS_WR VM_MEM_ACCESS_EXEC" Alignment="0x00001000"
                   CacheMode="VM_MEM_CACHE_CB" Contiguous="false" IsPool="false"
                   Name="_KMEM_" PhysicalAddress="-1"


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Physical Memory Partitioning 597

             Size="0x00080000" Type="VM_MEM_TYPE_KMEM"/>
        </MemoryRequirementTable>
</PartitionTable>

Note that the partition ID (1 in this case) is specified as attribute of Configuration to mark this as a VMIT for partition 1.

A.2.6.2 Partition ROM Image Definitions

Each partition may have its own ROM image in addition to the global one. The global one is marked with partition="0" at the romimage element. Other partition romimages carry their partition number here. Parti- tion romimages must be plain ROM image files without any kernel/PSP added to them. Each possible ROM image must be predeclared in the global ROM image with physical addressed set to where the partition ROM image will be found. The presence of a partition ROM image is still optional, i.e., it is possible to pre-declare a partition ROM image, but not include any image at the given physical address. The actual presence if a ROM image is determined at runtime by a valid ROM header signature each partrom entry is checked for a valid ROM image. If the signature is valid, but other errors are detected, like a CRC checksum mismatch or an unexpected partition value, then the kernel will panic during initialization. The following is an example where three partition ROM images are predeclared in the global ROM image.

...

This reserves three areas at 0x200000, 0x300000, and 0x400000, with a size of 0x100000 each to store the partition local ROM images.

A.2.6.3 Memory Region Configuration

This section shows an example configuration for the global ROM project4.rbx that defines two memregions for the global (partition 0) partition:

...

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

598 The ROM Images

   <memregion id="1" paddr="0x00900000" size="0x00100000"/>
...

This configuration defines a large memregion with the ID 0 at physical address 0x00800000. Within partition 0, the memregion 0 is the replacement for the global memory region the kernel uses for boot time allocation, and also for refilling partition memory pools if nothing else is specified. If this region is not present, the kernel wont boot. The second memregion in this example may be used to fulfill additional memory requirements by a separated segment. NOTE: When the memregions feature is used, only minimal checks on the consistency of the defined memory regions are performed. If non-overlapping but incorrect memory regions are defined, difficult to debug errors may arise.

A.3 Building the ROM Image(s)

To build runnable ROM images, the global integration project needs to be initiated with an empty VMIT, only containing the basic fields.

To get the application ROM images, make boot has to be run in the "application integration projects". Afterwards, romdump can be used to verify that the partition number is set, and that there is no PSP inside, i.e. its type is standalone ROM. The global ROM image is built by running the same command inside the global integration project. Here romdump should state that the image type is embedded ROM, because there is a kernel and PSP in it. For hardware targets where multiple boot images can be uploaded, it should now be possible to upload the packed images and boot. When using dedicated memory regions for storing the ROM images. Note that the application

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 599

ROM images have to be loaded to the locations specified in the partrom section of the global ROM image (see A.2.6).

A.3.1 Merging ROM Images (e.g. for Qemu)

Some targets, Qemu for example, do not support multiple images. For this case, there is a new target make multi in the main integration project, which combines all ROM images into a single file. The tool pikeos-multi-romimage reads the project4.rbx file, and builds a single ELF file according to the specifi- cation there. To use make multi correctly, the application ROM images have to be copied or linked into the target sub directory of the global integration project, e.g.:

  part-01.boot -> ../../hello-part1.int/hello-world.boot

Afterwards, make multi called in the global integration project should provide an output like follows:

/opt/pikeos-D5.0/cdk/x86/amd64/bin/x86_amd64-ld -b binary -r hello-world.boot -o boot/part-00.elf /opt/pikeos-D5.0/cdk/x86/amd64/bin/x86_amd64-ld -b binary -r target/part-01.boot -o boot/part-01.elf /opt/pikeos-D5.0/cdk/x86/amd64/bin/x86_amd64-ld -b binary -r target/part-02.boot -o boot/part-02.elf echo ENTRY(__entry) __entry = ABSOLUTE(0x100000) ; SECTIONS .part00 0x100000 : part-00.elf() .part01 0x200000 : part-01.elf() .part02 0x300000 : part-02.elf(*) >boot/multi.ld cd boot && /opt/pikeos-D5.0/cdk/x86/amd64/bin/x86_amd64-ld -Tmulti.ld -s -o multi.elf

Note that this example contains another partition, so this packs three files: the Global ROM image plus the two Application ROM images. The output file is boot/multi.elf.

A.4 Binary Configuration Data and Converter Tool

In system extensions and external file providers, the current version of PikeOS provides the property file system (propfs) to a means of configuring drivers. Access to this file system is available via a dedicated file provider in the PikeOS system software (PSSW). The original data is stored in a dedicated XML format to define the configuration items for a driver and the configconv tool converts the XML to a generic binary form, which is then readable by the propfsdriver. Access to the file system is done via key names (strings) that are structured recursively like paths and that index the property file system. In PikeOS 3.4, the property file system could only store basic data types like integer and strings. Drivers would have to use the relatively slow access via the propfs provider using recursive path-like string comparisons to access each simple piece of configuration data.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

600 The ROM Images

PikeOS 4.0 introduced a new generic binary configuration format that drivers can use to store configuration information. The binary data is defined at configuration time in XML files and compiled to its binary form by a dedicated converter pikeos-configconv. The structure of both, XML and binary format, is specified by each driver using XML schemata (XSD). To embed the new binary configuration into the PikeOS runtime environment, the property file system (propfs) is extended to contain binary configuration nodes that store a full configuration block for a driver. The driver simply needs to access propfs only once and can read the whole binary configuration at once. All access control mechanisms to the configuration are inherited from the property file system.

A.4.1 Configuration Converter (pikeos-configconv)

For converting XML configuration data into the binary format, a configuration converter is used. This tool is a generic XML to binary converter that reads a validating XSD description as a specification configuration data structure. The XSD specification format is used to defined how binary configuration files look like. It was chosen so that a standard XSD validator can validate the XML configuration files. pikeos-configconv accepts a subset of XSD, and also has some extensions to tweak binary format generation. This way, the same XSD file can be used for validation with standard tools and for converting an XML file into binary format. The subset of XSD that pikeos-configconv accepts is based on useful templates that define C data types like structs and unions, which are the C source code representation of the binary file. The following sections will list which XSD structures can be used and how they map to C and binary format. The configuration converter also defines some extensions, which are all embedded into the element that XSD provides exactly for this purpose.

A.4.1.1 Conversion of XML to Binary Configuration Files

To access binary configuration from a module, pikeos-configconv can generate C source code that defines the enum, struct, and union types that represent how the binary configuration looks like at byte level. I.e., a module that wants to use binary configuration will first write and XSD file describing the configuration items, and will then convert this XSD into a C source code header file with the definitions to access to the binary format from C. In this source code mode of operation, the configuration convert reads as input file the XSD, and writes C source code files. When binary configuration is defined, typically at integration time, the configuration converter is used in a different mode of operation: the binary mode. Here, it will read an XML file containing the configuration, which will reference the XSD file via the top-level element namespace. The configuration converter will then convert the XML file to binary format according to the XSD specification. The C source files generated in the source code mode will correspond exactly to the generated binary format. The source code mode generates header files that work for any supported architecture, i.e., for little or big endian machines and for ILP32 and LP64 size models. Occasionally, if the distinction is necessary, e.g., for padding bytes, the converter will insert conditions based in SIZEOF_POINTER, which the compile provides during compilation. The binary mode of operation depends on both endianness and pointer size it cannot produce a generic format that can be expected to be directly accessible from C.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 601

A.4.1.2 Architecture Support

Naturally, with this degree of native support for direct C access, the binary format is highly dependent on the target architecture. To generate a binary format for all architectures supported by PikeOS, the configuration converter supports two data type models:

• ILP32 for32-bit architectures, where int, long and void* are 32 bit types and

• LP64 for 64-bit architectures, where long and void* are 64 bit types.

Furthermore, two possible Endianness types are supported:

• little endian (low byte first) and

• big endian (high byte first).

Mode switches on the command line select the exact binary format at conversion time. Due to different sizes and thus different possible amounts of necessary padding, the generated header files are different depending on the type model as well, but they do not depend on the Endianness. Only one header is generated, with the distinctions between the 32-bit and 64-bit models, reflected by using the pre-defined header constant SIZEOF_POINTER. PikeOS will use either ILP32 or LP64 models on any platform, so checking the pointer size is sufficient to distinguish the models. To ensure that the tool and the compiler use exactly the same byte-wise layer, all padding bytes are explicitly declared and the compiler warnings may be switched of to check that there is no additional padding (-Wpadded). For more robustness, static assertions (P4_STATIC_ASSERT) in the header files can be used to check that the compiler has the same notion of byte layout, size and padding as the configuration converter.

A.4.2 XML Input File Formats

The XSD format is used as a basis for defining how binary format looks like. The same XSD file can be used for validation. To allow a strict validation, more XSD items are allowed than what the configuration converter will read. XSD to source code translation is common for the Java language, but not so much for C. Since C is more lowlevel, some extensions are used by the configuration converter that control C code generation. Also, some data types that should be special in C are just handled as strings by the validator, so again, for these cases, some extensions exist. The following sections will introduce in detail what is supported. XSD provides a way to embed extensions into the annotation/appinfo element, and that is how pikeos-configconv adds its extensions to the XSD format. The namespace used for XSD is http//www.w3.org/2001/XMLSchema:, just like the standard XSD Schema. In the following, elements from this namespace will have no name prefix. The extensions defined inside the annotation/appinfo that pikeos-configconv accepts are defined in the namespace http://www.sysgo.com/xsd/p4/confxsd-4.5-ext.xsd. In the following, elements form this extension namespace will have the name prefix cx. The configuration converter defines an own XSD for the XMLSchema namespace that specifies the structure that is accepted. It is a restriction of the WWW XMLSchema. Both the WWW XMLSchema XSD and the PikeOS XMLSchema XSD should validate the XSD files used with pikeos-configconv.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

602 The ROM Images

A.4.2.1 XML Namespaces

Namespaces are supported and strictly distinguished in the XSD and XML files. The only supported model is elementFormDefault="qualified". Attributes must be unqualified. All XSD files must declare this at the schema element so that the XSD validator and pikeos-configconv have the same view on the namespaces. In the following, namespaces will not be shown for simplicity reasons. In actual files, they will appear in the standard way as XML and XSD use them.

A.4.2.2 Supported XSD Subset

To simplify the code of the configuration converter, and also to be able to clearly specify how C types ore generated, only a sub-set of XSD is supported for configuration files. It was attempted to find a subset that is simple but still useful. To enhance the usefulness, some extensions to XSD have been added (via the appinfo element). This section describes what is supported. In order to stress the usefulness of the selected XSD items that are supported, this section also shows to which kind of C structure the XSD declarations are converted. The configuration converter appends _t to all names in the XSD when generating corresponding C source files. All attribute and element names are used as is. This means that if reserved words are used, the generated C files may not compile. There is no mechanism to avoid this in order to keep pikeos-configconv as simple as possible. The corresponding attribute or element will have to be renamed in XSD for the C source code to compile. The configuration converter supports to generate the following types in C:

  • enum

  • struct

  • struct with a single union inside

The conversion also supports alias types on XSD level, so that additional restrictions like string lengths can be added for validation, or the byte size in C may be changed, but such alias type names never occur in the generated C source code. Generally, pikeos-configconv will convert annotation/documentation into Doxygen comments when generating C code. For this reason, annotation/documentation is only accepted if Doxygen is generated for the given item. Commenting the XSD itself should be done using XML comments (with ).

A.4.2.2.1 XSD File Structure

The XSD files supported by the configuration converter always have a more rigid structure than XSD in general. SYNOPSIS

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 603

<annotation ...> ... </annotation>
<import ...>      ... </import>
<simpleType ...> ... </simpleType>
<group ... />     ... </group>
<complexType ...> ... </complexType>
<element ...>     ... </element>

Which namespace prefix is used for the namespace http//www.w3.org/2001/XMLSchema: does not matter: it may be empty or any other prefix the user sees fit. The configuration converter supports any prefix. 8-bit characters are currently not supported anywhere in the XSD file or in the binary input file, hence the encoding is declared as us-ascii. The elementFormDefault must be qualified. No attributeFormDefault attribute is allowed. The order of elements inside the top-level is fixed in contrast to general XSD, the order is as shown above: import, simpleType, group, complexType, element. Each sub-element may occur multiple times, or not at all. In the following, each of these sub-elements has its own explanatory section(s). The schema element can have an appinfo annotation to set the default reloc override for all complexTypes. See section A.4.2.7, page 622 for an explanation and an example.

A.4.2.2.2 Import Declaration

There are multiple ways to refer to other XSD files from within an XSD file. The configuration converter only supports , which means that each referenced XSD file will have to have its own namespace and namespace prefix. MINIMUM SYNOPSIS

MAXIMUM SYNOPSIS

Only the namespace attribute is supported by the configuration converter. The file corresponding with that names- pace is found by using a catalog file which maps namespaces to files. The PikeOS configurator automatically gen- erates a file catalog.xml in each project directory that contains all XSD files from the PikeOS pool and from the custom pool. This is the basis for finding files for the configuration converter. Typically, if a namespace is imported, there will be an additional declaration of a namespace prefix at the element.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

604 The ROM Images

The configuration converter accepts a single appinfo extension for the import directive: external, which is used to mark all types imported from that sub-namespace as external. This effects how the C code is generated: only for non-external types, C source code is generated. For producing binary format, however, the XSD import can be freely used. Configconv simply expects you to #include the definitions to access the binary from a different header file generated by another call to configconv where the given namespace is not external. Example

  <import namespace="http://www.sysgo.com/xsd/p4/type-4.5.xsd" />

<element name="foo" type="ty:stdUnsignedInt"/>

This example shows how the standard extension types are included, which will be explained later, see section A.4.2.4, page 608. This example also shows how the extensions to the XSD that the configuration converter supports are included by simply adding another namespace prefix referring to namespace http//www.sysgo.com/xsd/p4/confxsd-4.5- ext.xsd:. This enables the use of the various appinfo extensions.

A.4.2.2.3 Schema Element Declarations

Schema element declarations are used to validate an XML against its XSD. The configuration converter uses elements to mark inside the binary header which element the binary data contains. No C type declarations are generated for XSD schema element declarations. MINIMUM SYNOPSIS

MAXIMUM SYNOPSIS

DOXYGEN TEXT
                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 605

Example

For such a declaration, the converter will generate a #define with the element CRC checksum for the type of the element. See section A.4.3.1, page 643 to learn how this checksum is generated exactly. For example:

#define vmitConfiguration_Configuration_CRC 0x1c4340b2

Annotation Overview

annotation/documentation Documentation string that will be added as a Doxygen comment to C output before the #define. annotation/appinfo/ignore If present, the element will be ignored by pikeos- configconv, i.e, no C code will be generated, and the ele- ment cannot be used in configuration files.

A.4.2.2.4 Types

The XSD for the configuration data definition must be structured in such a way that each configuration type in C has either a simpleType, a complexType, or a group definition in XSD. This reflects the structure in the generated C source code where each type declaration is at top-level. With this structure, element and attribute definitions need to be specified with a type="..." attribute and cannot contain a nested type declaration. I.e., no inline type declarations are supported, i.e., no simpleType or complexType sub-elements are supported in element or attribute elements: each type must be declared as a child to schema. In contrast to XSD, the order of declaration groups in a schema is fixed: all simpleType declarations must come first, then all group, then all complexType declarations, and at the end, schema element declarations may appear. Unlike C, but just like XSD, the dependency order of types in the XSD does not need to be strictly top-down (this would not even work because groups will refer to embedded complexTypes), but the order is free.

A.4.2.3 Base Types

The configuration converter only supports a limited set of base types. A subset of the predefined types of XSD is directly supported. The following table shows which types are supported and how they are retranslated to C.

  XML Type               C Type                               Bits in ILP32      Bits in LP64   Notation
  string                 char *                                          32                64   any string
  ID                     char *                                          32                64   any string
  byte                   signed char                                      8                 8   decimal
  unsignedByte           unsigned char                                    8                 8   decimal
  short                  short                                           16                16   decimal
  unsignedShort          unsigned short                                  16                16   decimal


                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

606 The ROM Images

   int                   int                                               32             32    decimal
   unsignedInt           unsigned int                                      32             32    decimal
   long                  long long                                         64             64    decimal
   unsignedLong          unsigned long long                                64             64    decimal
   boolean               unsigned int                                      32             32    false|true
   float                 float                                             32             32    XSD float
   double                double                                            64             64    XSD float
   anyURI                struct {                                         128            256    file URI
                             void *data;
                             unsigned long size;
                             unsigned long alloc;
                             unsigned int crc32;
                         }
   IDREF                 Type *                                             32            64    ptrto struct

NOTE: In an attempt to generate a stable format and to unify with enums, booleans are now stored as 32 bit integers (either 0 or 1). The size can manually be changed using an alias type and the appinfo/sizeof/type. string and anyURI are translated as a pointer to an out-of-line binary data blob containing the actual data by default. This can be changed by using an alias type and the inline appinfo annotation. The pointer and size used in string and anyURI have either 32-bit or 64-bit size, depending on data model (ILP32 or LP64) of the binary. In C, they are pointer and unsigned long types. The anyURI structure always contains a CRC32 checksum and, on 64-bit, padding to the next word boundary. Boolean values are translated to unsigned int, just like all enum types are, in order to be sure of the exact size in the binary representation. More generic XSD types like integer are not available in pikeos-configconv, because information about binary size is required for binary and C code generation.

A.4.2.3.1 Floats

Note that the float types may not be very useful in kernel drivers, because floating point arithmetic is generally switched off in the PikeOS kernel for simplicity reasons. Nevertheless, the values are parsed like XSD floats, including the special values INF, -INF, and NaN. The digit strings before and after the decimal . are parsed as unsigned 64-bit integers, so any digit strings that cannot be represented in 64-bit integers will be rejected, even if they are valid floating point string values in XSD. For example, 0.18446744073709551615 is accepted, while 0.18446744073709551616 will be rejected. Note that these strings are too long for the double format to represent them, so just drop a digit that will anyway not be representable.

A.4.2.3.2 ID / IDREF

The ID type behaves exactly like string, with the side effect of assigning a name to the element where an attribute of this type is found at. The IDREF type is the counterpart of ID. It will find the reference defined by ID and establish a pointer in the binary to the structure that had that ID. By default, the pointer type is implemented as void* in C, so the user must have some information about identifying the type. The target type can be made more specific by using the

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 607

target/type appinfo in an alias type. This way, the possible target type is restricted (choice types are allowed), and in C, the proper C pointer type is used instead of void*. For an example, see section A.4.2.9, page 636.

A.4.2.3.3 anyURI

The anyURI type is a way to embed files into the binary output file. The file URL that is given will be opened and the contents of that file will be stored in the output binary. The representation in C is like a vector: with a pointer to the file data plus a size slot for the exact input byte size, plus an alloc slot which gives the number of bytes reserved in the binary file. alloc is the original size of the data rounded up according to the alignment. If the file is empty, the data pointer will be NULL (i.e., will be the relative pointer with value 0). The anyURI type is also linked to the element, as will be explained in the section on structs. In short, the element can be used to recursively embed configuration data from a different namespace into the configuration. The configurator is then recursively invoked and the data from the nested binary generation is stored in the same location as the anyURI at the same struct. In that case, the anyURI must have the value "internal:any" to indicate the link. See section A.4.2.7.2, page 632 for details. The anyURI type always computes a CRC32 of the inserted file inserted as an extra precaution against accidental corruption.

A.4.2.3.4 Extended Types

Additional to the above set of standard XSD types, some extended types are supported. These all begin with a double underbar, and they should not be used in type annotation that the XSD validator reads, because this causes the XSD file to be rejected. Instead, an alias type can be used to define how the syntax of these extended types is in XML, using base type and restrictions, and pikeos-configconv can use the builtin special type via the appinfo/type/name declaration. See section A.4.2.5.4, page 615 for an example.

XML Base Types          C Types                                    ILP32     LP64       Notation
__unsignedWord          unsigned long                                 32       64       decimal,hex
__word                  long                                          32       64       decimal,hex
__rec_id                char *                                        32       64       any string
__ipv4                  union {                                       32       32       4 .-separated decnums:
                           unsigned net;                                                A.B.C.D
                           unsigned char byte[4];                                       each 0..255
                        }
__mac                   union {                                        64       64      6 :-separated hexnums:
                           unsigned long long net;                                      A:B:C:D:E:F
                           unsigned char byte[6];                                       each 00..ff
                        }

The __mac type only uses the first 6 bytes, but it is aligned and padded to 64 bits. The next section shows how some useful alias declarations are already provided out of the box via a PikeOS standard types XSD file. The __rec_id type is very similar to the ID type, but it is an extension to add recursive, directory like structures: the ID used for a node with a __rec_id attribute is the "/"-separated concatenation of all strings in __rec_id attributes from root node to that node, i.e., this type recursively creates a "/"-separated path as an ID instead of

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

608 The ROM Images

using exactly the ID as given. References to __rec_id can also be established with IDREF. See section A.4.2.9, page 636 for examples on how to use this type.

A.4.2.4 Standard Extended Types

To make the special types of pikeos-configconv directly available in XSD user definitions, a standard set of types in the namespace http://www.sysgo.com/xsd/p4/type-4.5.xsd is defined. To use the definitions, an import declaration is used at the beginning of the XSD schema:

The namespace will typically be given a prefix at the root schema element. We will assume the prefix ty in the following. The type.xsd type has two purposes: to define alias types that wrap the special types with double underbar in a way that they can directly be used in XSD, and by the XSD validator. The syntax is defined using pattern rules in these alias types so that an XSD validator will check the syntax. The second purpose of the type.xsd is to introduce hexadecimal integers, which are very frequent in system configuration. XSD integers do not support this by default, but only decimal syntax can be used. Internally, all the predefined integer types of pikeos-configconv can parse both decimal and hexadecimal integers, but due to the restriction of XSD, hexadecimal syntax is rejected by the validator. To overcome this limitation, alias types are used. The following is a list of standard types defined in the type.xsd file.

                    Type Name                      Binary Storage         Notation
                    ty:stdUnsignedByte             unsignedByte           dec, hex
                    ty:stdUnsignedShort            unsignedShort          dec, hex
                    ty:stdUnsignedInt              unsignedInt            dec, hex
                    ty:stdUnsignedLong             unsignedLong           dec, hex
                    ty:stdWord                     __word                 dec, hex
                    ty:stdUnsignedWord             __unsignedWord         dec, hex
                    ty:stdIPv4                     __ipv4                 dotted quad: A.B.C.D
                    ty:stdMAC                      __mac                  colon hex: A:B:C:D:E:F
                    ty:stdBool64                   unsignedLong           false|true

Except for stdBool64, all of these types use string type as a base type in XSD plus a set of pattern restrictions to defined the XML syntax. The stdBool64 type uses boolean as a base type, and sets the C type/size/alignment using the appinfo/sizeof/type described above. The stdUnsigned* family of types accepts an additional value of -1 to represent a value with all-one bits values (i.e., 0xff, 0xffff, 0xffffffff or 0xffffffffffffffff, depending on bit width of the type). This is a special value that often comes in handy, and interpreting a negative number even for unsigneds follows C language tradition. Still, the types in configconv only accept this single negative value, unlike e.g. strtoul (or C), which accepts any negative value.

A.4.2.5 User-Defined Simple Types

Simple type declarations follow the normal XSD declaration using the element simpleType. The following variants of enums are supported:

                               c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 609

• contiguously enumerated enums (0,1,2,...)

• power-of-two enumerated enums, or bitfield enums (1,2,4,8,...)

• alias types

The following sections show how enumerations are recognized and treated.

A.4.2.5.1 Contiguous Enumeration (enum) Types

MINIMUM SYNOPSIS

MAXIMUM SYNOPSIS

DOXYGEN TEXT DOXYGEN TEXT
                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

610 The ROM Images

                DOXYGEN TEXT
            </documentation>
            <appinfo>
                <cx:numeric value="NUMERIC_ENUM_VALUE_OVERRIDE"/>
            </appinfo>
        </annotation>
    </enumeration>
    <!-- more <enumeration> elements -->
</restriction>

Example

The number of enum values must be at least 1 to be recognized by the converter as an enum declaration. The maximum number of enum values is currently 231 . Additionally, it is constrained by the amount of available main memory on the host running the converter tool. Such a declaration in XSD will be translated to C in the following way:

typedef enum { Foo = 0, Bar = 1, Hinz = 2, Kunz = 3, } myEnum_t;

The maximum enum value is currently 231 1 due to constraints inherited from the C programming language, in order to avoid confusion about signedness. This shows that apart from adding _t to the type name to conform to popular C naming conventions for typedefs, no identifier is modified. All names in XSD must be valid C identifiers. In structs, enums will not appear as their typedef type, but will, by default, appear as a 32-bit unsigned int (type unsigned in C, type unsignedInt in XSD). Using integer types instead of the declared enum type ensures that the converter and the compiler agree on the exact byte size of the type. NOTE: Enum values are stored in 32 bits in the binary format by default. The enum size can now be set up manually by using the appinfo/sizeof/type annotation. NOTE: The restriction/base type is ignored by configconv, and only present for the specification format to be compatible with XSD. The XSD validator uses this attribute, so additional validation can be specified by the base type.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 611

Values of such types will translate to the given integer value. For example, suppose the following is found in XML, with element1:attr1 having type myEnum.

Then in binary format, the corresponding unsigned int field will contain the value 2. Annotation Overview

annotation/documentation Doxygen documentation text prepended to the enum type in C. annotation/appinfo/docgroup Doxygen docgroup condition the C type is en- closed in. annotation/appinfo/ignore If this is found, no C code is generated for this type, elements and attributes of this type will be ignored, i.e., no C code nor binary output will be generated for them, and the corresponding nodes are ignored in configuration files, but configuration files will not be rejected if these are present, al- lowing additional annotations that are not visible in binary format. annotation/appinfo/sizeof/type Override the C type to represent the enum in structs. By default, unsignedInt is used, i.e., the enum is 4 bytes in size. This can be changed to any other integer type, including signed types. Both the C type name, the size for ILP32 and for LP64, and the alignment will be taken. It is possi- ble also to use another enum type to use the same C type/size/alignment. annotation/appinfo/inline/size Enforces inline storage for strings. Usually, strings are stored as pointers to the actual string data. This annotation changes that to use an inline ar- ray of the given size. The string value is then re- stricted to that size. The string will be 0-padded to the defined size, so that it will always have the same storage size as specified by this annotation. restriction/enumeration/annotation/documentation Doxygen documentation to be prepended to the enum value. restriction/enumeration/annotation/appinfo/numeric/value Override of the numeric value of the enum name. This value must be >= the default value, so that it is guaranteed that the enum values are in ascend- ing numeric order. This is explained more in the next section. restriction/appinfo/addEnum This adds another definition of an enum name and value in C. This is completely ignored otherwise by configconv, i.e., this name cannot be used in configuration files. restriction/appinfo/addEnum/doc If present with value false, the additional value will be removed from Doxygen documentation.

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

612 The ROM Images

restriction/appinfo/addEnum/documentation Doxygen documentation to be prepended to the additional enum value.

A.4.2.5.2 Explicit Enumeration (enum) Values

Sometimes it is desirable to set explicit values on enumerations. The converter supports this with restrictions. First, the values must be strictly ascending, no equal values are tolerated. Secondly, values of bit field enumerations must be powers of two. Moreover, any enum value must be in the range 0..0x7fffffff. To declare a numeric value, extensions via the annotation or appinfo mechanism of XSD are used:

The values after the explicitly specified one continue the sequence normally, i.e., the above will be translated as follows:

typedef enum { Meier = 0, Franck = 1, Mueller = 8, Schmidt = 9, Schneider = 10, } myEnum2_t;

A.4.2.5.3 Bit Field Enumeration (enum) Types

In low-level device or driver programming, bit fields are commonly used. As a convenience, the configuration converter has direct support for these. A declaration in XSD uses the list element wrapped around an enum type as shown above to mark a bit field. I.e., XSD, a bit field enum declaration looks as follows. The data type is very similar to normal enums. To indicate the bitfield, an additional level of elements is inserted in XSD: list/simpleType. MINIMUM SYNOPSIS

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 613

MAXIMUM SYNOPSIS

DOXYGEN TEXT DOXYGEN TEXT DOXYGEN TEXT
                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

614 The ROM Images

            </enumeration>
            <!-- more <enumeration> elements -->
        </restriction>
    </simpleType>
</list>

Example

The maximum number of enum values for a bit field enumeration is currently 31 so that the value stays within the range 1 and 0x40000000. This is due to a restriction inherited from C. Such a declaration is handled very similarly to the contiguous enum types, except that the values of the enum will be powers of two. I.e., the enum above will be translated as:

typedef enum { READ = 1, WRITE = 2, EXECUTE = 4, SPECIAL = 8, } myEnum2_t;

In structs, fields of such a type will use a 32-bit unsigned integer type instead of using the enumeration directly. NOTE: Bitfield values are stored in 32 bits in the binary format by default. The enum size can now be set up manually by using the appinfo/sizeof/type annotation. Values of this type will be parsed as XSD prescribes for XML: As a space separated list of values of the declared type. They will be composed into a bit field by the configuration converter when generating the binary format. Imagine the following snippet in XML:

The corresponding entry will contain the value 1|4, i.e. 5. Annotation Overview

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 615

annotation/documentation Just like for consecutive enums de- annotation/appinfo/docgroup scribed in the previous section, see annotation/appinfo/ignore Page 611 annotation/appinfo/sizeof/type list/simpleType/restriction/enumeration/annotation/documentation restriction/appinfo/addEnum restriction/appinfo/addEnum/doc restriction/appinfo/addEnum/documentation restriction/enumeration/annotation/appinfo/numeric/value Like for consecutive enums, but with the additional constraint that the value must be a power of 2.

A.4.2.5.4 Alias Simple Types

XSD provides a means to define a new type based on another type, to add additional restrictions on it. This is supported by pikeos-configconv, too. Most of the restrictions and modifications made to the alias type based on the base type are only relevant for the XSD validator, while only a few settings will influence the type in pikeos- configconv. MINIMUM SYNOPSIS

This simple alias type is like a typedef in C, defining an alias type without any restrictions or changes wrt. the base type. MAXIMUM SYNOPSIS

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

616 The ROM Images

    <!-- more <pattern> elements -->
</restriction>

Example: Resizing a Simple Type in C

<xs:simpleType name="bool64"> xs:annotation xs:appinfo <cx:sizeof type="xs:unsignedLong" /> </xs:appinfo> </xs:annotation> <xs:restriction base="xs:boolean"/> </xs:simpleType>

This type declares an alias so that bool64 behaves basically like boolean, i.e., at XML level, it accepts the same values true and false. The additional sizeof appinfo specifies that configconv shall use a 64-bit integer to realize the type in C and in binary format. Example: Special Types

<xs:simpleType name="stdIPv4"> xs:annotation xs:appinfo <cx:type name="xs:__ipv4" /> </xs:appinfo> </xs:annotation> <xs:restriction base="xs:string"> <xs:pattern value="(0|[1-9]{1,3})(.){3}" /> </xs:restriction> </xs:simpleType>

In this case, the appinfo/type/name annotation is used to tell the configuration converter to treat stdIPv4 like its internal type __ipv4. In the presence of that annotation, the restriction/base is ignored by configconv. The pattern restriction is ignored by configconv, too. On the other hand, the XSD validator will view the stdIPv4 type as a string with a pattern rule, so it can do an initial syntax check for the type. The pattern above is arguably very lax, but since configconv will parse the value, too, the exact range of each byte will be checked anyway. Using this kind of alias types, a common name for a type can be established that is usable by configconv and the XML validator. For strings and anyURI types, the data that is usually stored out of line can be allocated also inline, e.g., instead of realizing a string as char* in C, it will become an embedded array char[SIZE] with the SIZE taken from the appinfo. Note that for anyURI entries, the actual data size information that is usually output will be lost only the character array will be available the rest will be zero padded. Example: Embedded Strings

<xs:simpleType name="char32">

                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 617

<xs:annotation>
    <xs:appinfo>
        <cx:inline size="32" />
    </xs:appinfo>
</xs:annotation>
<xs:restriction base="xs:string"/>

</xs:simpleType>

<xs:complexType name="Test"> </xs:complexType>

This will be translated as follows into C:

typedef struct { char *a; char b[32]; } Test_t;

The inline size will constrain the size of the string to 31 characters in this case. This is a second constraint additional to the XSD maxLength constraint, which is enforced by the validator. Configconv does not use the maxLength restriction because for anyURI types, it cannot be used in XSD in the same way, so an appinfo annotation is used instead, which is applicable to both types, string and anyURI. Annotation Overview

annotation/documentation Not allowed here, because an alias type will not pro- duce any C code, so pikeos-configconv cannot handle any Doxygen documentation. To document the type on XSD level, use instead. restriction/minInclusive Ignored by pikeos-configconv. These attributes are used restriction/maxInclusive to restrict the values on XML level, i.e., these attributes restriction/minLength are meant for the XML validator. restriction/maxLength appinfo/ignore Has the same meaning as the corresponding attribute at enum types: if present, the type will be ignored for C code and binary generation, but configuration files may contain elements of this type without causing the file to be rejected. appinfo/type/name If this is present, then pikeos-configconv will use this at- tribute instead of restriction/base. This can be used to give pikeos-configconv a different view than the XSD val- idator. It is especially useful to define XSD types that use special types unknown to XSD, like the builtins __ipv4, __mac, etc.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

618 The ROM Images

appinfo/implementation/name If this is present, then pikeos-configconv will use this at- tribute as the type name in C without otherwise changing anything internally. E.g., the structural CRC checksum does not change when this is used. Caution: because this is a simple text replacement, no checks for compatibility are possible, so the user must ensure that the implementation type is compatible wrt. size and alignment. appinfo/sizeof/type This is used to use a different the C type/sizeof/alignment compared to the base type. For example, it can be used to define enums that use the some value, but use a dif- ferent C representation when embedded in structs. This attribute corresponds to the same attribute at enum and bitfield types. This attribute can only be used for bool, enum, or integer types. appinfo/align/value This can be used to change the default alignment of data blobs for binary generation. For example, string and anyURI will generate out-of-line data blobs contain- ing the actual data, and put a reference in the binary to that blob, and this alignment setting is used for that data blob. The default is 8. For binary data blobs that can be mapped directly, a setting of 0x1000 is often useful. This attribute can only be used if configconvs base type for this alias type is string or anyURI. appinfo/inline/size Realize the type in C and binary as an embedded array of char with the given size. This only applies to string and anyURI types. annotation/appinfo/preheader This can only be used for anyURI types. The embedded file data block will be put in front of the binary configura- tion header instead of being allocated into the space be- hind the header and before the relocations. This means that in order to find the start of the binary configura- tion header, mechanisms outside the scope of config- conv must be used, because there is no information that configconv generates to indicate the headers file position that may then be different from 0. If multiple preheaders are parsed, the order in which they are put in front of the header is unspecified. Also note that data before the header will not be CRC32 checksummed by the binary header content CRC, be- cause that checksumming starts only inside the header and covers the data up to the end of the content. However, each anyURI has its own embedded CRC32 checksum, so in total, all data in the binary configuration file will have some kind of CRC32 protection.

                        c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 619

appinfo/target/type Only accepted at IDREF base types. This defines the type of the target structure so that the type of the pointer in the C header can be selected cor- rectly. Because the reference will always be to a struct (an element), the target type must be a complexType (ei- ther struct or union). If this is not given, the IDREF will resolve to void* in C and no type checks for compatibility are done. See section A.4.2.9, page 636 for an example. appinfo/ifNotFound/emit Only accepted at IDREF base types. This defines how to react if the ID referenced by the IDREF is not found. The XSD standard demands an error message, so that is the default behaviour of configconv. To change the behaviour, possible values are: "null" to silently emit a NULL reference, "warning" to insert a NULL reference but warn about it, and "error" to abort and reject the file if the IDREF is not found. If the default behaviour is changed so that configconv behaves differently than XSD describes, then the XSD should be written in such a way that the XSD base type is string and the configconv base type of IDREF is set via target/type, because otherwise, XML files with missing IDREF targets will fail to validate with a standard XML validator.

A.4.2.6 Union Types

There are two kinds of type definitions supported by pikeos-configconv: complexType is used to define what is a struct in C, and group/choice is used to define what is a union in C. This section describes the union types, which have a simpler definition. MINIMUM SYNOPSIS

MAXIMUM SYNOPSIS

DOXYGEN TEXT
                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

620 The ROM Images

    <appinfo>
        <cx:docgroup name="DOCGROUP_NAME"/>
        <cx:ignore/>
        <cx:reloc type="none|ptr|vector"/>
    <appinfo>
</annotation>
<choice>
    <element name="NAME" type="TYPE">
        <annotation>
            <documentation>
                DOXYGEN TEXT
            </documentation>
        </annotation>
        <appinfo>
            <cx:ignore/>
            <cx:reloc type="none|ptr|vector"/>
            <cx:noConfig/>
            <cx:dumpPrefer/>
        <appinfo>
    </element>
    <!-- more <element> definitions -->
</choice>

Example

This will be translated to the following C declaration:

typedef struct { union { node_generic_t generic[1]; node_bool_t bool[1]; node_uint32_t uint32[1]; } u; } node_t;

Unions are always translated as a struct with an embedded union u for clarity so that in the C code using the union, each usage of the union is visible by a .u expression. The size (or alignment) of a union is the maximum size (or alignment) of any choice. (There is no minimum alignment for unions, in contrast to structs (see next section).)

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 621

Unions are meant to be used for other complex types, i.e., for structs. There is no restriction to do so, and pikeos- configconv will happily translate also simple types into the above structure, but usually, at runtime, to distinguish which choice was taken, on indicator value will be embedded at the same location inside each of the possible types. With simple types, it will be generally impossible to distinguish at runtime which choice was taken. The binary representation corresponds directly with the above C declaration, i.e., the data is just overlapped with he union, so the runtime code can again use the C definitions for direct access. If you set the relocation type, especially for a union, it is very advisable to do so at the type to have the same reloc at each slot, because only this way will the C code be able to access each choice in a uniform way. For example, if one choice is realized inline and the next one as a pointer, it will most probably not be possible to correctly access the union. The configuration converter does not try to enforce any kind of uniformness here, because it is a C level problem: C code generation and binary generation will work just fine. For example, with an additional <cx:reloc type="ptr"> at the element, the above would have been realized as follows.

typedef struct { union { node_generic_t *generic; node_bool_t *bool; node_uint32_t *uint32; } u; } node_t;

Annotation Overview

annotation/documentation Just like with enum types, see Page 611 annotation/appinfo/docgroup annotation/appinfo/ignore choice/element/annotation/documentation choice/element/annotation/appinfo/ignore The given choice is not generated in C code, and will be ignored in an XML input file. It has the same effect for the element as if the referenced type is marked ignored, as described for enum types already. choice/element/annotation/appinfo/noConfig This element is generated in C code and binary, but it is not allowed to be used in a XML input configuration when generating binary output. This can be used to defined access choices for C code only which are not allowed to be directly specified in XML configurations, e.g., This may contain only the signifying integer that distinguishes the choices. choice/element/annotation/appinfo/dumpPrefer This is ignored by pikeos-configconv. It is used by ex- tended tools like pikeos-configmore, which can generate dump tools for the given XSD file. In this case, there may be a situation where multiple choices are indistinguish- able in the binary form. If this element is present, this choice will be used to prefer this choice in dumping over another choice that has no such annotation. I.e., this re- solves ambiguities when dumping binary files.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

622 The ROM Images

choice/element/annotation/appinfo/reloc/type See next chapter on structs, section A.4.2.7, page 622. annotation/appinfo/reloc/type The default reloc for each slot. This overrides the global default defined at the schema, and can be over- ridden by the local default at each slot.

A.4.2.7 Struct Types

The most important and widely used complex type in configuration specification is a struct. This section introduces that type declaration. MINIMUM SYNOPSIS 1

MINIMUM SYNOPSIS 2

MAXIMUM SYNOPSIS

DOXYGEN TEXT DOXYGEN TEXT
                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 623

                <cx:ignore/>
                <cx:index by="NAMEA NAMEB ..."/>
                <cx:sort by="NAMEA NAMEB ..." [order="descending"]/>
                <!-- more <cx:sort> definitions -->
                <cx:unique/>
                <cx:reloc type="none|ptr|vector"/>
            </appinfo>
        </annotation>
    </element>
    <!-- more <element> definitions -->
    <group ref="TYPE_G"
        minOccurs="MINIMUM_OCCUR_COUNT_G"
        maxOccurs="MAXIMUM_OCCUR_COUNT_G">
        <annotation>
            <documentation>
                DOXYGEN TEXT
            </documentation>
            <appinfo>
                <cx:ignore/>
                <cx:index by="NAMEA NAMEB ..."/>
                <cx:sort by="NAMEA NAMEB ..." [order="descending"]/>
                <!-- more <cx:sort> definitions -->
                <cx:unique/>
                <cx:reloc type="none|ptr|vector"/>
            </appinfo>
        </annotation>
    </group>
    <any namespace="##other" minOccurs="0"/>
</sequence>
<attribute name="NAME_A_1" type="TYPE_A_1">
    <annotation>
        <documentation>
            DOXYGEN TEXT
        </documentation>
        <appinfo>
            <cx:ignore/>
            <cx:reloc type="none|ptr|vector"/>
        </appinfo>
    </annotation>
</attribute>
<!-- more <attribute> definitions -->

The exact order of entries in a struct in C is kept exactly like in the XSD. The different kinds of slots are generated in C and binary in the following order:

  1. slots

  2. slots

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.
    

624 The ROM Images

  1. slots

I.e., the order of the slot kinds in C this happens to be the reverse order of whats declared in the XSD. The attribute has no own slot in C, it is put in the same slot as the first anyURI typed attribute. No XSD extensions or restrictions are supported for complexType . This is mainly due to the fact that the XSD is translated to C (and not C++ or Java), which supports no native type derivation, i.e. extensions cannot be reflected in the C language. In order to keep the converter simple, it was decided to not support these features at all. For attributes, only simple types are supported (just like in XSD). For elements, both simple and complex types are supported. The converter supports all and sequence specifications, which are not distinguished by pikeos- configconv, but their sole purpose is to define one or another order acceptable in XML, so the XSD validator will distinguish whether elements are in or in . Because element slots in XSD basically define arrays, minOccurs and maxOccurs are supported to define the possible size of the array. The default values are just like in XSD: 1 for both attributes. minOccurs and maxOccurs are only supported on . On the element, minOccurs is supported with the values 0 or 1, with 1 the default. The corresponding specification on attributes is realized via the use attribute. A value of required are interpreted as a minimal count of 1, otherwise the minimal count is 0 for attributes, just like in XSD. A value of prohibited is accepted but has no special meaning to pikeos-configconv. For simpleType elements and attributes, configconv recognizes the default and fixed attributes. While the two have different meaning to the XSD validator, for pikeos-configconv, both are handled like a default value without distinction. The following is an example of a struct declaration using both attributes and elements:

In this example, assume that node is the union type defined in the previous section, see section A.4.2.6, page 619. This XSD declaration is translated to the following C declaration. The order of fields is, like in the C language, not changed inside the element and attributes. The realization order in C is: first attributes, then groups, then elements. This is the opposite order from the XSD file, but putting attributes first proved beneficial for defining unions, hence this order (see below). Padding is inserted automatically to reflect alignment and structure end padding. Padding is made explicit in C by inserting pad*: slots (both ILP32 and LP64 padding is correctly expressed in a single C file).

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 625

Note that configconv will always automatically pad structs to an 8 byte alignment to simplify internal handling (note that this is not true for unions, as described in the previous section, despite wrapping the union in a struct in C). The following shows the struct generated for the ILP32 type model.

typedef struct { unsigned char tag; char __pad1[3]; unsigned id; short * foo; node_t node[1]; struct { unsigned char *data; unsigned long size; } key; struct { unsigned char *data; unsigned long size; } xyz; unsigned char *male; char __pad2[4]; unsigned long long age; unsigned char ip[4]; char __pad3[4]; } myType3_t;

As can be seen, the storage kind differs for the different entries, depending on the values of minOccurs and maxOccurs or use, resp.. The default/fixed attributes also influences the storage, because if one of them is present, the binary representation will never lack the given value, i.e., pikeos-configconv will internally assume a minimum occur count of 1 instead of 0, independently of what is specified in XSD. The following table lists the existing storage classes, and how they are based by default on the minimum and maximum occurrence count. The tables unifies the element and attribute slots and uses minCnt and maxCnt instead of minOccurs, maxOccurs and required. As mentioned before, minCnt is at least 1 if there is a default/fixed value. The realization in C can be overridden manually with the reloc appinfo, which is also listed in the table. The combination reloc type="none" plus maxOccurs="unbounded" is forbidden and rejected by config- conv with an error, because it would mean to generate an array with infinite entry count in C.

Storage Condition and Class Description In the binary format, data of this kind will be stored inline as a single embedded data structure. minCnt == maxCnt == 1: For struct types, this will be represented in the C header as a single entry array, for simple types, as a slot of that simple type. int simpl In the above struct, tag, age and id are examples for this. foo_t compl[1]

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

626 The ROM Images

This is not possible for attributes, but only for elements: such data will be stored as an inline array in the struct with the given, constant size. minCnt == maxCnt >= 2: In the above struct, ip is an example for this.

  int   simpl[17];
  foo_t compl[17];

In the binary format, data from such slots will be stored out-of-line, and the struct will contain a pointer to that out of line data, if present. If it is minCnt == 0 AND not present, NULL will be stored. I.e., the pointer value NULL implements maxCnt == 1: the optionality. Note again that if there is a default/fixed value, no pointer is needed, so this will break down to the previous case. int *simpl; Strings directly support optionality by being pointers in C, so the required foo_t *compl; and optional variants are no different. In the above struct, male and foo are examples for this storage class. Again, this is only possible for elements, not for attributes. Inside the struct, another nested struct will be stored with the entries data, minCnt < maxCnt AND pointing the actual data array and size of type unsigned long to store maxCnt >= 2: the size of the data array. This representation was chosen to be similar in naming to C++ vectors. struct { In the binary format, such data will be stored in an array outside of the int *data; struct, and the data and size entries of the embedded struct will give the unsigned long size; location and size of the outline array. If the actual size is 0, the data pointer } simpl; will be NULL. foo_vector_t compl; All struct types have a dedicated typedef for their vector type, ending in _vector_t. This makes it easier to handle the slot in C code accessing it. In the above struct, key and xyz are examples for this.

The default reloc type is derived in such a way that no array entries are ever unfilled, array entries are not overly large, and the array size, if unclear, can be read from the binary. Manually overriding the realization using the reloc appinfo may introduce additional array entries to fill up the array, which the C program accessing the array will have to cope with. These array entries will be filled either with default values for struct types or will be filled with 0 bytes for unions and any simpleTypes. For example, when switching from vector relocation to none, array entries at the end of the array will be unfilled if the array is not specified up to the full maxOccurs count. Or when switching from a default vector relocation to ptr, then the size will be lost, only the pointer to the array will be available. There may be no way to derive the size from the resulting binary. This needs to be considered when overriding the default relocation type. On the other hand, it may make sense to switch to none relocation to remove relocation entries in order to use the data structure more easily without relocating the pointers. Also, arrays sized up to maxOccurs are equally large regardless of how many array entries are actually in the input XML, so the structure of the binary can be made more stable with this annotation. The global schema element can also have a reloc appinfo to set the default override for all slots in the file. This, in turn, can be overridden for each type, and that may be overridden locally at the given element/group/attribute. Example

<schema ...>

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 627

<annotation>
    <appinfo>
        <cx:reloc type="none"/>
    </appinfo>
</annotation>
<complexType name="foo">
    <all>
        <element name="bar" type="unsignedInt" maxOccurs="20"/>
    </all>
</complexType>

This has the same effect as:

<schema ...> <cx:reloc type="none"/>

And this has the same effect as:

<schema ...> <cx:reloc type="none"/>

And this is both realized as follows in C:

typedef struct { unsigned bar[20]; } foo_t;

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

628 The ROM Images

Without any reloc, it would have been:

typedef struct { struct { unsigned *data; unsigned long size; } bar; } foo_t;

Annotation Overview

annotation/documentation Just like with enums and unions, see Page 611 annotation/appinfo/docgroup annotation/appinfo/ignore all/element/annotation/documentation The Doxygen documentation to be prepended to the slot sequence/element/annotation/documentation in the struct definition in C. attribute/annotation/documentation all/group/annotation/documentation attribute/annotation/documentation all/element/annotation/appinfo/ignore Just like in union types: this element/slot will be allowed, sequence/element/annotation/appinfo/ignore but will be ignored in C code and binary generation. This attribute/annotation/appinfo/ignore way, additional information can be stored in the XML file all/group/annotation/appinfo/ignore without showing up in the generated binary. attribute/annotation/appinfo/ignore all/element/annotation/appinfo/reloc/type Switch the realization type in binary and C: either embed sequence/element/annotation/appinfo/reloc/type the structure, i.e., use no relocation/pointer (value none), attribute/annotation/appinfo/reloc/type but a single entry or an embedded array. Or use a simple all/group/annotation/appinfo/reloc/type pointer to an array or single entry (value ptr). Or use a attribute/annotation/appinfo/reloc/type vector, i.e., a pointer plus a size (value vector). By default, a realization is chosen based on the number of possible occurrences of the slot, as described above. This default can be overridden. A default may be specified at the type for each slot, and also at the schema for each types slot. The inner-most default will be used. If no default at all is found, the reloc type will be derived automatically as shown above. annotation/appinfo/type/name In the C language header output format, use the given type for defining the type instead of the one carrying the annotation. This will essentially implement an implicit cast, i.e., the type with the annotation is used in binary generation, which C will use the referenced type. The static assert generator will assert that the type, de- spite using a different definition in C, has exactly the same binary size, so that array declarations used in the binary format are compatible. However, this is still an implicit cast, and just like with unions (using choice), the XSD must be written in such a way that the C code is somehow able to interpret the data in a sensible way, because there will be no addition check for compatibility of the binary structure.

                          c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 629

annotation/appinfo/reloc/type The default reloc for each slot. This overrides the global default defined at the schema, and can be over- ridden by the local default at each slot. all/element/annotation/appinfo/sort/by Annotation to sort the generated array or vector in the bi- sequence/element/annotation/appinfo/sort/by nary that is generated from XML. Sorting is helpful for all/group/annotation/appinfo/sort/by using binary search later in C. The order attribute is op- sequence /group/annotation/appinfo/sort/by tional and defaults to "ascending" and can also have the value "descending" to reverse the order. See chapter section A.4.2.8, page 633 for details. all/element/annotation/appinfo/unique Based on the selected sort order, be sure that the set of sequence/element/annotation/appinfo/unique keys is unique. Using this option requires at least one all/group/annotation/appinfo/unique sort option. When combined with the index option, sequence /group/annotation/appinfo/unique this option is implicit and will have no additional effect. This option does not change binary structure, but only activates an additional check for uniqueness. See chapter section A.4.2.8, page 633 for details. all/element/annotation/appinfo/index/by Size the array the full maxOccurs count and use the sequence/element/annotation/appinfo/index/by given key to put each entry in the corresponding index of all/group/annotation/appinfo/index/by the array. Each index then needs to be unique among the sequence/group/annotation/appinfo/index/by array entries, i.e., the index option implies the unique option. Note that this may produce unfilled array entries if less than the full maxOccurs entries are given. For struct types, these entries will be filled with the default values specified for the attributes of that struct. For unions or simpleTypes, these entries will be zeroed, i.e., filled with 0 bytes. C code reading the binary will need to be able to cope with such zeroed entries. To force a fully initialized array, minOccurs=maxOccurs can be set, so that by the pigeon hole principle, all entries will be initialized from the XML input file. See chapter section A.4.2.8, page 633 for details.

A.4.2.7.1 Group References

To embed a sequence of choices in a struct, a element with a ref attribute can be used to refer to the corresponding group type as described in the previous section. Because the group element has no name attribute in XSD, there can only be one such group entry per struct type. The C struct slot will be called choice (and hence, it will conflict with elements or attributes that are called choice). Example

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

630 The ROM Images

                  c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 631

In this example, a sequence of nodes of different types is declared. Each type has a type attribute with fixed value so the union can be distinguished at runtime. Further, a generic choice is added that only contains the name and the type, for easy access in C. It carries a noConfig appinfo to prevent configuration from using this choice. The C code generated from this XSD is as follows.

typedef enum { TYPE_DIR = 0, TYPE_UINT32 = 1, } type_t;

typedef struct node node_t;

typedef struct { node_t *data; unsigned long size; } node_vector_t;

typedef struct { unsigned type; char * name; } node_generic_t;

typedef struct { unsigned type; char * name; node_vector_t choice; } node_dir_t;

typedef struct { unsigned type; char * name; unsigned data; } node_uint32_t;

struct node { union { node_generic_t generic[1]; node_dir_t prop_dir[1]; node_uint32_t prop_uint32[1]; } u; };

As can be seen, the group ref in the struct definition becomes a struct slot named choice in C, because no name can be added in XSD. The configuration converter also generates a vector type for the embedded union (it does that for all struct types, but the output was simplified for clarify here). As can also be seen, the sequence of different type entries is embedded in the same array, i.e., each array entry in the vector has the size of node_t, which is the maximum size of the embedded choices.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

632 The ROM Images

In the binary output, a group will retain the order of elements from its choice in the configuration XML file during binary generation of the corresponding array. That order can be changed by sorting, as explained later, which is exactly what is done above: the group is sorted by name. This works because all name entries have the same relative offset in the struct, the same default, and the same base type (string). The sort order is marked to result in unique keys by the unique annotation. If the input file was not unique, an error would be raised. The following is a possible input to this XSD: Example

Due to the sort directive, this will be sorted by configconv prior to generation of the binary output, corresponding to the following input file:

This file will then be turned into binary format. A group entry is not much different from an element entry, except that the sequence of elements uses multiple names depending on the choice. But storage etc. are all computed in the same way.

A.4.2.7.2 Any Element

To embed a nested configuration into a struct, the specification can be used. To avoid conflicts with the current namespace, the s namespace attribute in the XSD must be ##other to force a different namespace in the XML. pikeos-configconv supports maximally a single element to be embedded from another namespace, hence the maxOccurs attribute cannot be used, but is hardwired to 1. However, the element can be made optional by using minOccurs=0. An specification will not be allocated its own slot in the surrounding struct, but instead, will be allocated into a slot of type anyUri, i.e., there must be another slot of that type, otherwise cannot be used. If an element from a different namespace is found in the XML where is specified in the XSD, then the anyURI typed slot must have the value "internal:any" to establish the link. Example XSD Definition

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 633

    <any minOccurs="0" namespace="##other"/>
</sequence>
<attribute name="name" type="string" use="required"/>
<attribute name="data" type="anyURI" default="internal:any" />

With this specification, the following C code will be generated:

typedef struct { char *name; struct { void *data; unsigned long size; } data; } node_config_t;

As can be seen, the specification had no effect on the generated C source code: there is no slot for it in the struct. The above XSD specification accepts the following two formats of configuration, assuming an element config of type node_config.

This format loads the data stored in node_config_t::data from disk, from the file /tmp/data.bin In contrast to that, the following is embedded configuration:

...

In this case, pikeos-configconv will recursively generate binary data for the embedded root node, which matches the specification. By the default value in the XSD, the data slot has the value "internal:any", so the binary data recursively generated is embedded into the node_config_t::data structure. As previously mentioned, the anyURI simple type supports the align appinfo, by which the alignment of the embedded data in the binary output file can be specified. An alias type is typically defined for this, and in the above XSD, the data attribute would then use that alias type instead. The C code will look exactly the same, regardless of alignment.

A.4.2.8 Sorted and Indexed Arrays

Arrays can be sorted during binary generation by the converter. For this, the corresponding element in a complexType may carry multiple annotation:appinfo:sort annotations. Furthermore, arrays can be ar- ranged to put entries into indices given in XML/XSD for easy indexing in C. This works similarly to sorting.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

634 The ROM Images

The multiple sort annotation will be used to sort the array by multiple entries of the underlying complexType, i.e., multi-level sorting is supported. The sort hierarchy is defined by the order of sort elements in appinfo, the first being the highest priority sort criterion and for equal key, the next lower sort criterion is used. The above Group.person array will thus be primarily sorted by name and for equal names, by age. For integer and string, a standard sort algorithm is used (as an implementation note: a stable one is used to support multi-level sorting). Sorting is supported in ascending and descending orders. For optional entries, the sorting algorithm assumes the lowest value in the sort order, i.e., missing values will precede present values, e.g., for integers, NULL is smaller than 0; for strings, NULL is smaller than "". It is possible to sort not only by a single attribute, like above, but also zero or multiple keys, with the key names separated by space. For example, an array of integers can be sorted as follows, without any key to address a struct (note the by="", referring to the slot value itself):

Indexing has a similar syntax as sorting and uses the index appinfo. The referenced slot must be an unsigned integer, an enum, or a bitfield enum. Signed indices are not supported. The value of the index slot must be between 0 and maxOccurs 1.

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 635

In this case, the vector to store part_rom will be sized to accommodate 63 entries, based on the maxOccurs option. For a key, PartRom::partition will be used as an index into that array to place the entries. Indexing implicitly sorts the array to find multiple keys, which are disallowed. Since the key for indexing must be unique, it makes no sense to combine indexing with sorting, because any secondary sorting would have no effect. Note that the index appinfo has no influence on the type of reloc that is chosen, so the default in the above example is still a vector, because minOccurs != maxOccurs. In many cases, using index is sensibly combined with using <cx:reloc type="none">. If index is used with vector storage, the vector will contain as size value the actual count of entries that where found in the XML file, while the array pointed to by data will be allocated according to the maxOccurs setting.

A.4.2.8.1 Multi-Step Sort and Index Keys

To sort a vector by a slot inside another struct, a multi-step key can be used:

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

636 The ROM Images

In this example, the persons are primarily sorted by surname, cf. by="name sur", a two-step key first into Person::name and then into Name::sur. They are then secondarily sorted, if the surname is equal, by their first name, and finally, if both name constituents are equal, by age, in descending order. Group entries can also be sorted. Note that configconv does not check whether the entries will be distinguishable at run-time, and that the key can be extracted at run time in a uniform way. For this, the sort key will most probably need to be at the same byte offset for each of the choices of the group, and be of compatible type, including its size in bytes. It is left to the responsibility of the writer of the XSD to ensure this. The structs have a rigid order, just like in C, so the uniform access can be achieved in the same way as in C by using the same layout in the struct.

A.4.2.9 ID and IDREF

Arbitrary pointers can be established in the binary format by using the ID type to define a named alias for a given element, and by using IDREF to insert a pointer to an equally named alias. The mechanism is exactly how it works in standard XSD, but because we want typesafe C output, the IDREF slot is required to defined a target type, which will be checked, using the type/name annotation. Example

With this definition, the parent slot can link to any other node in the input file. The resulting C code definition will look as follows.

typedef struct Person Person_t; struct Person { char *name; void *parent; };

The input XML may now link IDREF to ID, e.g.:

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 637

... ...

The possible target types should be restricted to get more type safety in C. This is done by defining an alias type of IDREF with a given target type. For example:

This way, the C declaration is specialized, and configconv will allow only IDREFs to IDs with a Person type, i.e., type safety is ensured.

typedef struct Person Person_t; struct Person { char *name; Person_t *parent; };

In XSD, the ID has certain restrictions wrt. what string may be used. Internally, configconv does not have such restrictions: any string may be used. For example, spaces are not allowed in XSD. So to please the XSD validator, if you want freeform format, the fact that an ID is used needs to be hidden by using an alias type to have a different type to XSD and to configconv. For example, to use surname and first name with spaces, we could have defined the following.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

638 The ROM Images

    <appinfo>
        <cx:type name="IDREF"/>
        <cx:target type="pp:Person"/>
    </appinfo>
</annotation>
<restriction base="string"/>

With this definition, configconv establishes ID/IDREF references while the XSD validator only sees string. You can use this to have the following input XML.

... <Person name="John Doe" ... /> ...

Configconv has another extension, the __ref_id type, to replace the globally unique names by a recursive name definition, similar to directories. Using the recursive node example again, imagine the following, where we add another type node_link. Note that NameID and NameIDREF are almost the same as above, only NameID uses the type __rec_id for configconv now, which will cause the names to be recursively constructed.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 639

    <enumeration value="TYPE_UINT32"/>
    <enumeration value="TYPE_LINK"/>
</restriction>

With this definition, we can now use directory like names, where the IDs are constructed according to __rec_id names of the parent nodes. Note that only one __rec_id can be defined for any given element, while multiple are allowed for ID. This is because the subtrees will only go by a single path name. The following is an example of how a link can be established.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

640 The ROM Images

This way, a link will be established from the link nodes data slot to the internal integer. The names ROOT and eins and foo are all concatenated to give ROOT/eins/foo for the full ID of the inner uint32 node. Note also that the type does not exactly match: the IDREF has a target type of node and the type of the referenced node is actually node_uint32. This works because unions are accepted for target types if they contain as a choice the referenced node. This requires the type to be directly embedded into the union, i.e., the choice slot must have a reloc of none. Otherwise, the pointer structure would not work neither in C nor the binary, and therefore, such choices are rejected.

A.4.2.10 Pointers

Apart from scalar typed content, the binary configuration format stores pointers. However, pointers to memory locations make no sense in a generic file format. Therefore, all pointers are stored relative to their own position (the location of first byte), i.e., they are stored as self-relative pointers. Self-relative pointers require only a pointer to themselves to be resolved: since their own address is the base, no additional base pointer needs to be specified. To make pointers absolute for easy access in C, which does not have a self-relative pointer type, a relocation table is defined in the binary format (see next section). NULL is represented as 0 (i.e., there cannot be self-recursive pointers) and no relocation entry will be generated for NULL pointers.

A.4.2.11 Relocation Entries

To relocate the self-relative pointers in the binary format after loading, i.e., to recomputed for native C use absolute addresses, the converter generates an array of relocation entries. This array contains pointers to each pointer in the binary data block that needs relocation. The relocation entries are themselves self-pointers.

A.4.3 Binary Format Header

To store initial information, checksum, signatures, relocation info etc., the binary format the configuration converter generates from the XSD and XML is preceded by a header that is identical for all binary configuration files. To keep the header relatively small and still support full CRC-protected structures, the CRCs are initialized with a unique value that also contains a version number. This way, the CRC acts as a version control mechanism, too. The header contains the following entries (in the given order). The header is designed so that neither on ILP32 nor on LP64 it will have any intermediate padding bytes inserted by the compiler.

C Type Name Description unsigned int sig The signature of the binary file format (see below) unsigned int version The version of the binary file format (see below). unsigned int header_crc The CRC checksum spanning the binary configuration header, starting at DRV_CONFIG_CRC_START and ending before byte sizeof(drv_bin_header_t). unsigned int data_crc CRC32 checksum of the whole data block, starting at DRV_CONFIG_CRC_START, and ending before byte size as stored in the header.

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 641

All following entries will be CRC protected by the above CRC checksums.

C Type Name Description unsigned short sizeof_ptr Either 4 or 8, depending on memory model. unsigned short header_size The size, in bytes, of the header. unsigned int element_crc CRC32 of the top-level element name. Schemas may allow several top-level elements. This is a CRC32 of the element name used as top level. unsigned long size The size of the complete binary configuration file, starting from the very first byte in the header up to the last byte, including all padding. This should be equal to the file size when the binary format is stored in a data medium. This entry can be used for computing the CRC if the size is otherwise unknown from secondary information channels, e.g. if only a pointer to the first byte of the header is available. The header_crc can ensures that this value is uncorrupted before it is used to compute the full file CRC. void->->-> reloc_start Start of relocation array. The relocation array consists of unsigned long entries each of which is an offset into the binary data (starting to count at 0 at the beginning of the bin_header_t). Each entry thus points to a pointer that needs relocation by adding the address in memory at the begin- ning of bin_header_t. This is a relative pointer (relative to itself), signified by replacing * with -> in the C type. Technically, this is a pointer to a pointer to a pointer, all pointers being relative, so the type is given as void->->-> (the C type, if it was absolute pointers, would thus be void ***). If this is 0, then no relocation area is present (either the file is relocated already, or it needs no relocation). extension_arr This is a variable size array defining extension blocks. This array may be completely empty (0 entries). struct { Each block has a tag and a start. Future formats will possibly add ex- long tag; tension blocks, and by reserving this array for that, the principle format void-> start; of the header will not need to change. } [] The only tag defined currently is 0, which terminates the extension array. The extension array is also terminated by header_size. Negative tags are reserved for private use. They will never be defined by SYSGO and will always be ignored by SYSGO tool chains and libraries. char[] padding After the extension array, padding may follow. These are always 0x00 bytes. Padding may be missing completely if the structure is already properly padded.

The X-> notation designates a self-relative pointer to data type X. The C type used in the header file is simply a pointer so that after relocation, the pointers can be used directly. To compute the actual absolute address, add the signed numeric value stored in that pointer to its absolute address. For example, assume that there is a pointer X* x with (long)x equal to 8 and (unsigned long)&x equal to 0x40000000, then the absolute pointer x points to is 0x40000008. Data starts exactly where the header ends. The header end is defined by header_size. The structure may be aligned and thus zero padded at the end (reflected by different header sizes) to 8 bytes or more, depending on architecture. A reader should not expect more than an alignment of 8, but a writer is free to introduce more padding (e.g. to pad to the next cache line boundary).

                            c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

642 The ROM Images

Note that header_size is not necessarily equal to sizeof(drv_config_header_t) (but may accidentally be equal) due to the extension array and possible padding. header_size determines where the data block of the binary format starts. Padding may follow after the header, after the data area and after the relocation. This should be ignored at reading. Any padding bytes in the binary format are 0. The header is crafted in such a way that its architecture signature can be checked in the same way for 32-bit and 64-bit architectures: sizeof_ptr is stored in two bytes so that depending on endianness of the target architecture, the value is stored in different order and can thus be checked in target code by checking for equality of h->sizeof_ptr and sizeof(void*). The possible byte sequences for this entry are:

                                  00 04      big endian 32-bit architecture
                                  00 08      big endian 64-bit architecture
                                  04 00      little endian 32-bit architecture
                                  08 00      little endian 64-bit architecture

Only ILP32 and LP64 data models are supported by the defining header file, as mentioned in the previous chapter, therefore this single entry exhaustively defines the target architecture. Anything in the header that is not explicitly compared to a constant value is protected by a 32-bit CRC checksum. The CRC32 specified in the ARINC653 standard is used (see below for more details). When loading, before checking the header CRC, the entries sig, version, and sizeof_ptr must be checked for exact equality to what the reader expects. Then, header_size should be checked for consistency (it should be greater than or equal to sizeof(drv_config_header_t) and be smaller than size, as well as 8-byte aligned). This consistency check is optional because header_size is CRC protected anyway. The header_crc is computed for exactly sizeof(drv_config_header_t) bytes, not for header_size bytes. This is done so that header_size, which is not computed to a constant value, is also protected by a CRC checksum. This means that the extension array is not protected by header_crc. Before accessing the extension array, data_crc needs to be checked, which protects the whole binary file structure. The binary format is made available to C by a dedicated header file (config-format.h). It also contains several constants mentioned already above, which are defined as follows:

                                DRV_CONFIG_SIG                    0x148c7ab0
                                DRV_CONFIG_VERSION                         9
                                DRV_CONFIG_CRC_START                      16

The exact order of data structs and strings inside the binary format data area is undefined, but deterministic. The first object always starts at the address defined by header_size, i.e., directly following the header. Obviously, it is guaranteed that the pointer structure is correct, so there is no need in C to rely on any particular order. When generating binary format, any preferred order may be used. The element CRC is serves two purposes: first, by generating a unique ID for a schema element, the binary format can distinguish which element declared in the XSD was used as the top-level element. The second purpose is to give another robustness layer, i.e., if the binary structure changes, the element CRC will change, too. The element CRC will not change for all changes that might affect how the configuration is interpreted, or whether it is valid, e.g., most of the restrictions are not expressed. The main protection focus is the binary structure, i.e., types, sizes, and order. A configuration should, therefore, contain a version number that the configuration reader checks. On the other hand, the element CRC may be too eager to change in some cases, e.g., when a slot name

                             c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 643

is changed while the binary format stays the same. In that case, again, a version number is advisable to see whether the changes are still compatible.

A.4.3.1 CRC Checksums

The CRC checksums are exactly the ARINC 665-5 CRC-32: the polynomial generator is 0x04c11db7 (inverse: 0xedb88320). The init value is 0xffffffff (all ones, 32-bit). The result is bit-inverted to finalize the CRC. Three constant values are always added to the CRC after initialization of the sum, to ensure different CRCs for different file formats. These three 32-bit values that are added are (in order): DRV_CONFIG_SIG, DRV_CONFIG_VERSION, and DRV_CONFIG_CRC_START. They are always added in little endian order (thus the data added for the first four bytes is b0 7a 8c 14). The actual data block protected by the CRC is added to the CRC in the target byte order, i.e., byte by byte following the binary data. The computation of the element CRC is based on a text file that is generated to list all the reachable types starting at the given element. It encodes all their important properties in order to change whenever the file format changes. This generated text file will then be used to generate a CRC with the above algorithm. The element CRC checksum text file can be generated with pikeos-configconv using the --crc=ELEMENT option, in order to check expectations or simply to see examples. The following text describes the generation algorithm of the text file. The structure text file in is CSV syntax. No quotes are ever used, because only C identifiers are encoded in the file. No white space is used except for the line breaks. All decimal numbers are in the shortest possible notation (no leading 0s, except for 0 itself). The first column of each line is the column type. There are the following types, each a single letter: "t" type name "k" kind of type "e" subelement (slot in structs, choice in unions) "v" enum value The lines in the file have a different structure depending on the given type, as explained below. The text file consists of two sections: the first section is a list of types, sorted lexicographically by XSD type name. The second section is a list of enum values. Since these enum value names are global in C, this list is not embedded in the type, but is a separate global section. In the list of types, each type starts with a "t" line. A "t" line has the following columns.

   t,TYPENAME,SIZE32,SIZE64

Here, TYPENAME is the name of the type from the XSD, and SIZE32 and SIZE64 are the sizes in bytes in ILP32 and LP64 architecture models. For structs or union, the "t" line is followed by a "k" line, which has two columns:

   k,KIND

Here, KIND is either "struct" or "union". After a "k" line, the list of elements follows in "e" lines. An "e" line of a struct has five columns:

   e,NAME,MINCOUNT,MAXCOUNT,STORAGE


                              c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

644 The ROM Images

MINCOUNT and MAXCOUNT are decimal numbers, but if MAXCOUNT is unbounded, it is the empty string. The storage is a single letter defining how the entry in the struct is stored. The following options exist for STORAGE: "" inline: Type name "p" pointer: Type *name "v" vector: struct { Type *data; unsigned long size; } name For unions, the "e" line has only two columns:

    e,NAME

The second part of the file, the enum value list, is a list of "v" lines sorted lexicographically by name, each line has the following structure:

    v,NAME,TYPE,NUMERIC

The TYPE is again the XSD type. NUMERIC is in decimal notation. Each line is terminated with a single "\n" character (also on Windows "\r" is never used). This generated text file is then CRC checksummed with the standard algorithm described at the beginning of this section to give the element CRC.

A.4.4 Access Function and Macros

Once binary format becomes available on the target in the form of a block of data, access is possible using the C definitions that the configuration converter can generate. For this access, PikeOS defines a few auxiliary functions. These cover the following functionality. The following overview lists function and macro names related to the given functionality.

  • Check CRC checksums on data blocks with the standard binary file CRC checksum algorithm:

        ◦ drv_crc32_get

  • Check the binary header for signature, version, endianness, word width, and check the header and data
    CRC checksums:

        ◦ drv_config_valid

  • Get the pointer to payload data after checking that no relocation is needed, or, if allowed, apply the relocation
    to the binary, i.e., resolve all relative pointers inline:

        ◦ drv_config_get_data

  • Copy the binary configuration data to RAM, then do the previously mentioned checking and relocation:

        ◦ drv_config_import

  • Access a sorted array with binary search:

        ◦ DRV_BSEARCH

  • Access the binary using the relative pointers directly instead of first relocating (which may require copying
    the data to RAM):


                                c Copyright 2005  2019 SYSGO GmbH, all rights reserved.

Binary Configuration Data and Converter Tool 645

     ◦ DRV_RPTR_GET
     ◦ DRV_VECTOR_BSEARCH
     ◦ DRV_VECTOR_NTH

See the Driver Reference Manual for a detailed description of the above functions and macros.

                           c Copyright 2005  2019 SYSGO GmbH, all rights reserved.