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