Whamcloud - gitweb
LU-17744 ldiskfs: mballoc stats fixes
[fs/lustre-release.git] / libcfs / libcfs / libcfs_string.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * String manipulation functions.
32  *
33  * libcfs/libcfs/libcfs_string.c
34  *
35  * Author: Nathan Rutman <nathan.rutman@sun.com>
36  */
37
38 #include <linux/ctype.h>
39 #include <libcfs/libcfs.h>
40 #include <libcfs/libcfs_string.h>
41
42 /* Convert a text string to a bitmask */
43 int cfs_str2mask(const char *str, const char *(*bit2str)(int bit),
44                  int *oldmask, int minmask, int allmask)
45 {
46         const char *debugstr;
47         char op = 0;
48         int newmask = minmask, i, len, found = 0;
49
50         ENTRY;
51         /* <str> must be a list of tokens separated by whitespace or comma,
52          * and optionally an operator ('+' or '-').  If an operator
53          * appears first in <str>, '*oldmask' is used as the starting point
54          * (relative), otherwise minmask is used (absolute).  An operator
55          * applies to all following tokens up to the next operator.
56          */
57         while (*str != 0) {
58                 while (isspace(*str) || *str == ',')
59                         str++;
60                 if (*str == 0)
61                         break;
62                 if (*str == '+' || *str == '-') {
63                         op = *str++;
64                         if (!found)
65                                 /* only if first token is relative */
66                                 newmask = *oldmask;
67                         while (isspace(*str))
68                                 str++;
69                         if (*str == 0)          /* trailing op */
70                                 return -EINVAL;
71                 }
72
73                 /* find token length */
74                 for (len = 0; str[len] != 0 && !isspace(str[len]) &&
75                         str[len] != '+' && str[len] != '-' && str[len] != ',';
76                      len++);
77
78                 /* match token */
79                 found = 0;
80                 for (i = 0; i < 32; i++) {
81                         debugstr = bit2str(i);
82                         if (debugstr != NULL &&
83                             strlen(debugstr) == len &&
84                             strncasecmp(str, debugstr, len) == 0) {
85                                 if (op == '-')
86                                         newmask &= ~BIT(i);
87                                 else
88                                         newmask |= BIT(i);
89                                 found = 1;
90                                 break;
91                         }
92                 }
93                 if (!found && len == 3 &&
94                     (strncasecmp(str, "ALL", len) == 0)) {
95                         if (op == '-')
96                                 newmask = minmask;
97                         else
98                                 newmask = allmask;
99                         found = 1;
100                 }
101                 if (!found) {
102                         CWARN("unknown mask '%.*s'.\n"
103                               "mask usage: [+|-]<all|type> ...\n", len, str);
104                         return -EINVAL;
105                 }
106                 str += len;
107         }
108
109         *oldmask = newmask;
110         return 0;
111 }
112 EXPORT_SYMBOL(cfs_str2mask);
113
114 /**
115  * Extracts tokens from strings.
116  *
117  * Looks for \a delim in string \a next, sets \a res to point to
118  * substring before the delimiter, sets \a next right after the found
119  * delimiter.
120  *
121  * \retval 1 if \a res points to a string of non-whitespace characters
122  * \retval 0 otherwise
123  */
124 int
125 cfs_gettok(struct cfs_lstr *next, char delim, struct cfs_lstr *res)
126 {
127         char *end;
128
129         if (next->ls_str == NULL)
130                 return 0;
131
132         /* skip leading white spaces */
133         while (next->ls_len) {
134                 if (!isspace(*next->ls_str))
135                         break;
136                 next->ls_str++;
137                 next->ls_len--;
138         }
139
140         if (next->ls_len == 0) /* whitespaces only */
141                 return 0;
142
143         if (*next->ls_str == delim) {
144                 /* first non-writespace is the delimiter */
145                 return 0;
146         }
147
148         res->ls_str = next->ls_str;
149         end = memchr(next->ls_str, delim, next->ls_len);
150         if (end == NULL) {
151                 /* there is no the delimeter in the string */
152                 end = next->ls_str + next->ls_len;
153                 next->ls_str = NULL;
154                 next->ls_len = 0;
155         } else {
156                 next->ls_str = end + 1;
157                 next->ls_len -= (end - res->ls_str + 1);
158         }
159
160         /* skip ending whitespaces */
161         while (--end != res->ls_str) {
162                 if (!isspace(*end))
163                         break;
164         }
165
166         res->ls_len = end - res->ls_str + 1;
167         return 1;
168 }
169 EXPORT_SYMBOL(cfs_gettok);
170
171 /**
172  * Converts string to integer.
173  *
174  * Accepts decimal and hexadecimal number recordings.
175  *
176  * \retval 1 if first \a nob chars of \a str convert to decimal or
177  * hexadecimal integer in the range [\a min, \a max]
178  * \retval 0 otherwise
179  */
180 int
181 cfs_str2num_check(char *str, int nob, unsigned *num,
182                   unsigned min, unsigned max)
183 {
184         bool all_numbers = true;
185         char *endp, cache;
186         int len;
187         int rc;
188
189         endp = strim(str);
190         /**
191          * kstrouint can only handle strings composed
192          * of only numbers. We need to scan the string
193          * passed in for the first non-digit character
194          * and end the string at that location. If we
195          * don't find any non-digit character we still
196          * need to place a '\0' at position len since
197          * we are not interested in the rest of the
198          * string which is longer than len in size.
199          * After we are done the character at the
200          * position we placed '\0' must be restored.
201          */
202         len = min((int)strlen(endp), nob);
203         for (; endp < str + len; endp++) {
204                 if (!isxdigit(*endp) && *endp != '-' &&
205                     *endp != '+') {
206                         all_numbers = false;
207                         break;
208                 }
209         }
210
211         /* Eat trailing space */
212         if (!all_numbers && isspace(*endp)) {
213                 all_numbers = true;
214                 endp--;
215         }
216
217         cache = *endp;
218         *endp = '\0';
219
220         rc = kstrtouint(str, 0, num);
221         *endp = cache;
222         if (rc || !all_numbers)
223                 return 0;
224
225         return (*num >= min && *num <= max);
226 }
227 EXPORT_SYMBOL(cfs_str2num_check);
228
229 /**
230  * Parses \<range_expr\> token of the syntax. If \a bracketed is false,
231  * \a src should only have a single token which can be \<number\> or  \*
232  *
233  * \retval pointer to allocated range_expr and initialized
234  * range_expr::re_lo, range_expr::re_hi and range_expr:re_stride if \a
235  `* src parses to
236  * \<number\> |
237  * \<number\> '-' \<number\> |
238  * \<number\> '-' \<number\> '/' \<number\>
239  * \retval 0 will be returned if it can be parsed, otherwise -EINVAL or
240  * -ENOMEM will be returned.
241  */
242 static int
243 cfs_range_expr_parse(struct cfs_lstr *src, unsigned min, unsigned max,
244                      int bracketed, struct cfs_range_expr **expr)
245 {
246         struct cfs_range_expr *re;
247         struct cfs_lstr tok;
248
249         LIBCFS_ALLOC(re, sizeof(*re));
250         if (re == NULL)
251                 return -ENOMEM;
252
253         if (src->ls_len == 1 && src->ls_str[0] == '*') {
254                 re->re_lo = min;
255                 re->re_hi = max;
256                 re->re_stride = 1;
257                 goto out;
258         }
259
260         if (cfs_str2num_check(src->ls_str, src->ls_len,
261                               &re->re_lo, min, max)) {
262                 /* <number> is parsed */
263                 re->re_hi = re->re_lo;
264                 re->re_stride = 1;
265                 goto out;
266         }
267
268         if (!bracketed || !cfs_gettok(src, '-', &tok))
269                 goto failed;
270
271         if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
272                                &re->re_lo, min, max))
273                 goto failed;
274
275         /* <number> - */
276         if (cfs_str2num_check(src->ls_str, src->ls_len,
277                               &re->re_hi, min, max)) {
278                 /* <number> - <number> is parsed */
279                 re->re_stride = 1;
280                 goto out;
281         }
282
283         /* go to check <number> '-' <number> '/' <number> */
284         if (cfs_gettok(src, '/', &tok)) {
285                 if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
286                                        &re->re_hi, min, max))
287                         goto failed;
288
289                 /* <number> - <number> / ... */
290                 if (cfs_str2num_check(src->ls_str, src->ls_len,
291                                       &re->re_stride, min, max)) {
292                         /* <number> - <number> / <number> is parsed */
293                         goto out;
294                 }
295         }
296
297 out:
298         *expr = re;
299         return 0;
300
301 failed:
302         LIBCFS_FREE(re, sizeof(*re));
303         return -EINVAL;
304 }
305
306 /**
307  * Print the range expression \a re into specified \a buffer.
308  * If \a bracketed is true, expression does not need additional
309  * brackets.
310  *
311  * \retval number of characters written
312  */
313 static int
314 cfs_range_expr_print(char *buffer, int count, struct cfs_range_expr *expr,
315                      bool bracketed)
316 {
317         int i;
318         char s[] = "[";
319         char e[] = "]";
320
321         if (bracketed)
322                 s[0] = e[0] = '\0';
323
324         if (expr->re_lo == expr->re_hi)
325                 i = scnprintf(buffer, count, "%u", expr->re_lo);
326         else if (expr->re_stride == 1)
327                 i = scnprintf(buffer, count, "%s%u-%u%s",
328                               s, expr->re_lo, expr->re_hi, e);
329         else
330                 i = scnprintf(buffer, count, "%s%u-%u/%u%s",
331                               s, expr->re_lo, expr->re_hi,
332                               expr->re_stride, e);
333         return i;
334 }
335
336 /**
337  * Print a list of range expressions (\a expr_list) into specified \a buffer.
338  * If the list contains several expressions, separate them with comma
339  * and surround the list with brackets.
340  *
341  * \retval number of characters written
342  */
343 int
344 cfs_expr_list_print(char *buffer, int count, struct cfs_expr_list *expr_list)
345 {
346         struct cfs_range_expr *expr;
347         int i = 0, j = 0;
348         int numexprs = 0;
349
350         if (count <= 0)
351                 return 0;
352
353         list_for_each_entry(expr, &expr_list->el_exprs, re_link)
354                 numexprs++;
355
356         if (numexprs > 1)
357                 i += scnprintf(buffer + i, count - i, "[");
358
359         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
360                 if (j++ != 0)
361                         i += scnprintf(buffer + i, count - i, ",");
362                 i += cfs_range_expr_print(buffer + i, count - i, expr,
363                                           numexprs > 1);
364         }
365
366         if (numexprs > 1)
367                 i += scnprintf(buffer + i, count - i, "]");
368
369         return i;
370 }
371 EXPORT_SYMBOL(cfs_expr_list_print);
372
373 /**
374  * Matches value (\a value) against ranges expression list \a expr_list.
375  *
376  * \retval 1 if \a value matches
377  * \retval 0 otherwise
378  */
379 int
380 cfs_expr_list_match(__u32 value, struct cfs_expr_list *expr_list)
381 {
382         struct cfs_range_expr *expr;
383
384         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
385                 if (value >= expr->re_lo && value <= expr->re_hi &&
386                     ((value - expr->re_lo) % expr->re_stride) == 0)
387                         return 1;
388         }
389
390         return 0;
391 }
392 EXPORT_SYMBOL(cfs_expr_list_match);
393
394 /**
395  * Convert express list (\a expr_list) to an array of all matched values
396  *
397  * \retval N N is total number of all matched values
398  * \retval 0 if expression list is empty
399  * \retval < 0 for failure
400  */
401 int
402 cfs_expr_list_values(struct cfs_expr_list *expr_list, int max, __u32 **valpp)
403 {
404         struct cfs_range_expr *expr;
405         __u32 *val;
406         int count = 0;
407         int i;
408
409         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
410                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
411                         if (((i - expr->re_lo) % expr->re_stride) == 0)
412                                 count++;
413                 }
414         }
415
416         if (count == 0) /* empty expression list */
417                 return 0;
418
419         if (count > max) {
420                 CERROR("Number of values %d exceeds max allowed %d\n",
421                        max, count);
422                 return -EINVAL;
423         }
424
425         CFS_ALLOC_PTR_ARRAY(val, count);
426         if (val == NULL)
427                 return -ENOMEM;
428
429         count = 0;
430         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
431                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
432                         if (((i - expr->re_lo) % expr->re_stride) == 0)
433                                 val[count++] = i;
434                 }
435         }
436
437         *valpp = val;
438         return count;
439 }
440 EXPORT_SYMBOL(cfs_expr_list_values);
441
442 void
443 cfs_expr_list_values_free(__u32 *values, int num)
444 {
445         /* This array is allocated by LIBCFS_ALLOC(), so it shouldn't be freed
446          * by OBD_FREE() if it's called by module other than libcfs & LNet,
447          * otherwise we will see fake memory leak */
448         CFS_FREE_PTR_ARRAY(values, num);
449 }
450 EXPORT_SYMBOL(cfs_expr_list_values_free);
451
452 /**
453  * Frees cfs_range_expr structures of \a expr_list.
454  *
455  * \retval none
456  */
457 void
458 cfs_expr_list_free(struct cfs_expr_list *expr_list)
459 {
460         while (!list_empty(&expr_list->el_exprs)) {
461                 struct cfs_range_expr *expr;
462
463                 expr = list_entry(expr_list->el_exprs.next,
464                                       struct cfs_range_expr, re_link);
465                 list_del(&expr->re_link);
466                 LIBCFS_FREE(expr, sizeof(*expr));
467         }
468
469         LIBCFS_FREE(expr_list, sizeof(*expr_list));
470 }
471 EXPORT_SYMBOL(cfs_expr_list_free);
472
473 /**
474  * Parses \<cfs_expr_list\> token of the syntax.
475  *
476  * \retval 0 if \a str parses to \<number\> | \<expr_list\>
477  * \retval -errno otherwise
478  */
479 int
480 cfs_expr_list_parse(char *str, int len, unsigned min, unsigned max,
481                     struct cfs_expr_list **elpp)
482 {
483         struct cfs_expr_list *expr_list;
484         struct cfs_range_expr *expr;
485         struct cfs_lstr src;
486         int rc;
487
488         LIBCFS_ALLOC(expr_list, sizeof(*expr_list));
489         if (expr_list == NULL)
490                 return -ENOMEM;
491
492         src.ls_str = str;
493         src.ls_len = len;
494
495         INIT_LIST_HEAD(&expr_list->el_exprs);
496
497         if (src.ls_str[0] == '[' &&
498             src.ls_str[src.ls_len - 1] == ']') {
499                 src.ls_str++;
500                 src.ls_len -= 2;
501
502                 rc = -EINVAL;
503                 while (src.ls_str != NULL) {
504                         struct cfs_lstr tok;
505
506                         if (!cfs_gettok(&src, ',', &tok)) {
507                                 rc = -EINVAL;
508                                 break;
509                         }
510
511                         rc = cfs_range_expr_parse(&tok, min, max, 1, &expr);
512                         if (rc != 0)
513                                 break;
514
515                         list_add_tail(&expr->re_link, &expr_list->el_exprs);
516                 }
517         } else {
518                 rc = cfs_range_expr_parse(&src, min, max, 0, &expr);
519                 if (rc == 0)
520                         list_add_tail(&expr->re_link, &expr_list->el_exprs);
521         }
522
523         if (rc != 0)
524                 cfs_expr_list_free(expr_list);
525         else
526                 *elpp = expr_list;
527
528         return rc;
529 }
530 EXPORT_SYMBOL(cfs_expr_list_parse);
531
532 /**
533  * Frees cfs_expr_list structures of \a list.
534  *
535  * For each struct cfs_expr_list structure found on \a list it frees
536  * range_expr list attached to it and frees the cfs_expr_list itself.
537  *
538  * \retval none
539  */
540 void
541 cfs_expr_list_free_list(struct list_head *list)
542 {
543         struct cfs_expr_list *el;
544
545         while (!list_empty(list)) {
546                 el = list_entry(list->next,
547                                     struct cfs_expr_list, el_link);
548                 list_del(&el->el_link);
549                 cfs_expr_list_free(el);
550         }
551 }
552 EXPORT_SYMBOL(cfs_expr_list_free_list);