On 8/27/23 08:57, Karim Taha wrote:
From: Kyle Evans <kev...@freebsd.org>

Signed-off-by: Kyle Evans <kev...@freebsd.org>
Signed-off-by: Karim Taha <kariem.taha...@gmail.com>
---
  bsd-user/bsd-proc.c | 39 +++++++++++++++++++++++++++++++++++++++
  bsd-user/bsd-proc.h |  2 ++
  2 files changed, 41 insertions(+)

diff --git a/bsd-user/bsd-proc.c b/bsd-user/bsd-proc.c
index 49c0fb67d0..dd6bad6de3 100644
--- a/bsd-user/bsd-proc.c
+++ b/bsd-user/bsd-proc.c
@@ -185,3 +185,42 @@ int host_to_target_waitstatus(int status)
      return status;
  }
+int bsd_get_ncpu(void)
+{
+    static int ncpu = -1;
+
+    if (ncpu != -1) {
+        return ncpu;
+    }
+    if (ncpu == -1) {
+        cpuset_t mask;
+
+        CPU_ZERO(&mask);
+
+        if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, 
sizeof(mask),
+                               &mask) == 0) {
+            ncpu = CPU_COUNT(&mask);
+        }
+    }
+#ifdef _SC_NPROCESSORS_ONLN
+    if (ncpu == -1)
+        ncpu = sysconf(_SC_NPROCESSORS_ONLN);
+#endif
+#if defined(CTL_HW) && defined(HW_NCPU)
+    if (ncpu == -1) {
+        int mib[2] = {CTL_HW, HW_NCPU};
+        size_t sz;
+
+        sz = sizeof(ncpu);
+        if (sysctl(mib, 2, &ncpu, &sz, NULL, NULL) == -1) {
+            ncpu = -1;
+        }
+    }
+#endif
+    if (ncpu == -1) {
+        gemu_log("XXX Missing bsd_get_ncpu() implementation\n");
+        ncpu = 1;
+    }
+    return ncpu;
+}

This has the look of odd compatibility code. Surely all three of these alternatives are functional, and that sysconf() is easiest to use.

Looking at the freebsd implementation of sysconf, it uses AT_NCPUS if available, so the value is already cached within the process in the common case. So I also don't see a need for the ncpu local static either.


r~

Reply via email to