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