Skip to contentSkip to conversation

Introduce strtosz and make use of it

PATCH Applied [email protected] 3 participants 9 messages Oct 21, 2010 – Nov 3, 2010

lore
Share & tools
lore
#0 lore raw

v9 cover Introduce strtosz and make use of it

From: Jes Sorensen <[email protected]>

This patch introduces cutils.c: strtosz() and gets rid of the multiple custom hacks for parsing byte sizes. In addition it adds supports for specifying human style sizes such as 1.5G. Last it eliminates the horrible abuse of a float to store the byte size for migrate_set_speed in the monitor.

Note, this is tested on Linux and build tested for win32 using mingw32.

v9: I worked through a couple of revisions directly with Markus and I think I got it right finally.

Cheers,
Jes

Jes Sorensen (4):
Introduce strtosz() library function to convert a string to a byte
count.
Add support for 'o' octet (bytes) format as monitor parameter. Switch migrate_set_speed() to take an 'o' argument rather than a
float.
Remove obsolete 'f' double parameter type

 cutils.c        |   88 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 hmp-commands.hx |    5 ++-
 migration.c     |    4 +-
 monitor.c       |   47 +++++++++++++++++++----------
 qemu-common.h   |    1 +
 vl.c            |   31 ++++++-------------
 6 files changed, 134 insertions(+), 42 deletions(-)
Signature · 1 line
1.7.2.3
#1 lore raw

PATCH v9 1/4 Introduce strtosz() library function to convert a string to a byte count.

From: Jes Sorensen <[email protected]>

strtosz() returns -1 on error. It now supports human unit formats in eg. 1.0G, with better error handling.

The following suffixes are supported:
B/b = bytes
K/k = KB
M/m = MB
G/g = GB
T/t = TB

This patch changes -numa and -m input to use strtosz().

---
 cutils.c      |   88 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 qemu-common.h |    1 +
 vl.c          |   31 ++++++-------------
 3 files changed, 99 insertions(+), 21 deletions(-)
cutils.c +88 -0
index 5883737..28089aa 100644
@@ -23,6 +23,7 @@
  */
 #include "qemu-common.h"
 #include "host-utils.h"
+#include <math.h>
 
 void pstrcpy(char *buf, int buf_size, const char *str)
 {
@@ -283,3 +284,90 @@ int fcntl_setfl(int fd, int flag)
 }
 #endif
 
+/*
+ * Convert string to bytes, allowing either B/b for bytes, K/k for KB,
+ * M/m for MB, G/g for GB or T/t for TB. Default without any postfix
+ * is MB. End pointer will be returned in *end, if not NULL. A valid
+ * value must be terminated by whitespace, ',' or '\0'. Return -1 on
+ * error.
+ */
+ssize_t strtosz(const char *nptr, char **end)
+{
+    ssize_t retval = -1;
+    char *endptr, c;
+    int mul_required = 0;
+    double val, mul, integral, fraction;
+
+    errno = 0;
+    val = strtod(nptr, &endptr);
+    if (isnan(val) || endptr == nptr || errno != 0) {
+        goto fail;
+    }
+    integral = modf(val, &fraction);
+    if (integral != 0) {
+        mul_required = 1;
+    }
+    /*
+     * Any whitespace character is fine for terminating the number,
+     * in addition we accept ',' to handle strings where the size is
+     * part of a multi token argument.
+     */
+    c = *endptr;
+    if (isspace(c) || c == '\0' || c == ',') {
+        c = 0;
+    }
+    switch (c) {
+    case 'B':
+    case 'b':
+        mul = 1;
+        if (mul_required) {
+            goto fail;
+        }
+        break;
+    case 'K':
+    case 'k':
+        mul = 1 << 10;
+        break;
+    case 0:
+        if (mul_required) {
+            goto fail;
+        }
+    case 'M':
+    case 'm':
+        mul = 1ULL << 20;
+        break;
+    case 'G':
+    case 'g':
+        mul = 1ULL << 30;
+        break;
+    case 'T':
+    case 't':
+        mul = 1ULL << 40;
+        break;
+    default:
+        goto fail;
+    }
+    /*
+     * If not terminated by whitespace, ',', or \0, increment endptr
+     * to point to next character, then check that we are terminated
+     * by an appropriate separating character, ie. whitespace, ',', or
+     * \0. If not, we are seeing trailing garbage, thus fail.
+     */
+    if (c != 0) {
+        endptr++;
+        if (!isspace(*endptr) && *endptr != ',' && *endptr != 0) {
+            goto fail;
+        }
+    }
+    if ((val * mul >= ~(size_t)0) || val < 0) {
+        goto fail;
+    }
+    retval = val * mul;
+
+fail:
+    if (end) {
+        *end = endptr;
+    }
+
+    return retval;
+}
qemu-common.h +1 -0
index 81aafa0..0a062d4 100644
@@ -153,6 +153,7 @@ time_t mktimegm(struct tm *tm);
 int qemu_fls(int i);
 int qemu_fdatasync(int fd);
 int fcntl_setfl(int fd, int flag);
+ssize_t strtosz(const char *nptr, char **end);
 
 /* path.c */
 void init_paths(const char *prefix);
vl.c +9 -20
index df414ef..6043fa2 100644
@@ -734,16 +734,13 @@ static void numa_add(const char *optarg)
         if (get_param_value(option, 128, "mem", optarg) == 0) {
             node_mem[nodenr] = 0;
         } else {
-            value = strtoull(option, &endptr, 0);
-            switch (*endptr) {
-            case 0: case 'M': case 'm':
-                value <<= 20;
-                break;
-            case 'G': case 'g':
-                value <<= 30;
-                break;
+            ssize_t sval;
+            sval = strtosz(option, NULL);
+            if (sval < 0) {
+                fprintf(stderr, "qemu: invalid numa mem size: %s\n", optarg);
+                exit(1);
             }
-            node_mem[nodenr] = value;
+            node_mem[nodenr] = sval;
         }
         if (get_param_value(option, 128, "cpus", optarg) == 0) {
             node_cpumask[nodenr] = 0;
@@ -2163,18 +2160,10 @@ int main(int argc, char **argv, char **envp)
                 exit(0);
                 break;
             case QEMU_OPTION_m: {
-                uint64_t value;
-                char *ptr;
+                ssize_t value;
 
-                value = strtoul(optarg, &ptr, 10);
-                switch (*ptr) {
-                case 0: case 'M': case 'm':
-                    value <<= 20;
-                    break;
-                case 'G': case 'g':
-                    value <<= 30;
-                    break;
-                default:
+                value = strtosz(optarg, NULL);
+                if (value < 0) {
                     fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
                     exit(1);
                 }
Signature · 1 line
1.7.2.3
#2 lore raw

[Qemu-devel] Re: [PATCH 1/4] Introduce strtosz() library function to convert a string to a byte count.

Quoted 12 lines · On 10/21/2010 10:15 AM, [email protected] wrote:

From: Jes Sorensen<[email protected]>

strtosz() returns -1 on error. It now supports human unit formats in eg. 1.0G, with better error handling.

The following suffixes are supported:
B/b = bytes
K/k = KB
M/m = MB
G/g = GB
T/t = TB

Quoted 4 lines

This patch changes -numa and -m input to use strtosz().

Applied all. Thanks.

Regards,

Anthony Liguori

Quoted 171 lines
---
  cutils.c      |   88 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  qemu-common.h |    1 +
  vl.c          |   31 ++++++-------------
  3 files changed, 99 insertions(+), 21 deletions(-)
cutils.c +88 -0
index 5883737..28089aa 100644
@@ -23,6 +23,7 @@
   */
  #include "qemu-common.h"
  #include "host-utils.h"
+#include<math.h>
 
  void pstrcpy(char *buf, int buf_size, const char *str)
  {
@@ -283,3 +284,90 @@ int fcntl_setfl(int fd, int flag)
  }
  #endif
 
+/*
+ * Convert string to bytes, allowing either B/b for bytes, K/k for KB,
+ * M/m for MB, G/g for GB or T/t for TB. Default without any postfix
+ * is MB. End pointer will be returned in *end, if not NULL. A valid
+ * value must be terminated by whitespace, ',' or '\0'. Return -1 on
+ * error.
+ */
+ssize_t strtosz(const char *nptr, char **end)
+{
+    ssize_t retval = -1;
+    char *endptr, c;
+    int mul_required = 0;
+    double val, mul, integral, fraction;
+
+    errno = 0;
+    val = strtod(nptr,&endptr);
+    if (isnan(val) || endptr == nptr || errno != 0) {
+        goto fail;
+    }
+    integral = modf(val,&fraction);
+    if (integral != 0) {
+        mul_required = 1;
+    }
+    /*
+     * Any whitespace character is fine for terminating the number,
+     * in addition we accept ',' to handle strings where the size is
+     * part of a multi token argument.
+     */
+    c = *endptr;
+    if (isspace(c) || c == '\0' || c == ',') {
+        c = 0;
+    }
+    switch (c) {
+    case 'B':
+    case 'b':
+        mul = 1;
+        if (mul_required) {
+            goto fail;
+        }
+        break;
+    case 'K':
+    case 'k':
+        mul = 1<<  10;
+        break;
+    case 0:
+        if (mul_required) {
+            goto fail;
+        }
+    case 'M':
+    case 'm':
+        mul = 1ULL<<  20;
+        break;
+    case 'G':
+    case 'g':
+        mul = 1ULL<<  30;
+        break;
+    case 'T':
+    case 't':
+        mul = 1ULL<<  40;
+        break;
+    default:
+        goto fail;
+    }
+    /*
+     * If not terminated by whitespace, ',', or \0, increment endptr
+     * to point to next character, then check that we are terminated
+     * by an appropriate separating character, ie. whitespace, ',', or
+     * \0. If not, we are seeing trailing garbage, thus fail.
+     */
+    if (c != 0) {
+        endptr++;
+        if (!isspace(*endptr)&&  *endptr != ','&&  *endptr != 0) {
+            goto fail;
+        }
+    }
+    if ((val * mul>= ~(size_t)0) || val<  0) {
+        goto fail;
+    }
+    retval = val * mul;
+
+fail:
+    if (end) {
+        *end = endptr;
+    }
+
+    return retval;
+}
qemu-common.h +1 -0
index 81aafa0..0a062d4 100644
@@ -153,6 +153,7 @@ time_t mktimegm(struct tm *tm);
  int qemu_fls(int i);
  int qemu_fdatasync(int fd);
  int fcntl_setfl(int fd, int flag);
+ssize_t strtosz(const char *nptr, char **end);
 
  /* path.c */
  void init_paths(const char *prefix);
vl.c +9 -20
index df414ef..6043fa2 100644
@@ -734,16 +734,13 @@ static void numa_add(const char *optarg)
          if (get_param_value(option, 128, "mem", optarg) == 0) {
              node_mem[nodenr] = 0;
          } else {
-            value = strtoull(option,&endptr, 0);
-            switch (*endptr) {
-            case 0: case 'M': case 'm':
-                value<<= 20;
-                break;
-            case 'G': case 'g':
-                value<<= 30;
-                break;
+            ssize_t sval;
+            sval = strtosz(option, NULL);
+            if (sval<  0) {
+                fprintf(stderr, "qemu: invalid numa mem size: %s\n", optarg);
+                exit(1);
              }
-            node_mem[nodenr] = value;
+            node_mem[nodenr] = sval;
          }
          if (get_param_value(option, 128, "cpus", optarg) == 0) {
              node_cpumask[nodenr] = 0;
@@ -2163,18 +2160,10 @@ int main(int argc, char **argv, char **envp)
                  exit(0);
                  break;
              case QEMU_OPTION_m: {
-                uint64_t value;
-                char *ptr;
+                ssize_t value;
 
-                value = strtoul(optarg,&ptr, 10);
-                switch (*ptr) {
-                case 0: case 'M': case 'm':
-                    value<<= 20;
-                    break;
-                case 'G': case 'g':
-                    value<<= 30;
-                    break;
-                default:
+                value = strtosz(optarg, NULL);
+                if (value<  0) {
                      fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
                      exit(1);
                  }
#3 lore raw

PATCH v9 2/4 Add support for 'o' octet (bytes) format as monitor parameter.

In reply to [email protected]

From: Jes Sorensen <[email protected]>

Octet format relies on strtosz which supports K/k, M/m, G/g, T/t suffixes and unit support for humans, like 1.3G

---
 monitor.c |   29 +++++++++++++++++++++++++++++
 1 files changed, 29 insertions(+), 0 deletions(-)
monitor.c +29 -0
index 260cc02..6ef96a2 100644
@@ -78,6 +78,11 @@
  * 'l'          target long (32 or 64 bit)
  * 'M'          just like 'l', except in user mode the value is
  *              multiplied by 2^20 (think Mebibyte)
+ * 'o'          octets (aka bytes)
+ *              user mode accepts an optional T, t, G, g, M, m, K, k
+ *              suffix, which multiplies the value by 2^40 for
+ *              suffixes T and t, 2^30 for suffixes G and g, 2^20 for
+ *              M and m, 2^10 for K and k
  * 'f'          double
  *              user mode accepts an optional G, g, M, m, K, k suffix,
  *              which multiplies the value by 2^30 for suffixes G and
@@ -3703,6 +3708,29 @@ static const mon_cmd_t *monitor_parse_command(Monitor *mon,
                 qdict_put(qdict, key, qint_from_int(val));
             }
             break;
+        case 'o':
+            {
+                ssize_t val;
+                char *end;
+
+                while (qemu_isspace(*p)) {
+                    p++;
+                }
+                if (*typestr == '?') {
+                    typestr++;
+                    if (*p == '\0') {
+                        break;
+                    }
+                }
+                val = strtosz(p, &end);
+                if (val < 0) {
+                    monitor_printf(mon, "invalid size\n");
+                    goto fail;
+                }
+                qdict_put(qdict, key, qint_from_int(val));
+                p = end;
+            }
+            break;
         case 'f':
         case 'T':
             {
@@ -4200,6 +4228,7 @@ static int check_client_args_type(const QDict *client_args,
         case 'i':
         case 'l':
         case 'M':
+        case 'o':
             if (qobject_type(client_arg) != QTYPE_QINT) {
                 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
                               "int");
Signature · 1 line
1.7.2.3
#4 lore raw

PATCH v9 3/4 Switch migrate_set_speed() to take an 'o' argument rather than a float.

In reply to [email protected]

From: Jes Sorensen <[email protected]>

Clarify default value of MB in migration speed argument in monitor, if no suffix is specified. This differ from previous default of bytes, but is consistent with the rest of the places where we accept a size argument.

---
 hmp-commands.hx |    5 +++--
 migration.c     |    4 ++--
 2 files changed, 5 insertions(+), 4 deletions(-)
hmp-commands.hx +3 -2
index 81999aa..e5585ba 100644
@@ -754,9 +754,10 @@ ETEXI
 
     {
         .name       = "migrate_set_speed",
-        .args_type  = "value:f",
+        .args_type  = "value:o",
         .params     = "value",
-        .help       = "set maximum speed (in bytes) for migrations",
+        .help       = "set maximum speed (in bytes) for migrations. "
+	"Defaults to MB if no size suffix is specified, ie. B/K/M/G/T",
         .user_print = monitor_user_noop,
         .mhandler.cmd_new = do_migrate_set_speed,
     },
migration.c +2 -2
index 468d517..9ee8b17 100644
@@ -132,10 +132,10 @@ int do_migrate_cancel(Monitor *mon, const QDict *qdict, QObject **ret_data)
 
 int do_migrate_set_speed(Monitor *mon, const QDict *qdict, QObject **ret_data)
 {
-    double d;
+    int64_t d;
     FdMigrationState *s;
 
-    d = qdict_get_double(qdict, "value");
+    d = qdict_get_int(qdict, "value");
     d = MAX(0, MIN(UINT32_MAX, d));
     max_throttle = d;
 
Signature · 1 line
1.7.2.3
#5 lore raw

PATCH v9 4/4 Remove obsolete 'f' double parameter type

In reply to [email protected]

From: Jes Sorensen <[email protected]>

'f' double is no longer used, and we should be using floating point variables to store byte sizes. Remove it.

---
 monitor.c |   18 +-----------------
 1 files changed, 1 insertions(+), 17 deletions(-)
monitor.c +1 -17
index 6ef96a2..ae5355d 100644
@@ -83,10 +83,6 @@
  *              suffix, which multiplies the value by 2^40 for
  *              suffixes T and t, 2^30 for suffixes G and g, 2^20 for
  *              M and m, 2^10 for K and k
- * 'f'          double
- *              user mode accepts an optional G, g, M, m, K, k suffix,
- *              which multiplies the value by 2^30 for suffixes G and
- *              g, 2^20 for M and m, 2^10 for K and k
  * 'T'          double
  *              user mode accepts an optional ms, us, ns suffix,
  *              which divides the value by 1e3, 1e6, 1e9, respectively
@@ -3731,7 +3727,6 @@ static const mon_cmd_t *monitor_parse_command(Monitor *mon,
                 p = end;
             }
             break;
-        case 'f':
         case 'T':
             {
                 double val;
@@ -3747,17 +3742,7 @@ static const mon_cmd_t *monitor_parse_command(Monitor *mon,
                 if (get_double(mon, &val, &p) < 0) {
                     goto fail;
                 }
-                if (c == 'f' && *p) {
-                    switch (*p) {
-                    case 'K': case 'k':
-                        val *= 1 << 10; p++; break;
-                    case 'M': case 'm':
-                        val *= 1 << 20; p++; break;
-                    case 'G': case 'g':
-                        val *= 1 << 30; p++; break;
-                    }
-                }
-                if (c == 'T' && p[0] && p[1] == 's') {
+                if (p[0] && p[1] == 's') {
                     switch (*p) {
                     case 'm':
                         val /= 1e3; p += 2; break;
@@ -4235,7 +4220,6 @@ static int check_client_args_type(const QDict *client_args,
                 return -1; 
             }
             break;
-        case 'f':
         case 'T':
             if (qobject_type(client_arg) != QTYPE_QINT &&
                 qobject_type(client_arg) != QTYPE_QFLOAT) {
Signature · 1 line
1.7.2.3
#6 lore raw
In reply to [email protected]
Quoted 8 lines · [email protected] writes:

From: Jes Sorensen <[email protected]>

This patch introduces cutils.c: strtosz() and gets rid of the multiple custom hacks for parsing byte sizes. In addition it adds supports for specifying human style sizes such as 1.5G. Last it eliminates the horrible abuse of a float to store the byte size for migrate_set_speed in the monitor.

Quoted 5 lines

Note, this is tested on Linux and build tested for win32 using mingw32.

v9: I worked through a couple of revisions directly with Markus and I think I got it right finally.

I'd prefer to have strtosz() to match strtol() & friends and not restrict suffixes. But this code does what it claims to do, as far as I can see, so:

ACK series

#7 lore raw
Quoted 11 lines · Markus Armbruster
Quoted 10 lines · [email protected] writes:

From: Jes Sorensen <[email protected]>
This patch introduces cutils.c: strtosz() and gets rid of the multiple custom hacks for parsing byte sizes. In addition it adds supports for specifying human style sizes such as 1.5G. Last it eliminates the horrible abuse of a float to store the byte size for migrate_set_speed in the monitor.

Note, this is tested on Linux and build tested for win32 using mingw32.

Quoted 8 lines
Quoted 2 lines

v9: I worked through a couple of revisions directly with Markus and I think I got it right finally.

I'd prefer to have strtosz() to match strtol() & friends and not restrict suffixes. But this code does what it claims to do, as far as I can see, so:

ACK series

Thanks!

I thought about this a fair bit and I believe doing the full test in the function is the most valuable. It's a personal preference obviously. I think it's a win to do it here since it simplifies the caller code.

Would be great to get this applied so I can get it off my plate :)

Cheers,
Jes

#8 lore raw
Quoted 19 lines · Jes Sorensen
Quoted 18 lines · Markus Armbruster
Quoted 7 lines · [email protected] writes:

From: Jes Sorensen <[email protected]>
This patch introduces cutils.c: strtosz() and gets rid of the multiple custom hacks for parsing byte sizes. In addition it adds supports for specifying human style sizes such as 1.5G. Last it eliminates the horrible abuse of a float to store the byte size for migrate_set_speed in the monitor.

Quoted 5 lines

Note, this is tested on Linux and build tested for win32 using mingw32.

v9: I worked through a couple of revisions directly with Markus and I think I got it right finally.

I'd prefer to have strtosz() to match strtol() & friends and not restrict suffixes. But this code does what it claims to do, as far as I can see, so:

Quoted 7 lines
Quoted 1 line

ACK series

Thanks!

I thought about this a fair bit and I believe doing the full test in the function is the most valuable. It's a personal preference obviously. I think it's a win to do it here since it simplifies the caller code.

But strtosz() doesn't know what suffixes the caller wants accepted. It accepting suffixes starting with whitespace, '\0' and ',' is just a guess. Three cases:

1. The guess is exactly right. strtosz()'s checking saves the caller the check.

2. It's too lose, caller wants to accept fewer suffixes, e.g. just '\0'. strtosz()'s checking doesn't save the caller anything.

3. It's too tight, caller wants to accept more suffixes. Caller needs to make a copy without the suffix. In the general case, this requires duplicating strtosz()'s parsing logic. It's easier not to use it then.

The uses of strtosz() added by this series all fall into case 2. The callers lack the check, which means we accept trailing garbage. Fine with me, because it's no worse than before.

Quoted 1 line

Would be great to get this applied so I can get it off my plate :)

Agreed.