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