|
| 1 | +// Copyright 2022 The IREE Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License v2.0 with LLVM Exceptions. |
| 4 | +// See https://llvm.org/LICENSE.txt for license information. |
| 5 | +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | + |
| 7 | +#include "iree/base/internal/cpu.h" |
| 8 | + |
| 9 | +#include "iree/base/target_platform.h" |
| 10 | + |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | +// iree_cpu_* |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +#if defined(IREE_PLATFORM_ANDROID) || defined(IREE_PLATFORM_EMSCRIPTEN) || \ |
| 16 | + defined(IREE_PLATFORM_LINUX) |
| 17 | + |
| 18 | +#include <sched.h> |
| 19 | + |
| 20 | +extern __attribute__((weak)) int sched_getcpu(void) { |
| 21 | + // TODO(benvanik): emulate with syscall/vdso/etc. |
| 22 | + errno = ENOSYS; |
| 23 | + return -1; |
| 24 | +} |
| 25 | + |
| 26 | +iree_cpu_processor_id_t iree_cpu_query_processor_id(void) { |
| 27 | + // This path is relatively portable and should work on linux/bsd/etc-likes. |
| 28 | + // We may want to use getcpu when available so that we can get the group ID. |
| 29 | + // https://man7.org/linux/man-pages/man3/sched_getcpu.3.html |
| 30 | + // |
| 31 | + // libc implementations can use vDSO and other fun stuff to make this really |
| 32 | + // cheap: http://git.musl-libc.org/cgit/musl/tree/src/sched/sched_getcpu.c |
| 33 | + int id = sched_getcpu(); |
| 34 | + return id != -1 ? id : 0; |
| 35 | +} |
| 36 | + |
| 37 | +#elif defined(IREE_PLATFORM_WINDOWS) |
| 38 | + |
| 39 | +iree_cpu_processor_id_t iree_cpu_query_processor_id(void) { |
| 40 | + PROCESSOR_NUMBER pn; |
| 41 | + GetCurrentProcessorNumberEx(&pn); |
| 42 | + return 64 * pn.Group + pn.Number; |
| 43 | +} |
| 44 | + |
| 45 | +#else |
| 46 | + |
| 47 | +// No implementation. |
| 48 | +// We could allow an iree/base/config.h override to externalize this. |
| 49 | +iree_cpu_processor_id_t iree_cpu_query_processor_id(void) { return 0; } |
| 50 | + |
| 51 | +#endif // IREE_PLATFORM_* |
| 52 | + |
| 53 | +void iree_cpu_requery_processor_id(iree_cpu_processor_tag_t* IREE_RESTRICT tag, |
| 54 | + iree_cpu_processor_id_t* IREE_RESTRICT |
| 55 | + processor_id) { |
| 56 | + IREE_ASSERT_ARGUMENT(tag); |
| 57 | + IREE_ASSERT_ARGUMENT(processor_id); |
| 58 | + |
| 59 | + // TODO(benvanik): set a frequency for this and use a coarse timer |
| 60 | + // (CLOCK_MONOTONIC_COARSE) to do a ~4-10Hz refresh. We can store the last |
| 61 | + // query time and the last processor ID in the tag and only perform the query |
| 62 | + // if it has changed. |
| 63 | + |
| 64 | + *processor_id = iree_cpu_query_processor_id(); |
| 65 | +} |
0 commit comments