1 /*
2  * Copyright (c) 2024, Tenstorrent AI ULC
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <errno.h>
8 #include <time.h>
9 
10 #include <zephyr/kernel.h>
11 #include <zephyr/posix/sys/times.h>
12 #include <zephyr/posix/unistd.h>
13 #include <zephyr/sys/clock.h>
14 #include <zephyr/sys/time_units.h>
15 #include <zephyr/sys/util.h>
16 
getpid(void)17 pid_t getpid(void)
18 {
19 	/*
20 	 * To maintain compatibility with some other POSIX operating systems,
21 	 * a PID of zero is used to indicate that the process exists in another namespace.
22 	 * PID zero is also used by the scheduler in some cases.
23 	 * PID one is usually reserved for the init process.
24 	 * Also note, that negative PIDs may be used by kill()
25 	 * to send signals to process groups in some implementations.
26 	 *
27 	 * At the moment, getpid just returns an arbitrary number >= 2
28 	 */
29 
30 	return 42;
31 }
32 #ifdef CONFIG_POSIX_MULTI_PROCESS_ALIAS_GETPID
33 FUNC_ALIAS(getpid, _getpid, pid_t);
34 #endif /* CONFIG_POSIX_MULTI_PROCESS_ALIAS_GETPID */
35 
times(struct tms * buffer)36 clock_t times(struct tms *buffer)
37 {
38 	int ret;
39 	clock_t utime; /* user time */
40 	k_thread_runtime_stats_t stats;
41 
42 	ret = k_thread_runtime_stats_all_get(&stats);
43 	if (ret < 0) {
44 		errno = -ret;
45 		return (clock_t)-1;
46 	}
47 
48 	utime = z_tmcvt(stats.total_cycles, sys_clock_hw_cycles_per_sec(), USEC_PER_SEC,
49 			IS_ENABLED(CONFIG_TIMER_READS_ITS_FREQUENCY_AT_RUNTIME) ? false : true,
50 			sizeof(clock_t) == sizeof(uint32_t), false, false);
51 
52 	*buffer = (struct tms){
53 		.tms_utime = utime,
54 		.tms_stime = 0,
55 		.tms_cutime = 0,
56 		.tms_cstime = 0,
57 	};
58 
59 	return utime;
60 }
61