Patchwork [01/20] host-utils: add ffsl

login
register
mail settings
Submitter Paolo Bonzini
Date Dec. 12, 2012, 1:46 p.m.
Message ID <1355319999-30627-2-git-send-email-pbonzini@redhat.com>
Download mbox | patch
Permalink /patch/205538/
State New
Headers show

Comments

Paolo Bonzini - Dec. 12, 2012, 1:46 p.m.
We can provide fast versions based on the other functions defined
by host-utils.h.  Some care is required on glibc, which provides
ffsl already.

Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
---
 host-utils.h | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)
Eric Blake - Dec. 12, 2012, 11:41 p.m.
On 12/12/2012 06:46 AM, Paolo Bonzini wrote:
> We can provide fast versions based on the other functions defined
> by host-utils.h.  Some care is required on glibc, which provides
> ffsl already.
> 
> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
> ---
>  host-utils.h | 26 ++++++++++++++++++++++++++
>  1 file changed, 26 insertions(+)

Reviewed-by: Eric Blake <eblake@redhat.com>

> 
> diff --git a/host-utils.h b/host-utils.h
> index 821db93..231d580 100644
> --- a/host-utils.h
> +++ b/host-utils.h
> @@ -24,6 +24,7 @@
>   */
>  
>  #include "compiler.h"   /* QEMU_GNUC_PREREQ */
> +#include <string.h>     /* ffsl */

I never really understood why ffs() is in <strings.h> but ffsl() is in
<string.h>, especially when neither function deals with strings (a
<bitops.h> header would have made more sense), but such is life.

Patch

diff --git a/host-utils.h b/host-utils.h
index 821db93..231d580 100644
--- a/host-utils.h
+++ b/host-utils.h
@@ -24,6 +24,7 @@ 
  */
 
 #include "compiler.h"   /* QEMU_GNUC_PREREQ */
+#include <string.h>     /* ffsl */
 
 #if defined(__x86_64__)
 #define __HAVE_FAST_MULU64__
@@ -234,3 +235,28 @@  static inline int ctpop64(uint64_t val)
     return val;
 #endif
 }
+
+/* glibc does not provide an inline version of ffsl, so always define
+ * ours.  We need to give it a different name, however.
+ */
+#ifdef __GLIBC__
+#define ffsl qemu_ffsl
+#endif
+static inline int ffsl(long val)
+{
+    if (!val) {
+        return 0;
+    }
+
+#if QEMU_GNUC_PREREQ(3, 4)
+    return __builtin_ctzl(val) + 1;
+#else
+    if (sizeof(long) == 4) {
+        return ctz32(val) + 1;
+    } else if (sizeof(long) == 8) {
+        return ctz64(val) + 1;
+    } else {
+        abort();
+    }
+#endif
+}