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