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