Whamcloud - gitweb
08db676a3c8765bf02edcb649cc42bbbdabbc5ec
[fs/lustre-release.git] / lustre / obdclass / lprocfs_status.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) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 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  * lustre/obdclass/lprocfs_status.c
33  *
34  * Author: Hariharan Thantry <thantry@users.sourceforge.net>
35  */
36
37 #define DEBUG_SUBSYSTEM S_CLASS
38
39 #include <obd_class.h>
40 #include <lprocfs_status.h>
41 #include <lustre/lustre_idl.h>
42
43 #ifdef CONFIG_PROC_FS
44
45 static int lprocfs_no_percpu_stats = 0;
46 module_param(lprocfs_no_percpu_stats, int, 0644);
47 MODULE_PARM_DESC(lprocfs_no_percpu_stats, "Do not alloc percpu data for lprocfs stats");
48
49 #define MAX_STRING_SIZE 128
50
51 int lprocfs_single_release(struct inode *inode, struct file *file)
52 {
53         return single_release(inode, file);
54 }
55 EXPORT_SYMBOL(lprocfs_single_release);
56
57 int lprocfs_seq_release(struct inode *inode, struct file *file)
58 {
59         return seq_release(inode, file);
60 }
61 EXPORT_SYMBOL(lprocfs_seq_release);
62
63 struct proc_dir_entry *
64 lprocfs_add_simple(struct proc_dir_entry *root, char *name,
65                    void *data, const struct file_operations *fops)
66 {
67         struct proc_dir_entry *proc;
68         mode_t mode = 0;
69
70         if (root == NULL || name == NULL || fops == NULL)
71                 return ERR_PTR(-EINVAL);
72
73         if (fops->read)
74                 mode = 0444;
75         if (fops->write)
76                 mode |= 0200;
77         proc = proc_create_data(name, mode, root, fops, data);
78         if (!proc) {
79                 CERROR("LprocFS: No memory to create /proc entry %s\n",
80                        name);
81                 return ERR_PTR(-ENOMEM);
82         }
83         return proc;
84 }
85 EXPORT_SYMBOL(lprocfs_add_simple);
86
87 struct proc_dir_entry *lprocfs_add_symlink(const char *name,
88                         struct proc_dir_entry *parent, const char *format, ...)
89 {
90         struct proc_dir_entry *entry;
91         char *dest;
92         va_list ap;
93
94         if (parent == NULL || format == NULL)
95                 return NULL;
96
97         OBD_ALLOC_WAIT(dest, MAX_STRING_SIZE + 1);
98         if (dest == NULL)
99                 return NULL;
100
101         va_start(ap, format);
102         vsnprintf(dest, MAX_STRING_SIZE, format, ap);
103         va_end(ap);
104
105         entry = proc_symlink(name, parent, dest);
106         if (entry == NULL)
107                 CERROR("LprocFS: Could not create symbolic link from "
108                        "%s to %s\n", name, dest);
109
110         OBD_FREE(dest, MAX_STRING_SIZE + 1);
111         return entry;
112 }
113 EXPORT_SYMBOL(lprocfs_add_symlink);
114
115 static const struct file_operations lprocfs_generic_fops = { };
116
117 /**
118  * Add /proc entries.
119  *
120  * \param root [in]  The parent proc entry on which new entry will be added.
121  * \param list [in]  Array of proc entries to be added.
122  * \param data [in]  The argument to be passed when entries read/write routines
123  *                   are called through /proc file.
124  *
125  * \retval 0   on success
126  *         < 0 on error
127  */
128 int
129 lprocfs_add_vars(struct proc_dir_entry *root, struct lprocfs_vars *list,
130                  void *data)
131 {
132         if (root == NULL || list == NULL)
133                 return -EINVAL;
134
135         while (list->name != NULL) {
136                 struct proc_dir_entry *proc;
137                 mode_t mode = 0;
138
139                 if (list->proc_mode != 0000) {
140                         mode = list->proc_mode;
141                 } else if (list->fops) {
142                         if (list->fops->read)
143                                 mode = 0444;
144                         if (list->fops->write)
145                                 mode |= 0200;
146                 }
147                 proc = proc_create_data(list->name, mode, root,
148                                         list->fops ?: &lprocfs_generic_fops,
149                                         list->data ?: data);
150                 if (proc == NULL)
151                         return -ENOMEM;
152                 list++;
153         }
154         return 0;
155 }
156 EXPORT_SYMBOL(lprocfs_add_vars);
157
158 #ifndef HAVE_REMOVE_PROC_SUBTREE
159 /* for b=10866, global variable */
160 DECLARE_RWSEM(_lprocfs_lock);
161 EXPORT_SYMBOL(_lprocfs_lock);
162
163 static void lprocfs_remove_nolock(struct proc_dir_entry **proot)
164 {
165         struct proc_dir_entry *root = *proot;
166         struct proc_dir_entry *temp = root;
167         struct proc_dir_entry *rm_entry;
168         struct proc_dir_entry *parent;
169
170         *proot = NULL;
171         if (root == NULL || IS_ERR(root))
172                 return;
173
174         parent = root->parent;
175         LASSERT(parent != NULL);
176
177         while (1) {
178                 while (temp->subdir != NULL)
179                         temp = temp->subdir;
180
181                 rm_entry = temp;
182                 temp = temp->parent;
183
184                 /* Memory corruption once caused this to fail, and
185                    without this LASSERT we would loop here forever. */
186                 LASSERTF(strlen(rm_entry->name) == rm_entry->namelen,
187                          "0x%p  %s/%s len %d\n", rm_entry, temp->name,
188                          rm_entry->name, (int)strlen(rm_entry->name));
189
190                 remove_proc_entry(rm_entry->name, temp);
191                 if (temp == parent)
192                         break;
193         }
194 }
195
196 int remove_proc_subtree(const char *name, struct proc_dir_entry *parent)
197 {
198         struct proc_dir_entry    *t = NULL;
199         struct proc_dir_entry   **p;
200         int                       len, busy = 0;
201
202         LASSERT(parent != NULL);
203         len = strlen(name);
204
205         down_write(&_lprocfs_lock);
206         /* lookup target name */
207         for (p = &parent->subdir; *p; p = &(*p)->next) {
208                 if ((*p)->namelen != len)
209                         continue;
210                 if (memcmp(name, (*p)->name, len))
211                         continue;
212                 t = *p;
213                 break;
214         }
215
216         if (t) {
217                 /* verify it's empty: do not count "num_refs" */
218                 for (p = &t->subdir; *p; p = &(*p)->next) {
219                         if ((*p)->namelen != strlen("num_refs")) {
220                                 busy = 1;
221                                 break;
222                         }
223                         if (memcmp("num_refs", (*p)->name,
224                                    strlen("num_refs"))) {
225                                 busy = 1;
226                                 break;
227                         }
228                 }
229         }
230
231         if (busy == 0)
232                 lprocfs_remove_nolock(&t);
233
234         up_write(&_lprocfs_lock);
235         return 0;
236 }
237 #endif /* !HAVE_REMOVE_PROC_SUBTREE */
238
239 #ifndef HAVE_PROC_REMOVE
240 void proc_remove(struct proc_dir_entry *de)
241 {
242 #ifndef HAVE_REMOVE_PROC_SUBTREE
243         down_write(&_lprocfs_lock); /* search vs remove race */
244         lprocfs_remove_nolock(&de);
245         up_write(&_lprocfs_lock);
246 #else
247         if (de)
248                 remove_proc_subtree(de->name, de->parent);
249 #endif
250 }
251 #endif
252
253 void lprocfs_remove(struct proc_dir_entry **rooth)
254 {
255         proc_remove(*rooth);
256         *rooth = NULL;
257 }
258 EXPORT_SYMBOL(lprocfs_remove);
259
260 void lprocfs_remove_proc_entry(const char *name, struct proc_dir_entry *parent)
261 {
262         LASSERT(parent != NULL);
263         remove_proc_entry(name, parent);
264 }
265 EXPORT_SYMBOL(lprocfs_remove_proc_entry);
266
267 struct proc_dir_entry *
268 lprocfs_register(const char *name, struct proc_dir_entry *parent,
269                  struct lprocfs_vars *list, void *data)
270 {
271         struct proc_dir_entry *newchild;
272
273         newchild = proc_mkdir(name, parent);
274         if (newchild == NULL)
275                 return ERR_PTR(-ENOMEM);
276
277         if (list != NULL) {
278                 int rc = lprocfs_add_vars(newchild, list, data);
279                 if (rc) {
280                         lprocfs_remove(&newchild);
281                         return ERR_PTR(rc);
282                 }
283         }
284         return newchild;
285 }
286 EXPORT_SYMBOL(lprocfs_register);
287
288 /* Generic callbacks */
289 int lprocfs_uint_seq_show(struct seq_file *m, void *data)
290 {
291         seq_printf(m, "%u\n", *(unsigned int *)data);
292         return 0;
293 }
294 EXPORT_SYMBOL(lprocfs_uint_seq_show);
295
296 int lprocfs_wr_uint(struct file *file, const char __user *buffer,
297                     unsigned long count, void *data)
298 {
299         unsigned        *p = data;
300         char             dummy[MAX_STRING_SIZE + 1];
301         char            *end;
302         unsigned long    tmp;
303
304         if (count >= sizeof(dummy))
305                 return -EINVAL;
306
307         if (count == 0)
308                 return 0;
309
310         if (copy_from_user(dummy, buffer, count))
311                 return -EFAULT;
312
313         dummy[count] = 0;
314
315         tmp = simple_strtoul(dummy, &end, 0);
316         if (dummy == end)
317                 return -EINVAL;
318
319         *p = (unsigned int)tmp;
320         return count;
321 }
322 EXPORT_SYMBOL(lprocfs_wr_uint);
323
324 ssize_t lprocfs_uint_seq_write(struct file *file, const char __user *buffer,
325                                size_t count, loff_t *off)
326 {
327         int *data = ((struct seq_file *)file->private_data)->private;
328         int rc;
329         __s64 val = 0;
330
331         rc = lprocfs_str_to_s64(buffer, count, &val);
332         if (rc < 0)
333                 return rc;
334
335         return lprocfs_wr_uint(file, buffer, count, data);
336 }
337 EXPORT_SYMBOL(lprocfs_uint_seq_write);
338
339 int lprocfs_u64_seq_show(struct seq_file *m, void *data)
340 {
341         LASSERT(data != NULL);
342         seq_printf(m, "%llu\n", *(__u64 *)data);
343         return 0;
344 }
345 EXPORT_SYMBOL(lprocfs_u64_seq_show);
346
347 int lprocfs_atomic_seq_show(struct seq_file *m, void *data)
348 {
349         atomic_t *atom = data;
350         LASSERT(atom != NULL);
351         seq_printf(m, "%d\n", atomic_read(atom));
352         return 0;
353 }
354 EXPORT_SYMBOL(lprocfs_atomic_seq_show);
355
356 ssize_t
357 lprocfs_atomic_seq_write(struct file *file, const char __user *buffer,
358                         size_t count, loff_t *off)
359 {
360         atomic_t *atm = ((struct seq_file *)file->private_data)->private;
361         __s64 val = 0;
362         int rc;
363
364         rc = lprocfs_str_to_s64(buffer, count, &val);
365         if (rc < 0)
366                 return rc;
367
368         if (val <= 0 || val > INT_MAX)
369                 return -ERANGE;
370
371         atomic_set(atm, val);
372         return count;
373 }
374 EXPORT_SYMBOL(lprocfs_atomic_seq_write);
375
376 int lprocfs_uuid_seq_show(struct seq_file *m, void *data)
377 {
378         struct obd_device *obd = data;
379
380         LASSERT(obd != NULL);
381         seq_printf(m, "%s\n", obd->obd_uuid.uuid);
382         return 0;
383 }
384 EXPORT_SYMBOL(lprocfs_uuid_seq_show);
385
386 int lprocfs_name_seq_show(struct seq_file *m, void *data)
387 {
388         struct obd_device *dev = data;
389
390         LASSERT(dev != NULL);
391         seq_printf(m, "%s\n", dev->obd_name);
392         return 0;
393 }
394 EXPORT_SYMBOL(lprocfs_name_seq_show);
395
396 int lprocfs_blksize_seq_show(struct seq_file *m, void *data)
397 {
398         struct obd_device *obd = data;
399         struct obd_statfs  osfs;
400         int rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
401                             cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS),
402                             OBD_STATFS_NODELAY);
403         if (!rc)
404                 seq_printf(m, "%u\n", osfs.os_bsize);
405         return rc;
406 }
407 EXPORT_SYMBOL(lprocfs_blksize_seq_show);
408
409 int lprocfs_kbytestotal_seq_show(struct seq_file *m, void *data)
410 {
411         struct obd_device *obd = data;
412         struct obd_statfs  osfs;
413         int rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
414                             cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS),
415                             OBD_STATFS_NODELAY);
416         if (!rc) {
417                 __u32 blk_size = osfs.os_bsize >> 10;
418                 __u64 result = osfs.os_blocks;
419
420                 while (blk_size >>= 1)
421                         result <<= 1;
422
423                 seq_printf(m, "%llu\n", result);
424         }
425         return rc;
426 }
427 EXPORT_SYMBOL(lprocfs_kbytestotal_seq_show);
428
429 int lprocfs_kbytesfree_seq_show(struct seq_file *m, void *data)
430 {
431         struct obd_device *obd = data;
432         struct obd_statfs  osfs;
433         int rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
434                             cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS),
435                             OBD_STATFS_NODELAY);
436         if (!rc) {
437                 __u32 blk_size = osfs.os_bsize >> 10;
438                 __u64 result = osfs.os_bfree;
439
440                 while (blk_size >>= 1)
441                         result <<= 1;
442
443                 seq_printf(m, "%llu\n", result);
444         }
445         return rc;
446 }
447 EXPORT_SYMBOL(lprocfs_kbytesfree_seq_show);
448
449 int lprocfs_kbytesavail_seq_show(struct seq_file *m, void *data)
450 {
451         struct obd_device *obd = data;
452         struct obd_statfs  osfs;
453         int rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
454                             cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS),
455                             OBD_STATFS_NODELAY);
456         if (!rc) {
457                 __u32 blk_size = osfs.os_bsize >> 10;
458                 __u64 result = osfs.os_bavail;
459
460                 while (blk_size >>= 1)
461                         result <<= 1;
462
463                 seq_printf(m, "%llu\n", result);
464         }
465         return rc;
466 }
467 EXPORT_SYMBOL(lprocfs_kbytesavail_seq_show);
468
469 int lprocfs_filestotal_seq_show(struct seq_file *m, void *data)
470 {
471         struct obd_device *obd = data;
472         struct obd_statfs  osfs;
473         int rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
474                             cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS),
475                             OBD_STATFS_NODELAY);
476         if (!rc)
477                 seq_printf(m, "%llu\n", osfs.os_files);
478         return rc;
479 }
480 EXPORT_SYMBOL(lprocfs_filestotal_seq_show);
481
482 int lprocfs_filesfree_seq_show(struct seq_file *m, void *data)
483 {
484         struct obd_device *obd = data;
485         struct obd_statfs  osfs;
486         int rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
487                             cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS),
488                             OBD_STATFS_NODELAY);
489         if (!rc)
490                 seq_printf(m, "%llu\n", osfs.os_ffree);
491         return rc;
492 }
493 EXPORT_SYMBOL(lprocfs_filesfree_seq_show);
494
495 int lprocfs_server_uuid_seq_show(struct seq_file *m, void *data)
496 {
497         struct obd_device *obd = data;
498         struct obd_import *imp;
499         char *imp_state_name = NULL;
500         int rc = 0;
501
502         LASSERT(obd != NULL);
503         LPROCFS_CLIMP_CHECK(obd);
504         imp = obd->u.cli.cl_import;
505         imp_state_name = ptlrpc_import_state_name(imp->imp_state);
506         seq_printf(m, "%s\t%s%s\n", obd2cli_tgt(obd), imp_state_name,
507                    imp->imp_deactive ? "\tDEACTIVATED" : "");
508
509         LPROCFS_CLIMP_EXIT(obd);
510         return rc;
511 }
512 EXPORT_SYMBOL(lprocfs_server_uuid_seq_show);
513
514 int lprocfs_conn_uuid_seq_show(struct seq_file *m, void *data)
515 {
516         struct obd_device *obd = data;
517         struct ptlrpc_connection *conn;
518         int rc = 0;
519
520         LASSERT(obd != NULL);
521
522         LPROCFS_CLIMP_CHECK(obd);
523         conn = obd->u.cli.cl_import->imp_connection;
524         if (conn && obd->u.cli.cl_import)
525                 seq_printf(m, "%s\n", conn->c_remote_uuid.uuid);
526         else
527                 seq_printf(m, "%s\n", "<none>");
528
529         LPROCFS_CLIMP_EXIT(obd);
530         return rc;
531 }
532 EXPORT_SYMBOL(lprocfs_conn_uuid_seq_show);
533
534 /** add up per-cpu counters */
535 void lprocfs_stats_collect(struct lprocfs_stats *stats, int idx,
536                            struct lprocfs_counter *cnt)
537 {
538         unsigned int                    num_entry;
539         struct lprocfs_counter          *percpu_cntr;
540         int                             i;
541         unsigned long                   flags = 0;
542
543         memset(cnt, 0, sizeof(*cnt));
544
545         if (stats == NULL) {
546                 /* set count to 1 to avoid divide-by-zero errs in callers */
547                 cnt->lc_count = 1;
548                 return;
549         }
550
551         cnt->lc_min = LC_MIN_INIT;
552
553         num_entry = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
554
555         for (i = 0; i < num_entry; i++) {
556                 if (stats->ls_percpu[i] == NULL)
557                         continue;
558                 percpu_cntr = lprocfs_stats_counter_get(stats, i, idx);
559
560                 cnt->lc_count += percpu_cntr->lc_count;
561                 cnt->lc_sum += percpu_cntr->lc_sum;
562                 if (percpu_cntr->lc_min < cnt->lc_min)
563                         cnt->lc_min = percpu_cntr->lc_min;
564                 if (percpu_cntr->lc_max > cnt->lc_max)
565                         cnt->lc_max = percpu_cntr->lc_max;
566                 cnt->lc_sumsquare += percpu_cntr->lc_sumsquare;
567         }
568
569         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
570 }
571
572 /**
573  * Append a space separated list of current set flags to str.
574  */
575 #define flag2str(flag)                                          \
576         do {                                                            \
577                 if (imp->imp_##flag) {                                  \
578                         seq_printf(m, "%s" #flag, first ? "" : ", ");   \
579                         first = false;                                  \
580                 }                                                       \
581         } while (0)
582 static void obd_import_flags2str(struct obd_import *imp, struct seq_file *m)
583 {
584         bool first = true;
585
586         if (imp->imp_obd->obd_no_recov) {
587                 seq_printf(m, "no_recov");
588                 first = false;
589         }
590
591         flag2str(invalid);
592         flag2str(deactive);
593         flag2str(replayable);
594         flag2str(delayed_recovery);
595         flag2str(no_lock_replay);
596         flag2str(vbr_failed);
597         flag2str(pingable);
598         flag2str(resend_replay);
599         flag2str(no_pinger_recover);
600         flag2str(need_mne_swab);
601         flag2str(connect_tried);
602 }
603 #undef flag2str
604
605 static const char *obd_connect_names[] = {
606         /* flags names  */
607         "read_only",
608         "lov_index",
609         "connect_from_mds",
610         "write_grant",
611         "server_lock",
612         "version",
613         "request_portal",
614         "acl",
615         "xattr",
616         "create_on_write",
617         "truncate_lock",
618         "initial_transno",
619         "inode_bit_locks",
620         "join_file(obsolete)",
621         "getattr_by_fid",
622         "no_oh_for_devices",
623         "remote_client",
624         "remote_client_by_force",
625         "max_byte_per_rpc",
626         "64bit_qdata",
627         "mds_capability",
628         "oss_capability",
629         "early_lock_cancel",
630         "som",
631         "adaptive_timeouts",
632         "lru_resize",
633         "mds_mds_connection",
634         "real_conn",
635         "change_qunit_size",
636         "alt_checksum_algorithm",
637         "fid_is_enabled",
638         "version_recovery",
639         "pools",
640         "grant_shrink",
641         "skip_orphan",
642         "large_ea",
643         "full20",
644         "layout_lock",
645         "64bithash",
646         "object_max_bytes",
647         "imp_recov",
648         "jobstats",
649         "umask",
650         "einprogress",
651         "grant_param",
652         "flock_owner",
653         "lvb_type",
654         "nanoseconds_times",
655         "lightweight_conn",
656         "short_io",
657         "pingless",
658         "flock_deadlock",
659         "disp_stripe",
660         "open_by_fid",
661         "lfsck",
662         "unknown",
663         "unlink_close",
664         "multi_mod_rpcs",
665         "dir_stripe",
666         "subtree",
667         "lock_ahead",
668         "bulk_mbits",
669         "compact_obdo",
670         "second_flags",
671         /* flags2 names */
672         "file_secctx",
673         NULL
674 };
675
676 static void obd_connect_seq_flags2str(struct seq_file *m, __u64 flags,
677                                       __u64 flags2, const char *sep)
678 {
679         bool first = true;
680         __u64 mask;
681         int i;
682
683         for (i = 0, mask = 1; i < 64; i++, mask <<= 1) {
684                 if (flags & mask) {
685                         seq_printf(m, "%s%s",
686                                    first ? "" : sep, obd_connect_names[i]);
687                         first = false;
688                 }
689         }
690
691         if (flags & ~(mask - 1)) {
692                 seq_printf(m, "%sunknown_%#llx",
693                            first ? "" : sep, flags & ~(mask - 1));
694                 first = false;
695         }
696
697         if (!(flags & OBD_CONNECT_FLAGS2) || flags2 == 0)
698                 return;
699
700         for (i = 64, mask = 1; obd_connect_names[i] != NULL; i++, mask <<= 1) {
701                 if (flags2 & mask) {
702                         seq_printf(m, "%s%s",
703                                    first ? "" : sep, obd_connect_names[i]);
704                         first = false;
705                 }
706         }
707
708         if (flags2 & ~(mask - 1)) {
709                 seq_printf(m, "%sunknown2_%#llx",
710                            first ? "" : sep, flags2 & ~(mask - 1));
711                 first = false;
712         }
713 }
714
715 int obd_connect_flags2str(char *page, int count, __u64 flags, __u64 flags2,
716                           const char *sep)
717 {
718         __u64 mask;
719         int i, ret = 0;
720
721         for (i = 0, mask = 1; i < 64; i++, mask <<= 1) {
722                 if (flags & mask)
723                         ret += snprintf(page + ret, count - ret, "%s%s",
724                                         ret ? sep : "", obd_connect_names[i]);
725         }
726
727         if (flags & ~(mask - 1))
728                 ret += snprintf(page + ret, count - ret,
729                                 "%sunknown_%#llx",
730                                 ret ? sep : "", flags & ~(mask - 1));
731
732         if (!(flags & OBD_CONNECT_FLAGS2) || flags2 == 0)
733                 return ret;
734
735         for (i = 64, mask = 1; obd_connect_names[i] != NULL; i++, mask <<= 1) {
736                 if (flags2 & mask)
737                         ret += snprintf(page + ret, count - ret, "%s%s",
738                                         ret ? sep : "", obd_connect_names[i]);
739         }
740
741         if (flags2 & ~(mask - 1))
742                 ret += snprintf(page + ret, count - ret,
743                                 "%sunknown2_%#llx",
744                                 ret ? sep : "", flags2 & ~(mask - 1));
745
746         return ret;
747 }
748 EXPORT_SYMBOL(obd_connect_flags2str);
749
750 static void obd_connect_data_seqprint(struct seq_file *m,
751                                       struct obd_connect_data *ocd)
752 {
753         __u64 flags;
754
755         LASSERT(ocd != NULL);
756         flags = ocd->ocd_connect_flags;
757
758         seq_printf(m, "    connect_data:\n"
759                    "       flags: %#llx\n"
760                    "       instance: %u\n",
761                    ocd->ocd_connect_flags,
762                    ocd->ocd_instance);
763         if (flags & OBD_CONNECT_VERSION)
764                 seq_printf(m, "       target_version: %u.%u.%u.%u\n",
765                            OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
766                            OBD_OCD_VERSION_MINOR(ocd->ocd_version),
767                            OBD_OCD_VERSION_PATCH(ocd->ocd_version),
768                            OBD_OCD_VERSION_FIX(ocd->ocd_version));
769         if (flags & OBD_CONNECT_MDS)
770                 seq_printf(m, "       mdt_index: %d\n", ocd->ocd_group);
771         if (flags & OBD_CONNECT_GRANT)
772                 seq_printf(m, "       initial_grant: %d\n", ocd->ocd_grant);
773         if (flags & OBD_CONNECT_INDEX)
774                 seq_printf(m, "       target_index: %u\n", ocd->ocd_index);
775         if (flags & OBD_CONNECT_BRW_SIZE)
776                 seq_printf(m, "       max_brw_size: %d\n", ocd->ocd_brw_size);
777         if (flags & OBD_CONNECT_IBITS)
778                 seq_printf(m, "       ibits_known: %#llx\n",
779                            ocd->ocd_ibits_known);
780         if (flags & OBD_CONNECT_GRANT_PARAM)
781                 seq_printf(m, "       grant_block_size: %d\n"
782                            "       grant_inode_size: %d\n"
783                            "       grant_max_extent_size: %d\n"
784                            "       grant_extent_tax: %d\n",
785                            1 << ocd->ocd_grant_blkbits,
786                            1 << ocd->ocd_grant_inobits,
787                            ocd->ocd_grant_max_blks << ocd->ocd_grant_blkbits,
788                            ocd->ocd_grant_tax_kb << 10);
789         if (flags & OBD_CONNECT_TRANSNO)
790                 seq_printf(m, "       first_transno: %#llx\n",
791                            ocd->ocd_transno);
792         if (flags & OBD_CONNECT_CKSUM)
793                 seq_printf(m, "       cksum_types: %#x\n",
794                            ocd->ocd_cksum_types);
795         if (flags & OBD_CONNECT_MAX_EASIZE)
796                 seq_printf(m, "       max_easize: %d\n", ocd->ocd_max_easize);
797         if (flags & OBD_CONNECT_MAXBYTES)
798                 seq_printf(m, "       max_object_bytes: %llu\n",
799                            ocd->ocd_maxbytes);
800         if (flags & OBD_CONNECT_MULTIMODRPCS)
801                 seq_printf(m, "       max_mod_rpcs: %hu\n",
802                            ocd->ocd_maxmodrpcs);
803 }
804
805 int lprocfs_import_seq_show(struct seq_file *m, void *data)
806 {
807         char                            nidstr[LNET_NIDSTR_SIZE];
808         struct lprocfs_counter          ret;
809         struct lprocfs_counter_header   *header;
810         struct obd_device               *obd    = (struct obd_device *)data;
811         struct obd_import               *imp;
812         struct obd_import_conn          *conn;
813         struct obd_connect_data         *ocd;
814         int                             j;
815         int                             k;
816         int                             rw      = 0;
817
818         LASSERT(obd != NULL);
819         LPROCFS_CLIMP_CHECK(obd);
820         imp = obd->u.cli.cl_import;
821         ocd = &imp->imp_connect_data;
822
823         seq_printf(m, "import:\n"
824                    "    name: %s\n"
825                    "    target: %s\n"
826                    "    state: %s\n"
827                    "    connect_flags: [ ",
828                    obd->obd_name,
829                    obd2cli_tgt(obd),
830                    ptlrpc_import_state_name(imp->imp_state));
831         obd_connect_seq_flags2str(m, imp->imp_connect_data.ocd_connect_flags,
832                                   imp->imp_connect_data.ocd_connect_flags2,
833                                   ", ");
834         seq_printf(m, " ]\n");
835         obd_connect_data_seqprint(m, ocd);
836         seq_printf(m, "    import_flags: [ ");
837         obd_import_flags2str(imp, m);
838
839         seq_printf(m, " ]\n"
840                    "    connection:\n"
841                    "       failover_nids: [ ");
842         spin_lock(&imp->imp_lock);
843         j = 0;
844         list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
845                 libcfs_nid2str_r(conn->oic_conn->c_peer.nid,
846                                  nidstr, sizeof(nidstr));
847                 seq_printf(m, "%s%s", j ? ", " : "", nidstr);
848                 j++;
849         }
850         if (imp->imp_connection != NULL)
851                 libcfs_nid2str_r(imp->imp_connection->c_peer.nid,
852                                  nidstr, sizeof(nidstr));
853         else
854                 strncpy(nidstr, "<none>", sizeof(nidstr));
855         seq_printf(m, " ]\n"
856                    "       current_connection: %s\n"
857                    "       connection_attempts: %u\n"
858                    "       generation: %u\n"
859                    "       in-progress_invalidations: %u\n",
860                    nidstr,
861                    imp->imp_conn_cnt,
862                    imp->imp_generation,
863                    atomic_read(&imp->imp_inval_count));
864         spin_unlock(&imp->imp_lock);
865
866         if (obd->obd_svc_stats == NULL)
867                 goto out_climp;
868
869         header = &obd->obd_svc_stats->ls_cnt_header[PTLRPC_REQWAIT_CNTR];
870         lprocfs_stats_collect(obd->obd_svc_stats, PTLRPC_REQWAIT_CNTR, &ret);
871         if (ret.lc_count != 0) {
872                 /* first argument to do_div MUST be __u64 */
873                 __u64 sum = ret.lc_sum;
874                 do_div(sum, ret.lc_count);
875                 ret.lc_sum = sum;
876         } else
877                 ret.lc_sum = 0;
878         seq_printf(m, "    rpcs:\n"
879                    "       inflight: %u\n"
880                    "       unregistering: %u\n"
881                    "       timeouts: %u\n"
882                    "       avg_waittime: %llu %s\n",
883                    atomic_read(&imp->imp_inflight),
884                    atomic_read(&imp->imp_unregistering),
885                    atomic_read(&imp->imp_timeouts),
886                    ret.lc_sum, header->lc_units);
887
888         k = 0;
889         for(j = 0; j < IMP_AT_MAX_PORTALS; j++) {
890                 if (imp->imp_at.iat_portal[j] == 0)
891                         break;
892                 k = max_t(unsigned int, k,
893                           at_get(&imp->imp_at.iat_service_estimate[j]));
894         }
895         seq_printf(m, "    service_estimates:\n"
896                    "       services: %u sec\n"
897                    "       network: %u sec\n",
898                    k,
899                    at_get(&imp->imp_at.iat_net_latency));
900
901         seq_printf(m, "    transactions:\n"
902                    "       last_replay: %llu\n"
903                    "       peer_committed: %llu\n"
904                    "       last_checked: %llu\n",
905                    imp->imp_last_replay_transno,
906                    imp->imp_peer_committed_transno,
907                    imp->imp_last_transno_checked);
908
909         /* avg data rates */
910         for (rw = 0; rw <= 1; rw++) {
911                 lprocfs_stats_collect(obd->obd_svc_stats,
912                                       PTLRPC_LAST_CNTR + BRW_READ_BYTES + rw,
913                                       &ret);
914                 if (ret.lc_sum > 0 && ret.lc_count > 0) {
915                         /* first argument to do_div MUST be __u64 */
916                         __u64 sum = ret.lc_sum;
917                         do_div(sum, ret.lc_count);
918                         ret.lc_sum = sum;
919                         seq_printf(m, "    %s_data_averages:\n"
920                                    "       bytes_per_rpc: %llu\n",
921                                    rw ? "write" : "read",
922                                    ret.lc_sum);
923                 }
924                 k = (int)ret.lc_sum;
925                 j = opcode_offset(OST_READ + rw) + EXTRA_MAX_OPCODES;
926                 header = &obd->obd_svc_stats->ls_cnt_header[j];
927                 lprocfs_stats_collect(obd->obd_svc_stats, j, &ret);
928                 if (ret.lc_sum > 0 && ret.lc_count != 0) {
929                         /* first argument to do_div MUST be __u64 */
930                         __u64 sum = ret.lc_sum;
931                         do_div(sum, ret.lc_count);
932                         ret.lc_sum = sum;
933                         seq_printf(m, "       %s_per_rpc: %llu\n",
934                                    header->lc_units, ret.lc_sum);
935                         j = (int)ret.lc_sum;
936                         if (j > 0)
937                                 seq_printf(m, "       MB_per_sec: %u.%.02u\n",
938                                            k / j, (100 * k / j) % 100);
939                 }
940         }
941
942 out_climp:
943         LPROCFS_CLIMP_EXIT(obd);
944         return 0;
945 }
946 EXPORT_SYMBOL(lprocfs_import_seq_show);
947
948 int lprocfs_state_seq_show(struct seq_file *m, void *data)
949 {
950         struct obd_device *obd = (struct obd_device *)data;
951         struct obd_import *imp;
952         int j, k;
953
954         LASSERT(obd != NULL);
955         LPROCFS_CLIMP_CHECK(obd);
956         imp = obd->u.cli.cl_import;
957
958         seq_printf(m, "current_state: %s\n",
959                    ptlrpc_import_state_name(imp->imp_state));
960         seq_printf(m, "state_history:\n");
961         k = imp->imp_state_hist_idx;
962         for (j = 0; j < IMP_STATE_HIST_LEN; j++) {
963                 struct import_state_hist *ish =
964                         &imp->imp_state_hist[(k + j) % IMP_STATE_HIST_LEN];
965                 if (ish->ish_state == 0)
966                         continue;
967                 seq_printf(m, " - [ "CFS_TIME_T", %s ]\n",
968                            ish->ish_time,
969                 ptlrpc_import_state_name(ish->ish_state));
970         }
971
972         LPROCFS_CLIMP_EXIT(obd);
973         return 0;
974 }
975 EXPORT_SYMBOL(lprocfs_state_seq_show);
976
977 int lprocfs_at_hist_helper(struct seq_file *m, struct adaptive_timeout *at)
978 {
979         int i;
980         for (i = 0; i < AT_BINS; i++)
981                 seq_printf(m, "%3u ", at->at_hist[i]);
982         seq_printf(m, "\n");
983         return 0;
984 }
985 EXPORT_SYMBOL(lprocfs_at_hist_helper);
986
987 /* See also ptlrpc_lprocfs_timeouts_show_seq */
988 int lprocfs_timeouts_seq_show(struct seq_file *m, void *data)
989 {
990         struct obd_device *obd = (struct obd_device *)data;
991         struct obd_import *imp;
992         unsigned int cur, worst;
993         time_t now, worstt;
994         struct dhms ts;
995         int i;
996
997         LASSERT(obd != NULL);
998         LPROCFS_CLIMP_CHECK(obd);
999         imp = obd->u.cli.cl_import;
1000
1001         now = cfs_time_current_sec();
1002
1003         /* Some network health info for kicks */
1004         s2dhms(&ts, now - imp->imp_last_reply_time);
1005         seq_printf(m, "%-10s : %ld, "DHMS_FMT" ago\n",
1006                    "last reply", imp->imp_last_reply_time, DHMS_VARS(&ts));
1007
1008         cur = at_get(&imp->imp_at.iat_net_latency);
1009         worst = imp->imp_at.iat_net_latency.at_worst_ever;
1010         worstt = imp->imp_at.iat_net_latency.at_worst_time;
1011         s2dhms(&ts, now - worstt);
1012         seq_printf(m, "%-10s : cur %3u  worst %3u (at %ld, "DHMS_FMT" ago) ",
1013                    "network", cur, worst, worstt, DHMS_VARS(&ts));
1014         lprocfs_at_hist_helper(m, &imp->imp_at.iat_net_latency);
1015
1016         for(i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1017                 if (imp->imp_at.iat_portal[i] == 0)
1018                         break;
1019                 cur = at_get(&imp->imp_at.iat_service_estimate[i]);
1020                 worst = imp->imp_at.iat_service_estimate[i].at_worst_ever;
1021                 worstt = imp->imp_at.iat_service_estimate[i].at_worst_time;
1022                 s2dhms(&ts, now - worstt);
1023                 seq_printf(m, "portal %-2d  : cur %3u  worst %3u (at %ld, "
1024                            DHMS_FMT" ago) ", imp->imp_at.iat_portal[i],
1025                            cur, worst, worstt, DHMS_VARS(&ts));
1026                 lprocfs_at_hist_helper(m, &imp->imp_at.iat_service_estimate[i]);
1027         }
1028
1029         LPROCFS_CLIMP_EXIT(obd);
1030         return 0;
1031 }
1032 EXPORT_SYMBOL(lprocfs_timeouts_seq_show);
1033
1034 int lprocfs_connect_flags_seq_show(struct seq_file *m, void *data)
1035 {
1036         struct obd_device *obd = data;
1037         __u64 flags;
1038         __u64 flags2;
1039
1040         LPROCFS_CLIMP_CHECK(obd);
1041         flags = obd->u.cli.cl_import->imp_connect_data.ocd_connect_flags;
1042         flags2 = obd->u.cli.cl_import->imp_connect_data.ocd_connect_flags2;
1043         seq_printf(m, "flags=%#llx\n", flags);
1044         seq_printf(m, "flags2=%#llx\n", flags2);
1045         obd_connect_seq_flags2str(m, flags, flags2, "\n");
1046         seq_printf(m, "\n");
1047         LPROCFS_CLIMP_EXIT(obd);
1048         return 0;
1049 }
1050 EXPORT_SYMBOL(lprocfs_connect_flags_seq_show);
1051
1052 int
1053 lprocfs_obd_setup(struct obd_device *obd)
1054 {
1055         int rc = 0;
1056
1057         LASSERT(obd != NULL);
1058         LASSERT(obd->obd_magic == OBD_DEVICE_MAGIC);
1059         LASSERT(obd->obd_type->typ_procroot != NULL);
1060
1061         obd->obd_proc_entry = lprocfs_register(obd->obd_name,
1062                                                obd->obd_type->typ_procroot,
1063                                                obd->obd_vars, obd);
1064         if (IS_ERR(obd->obd_proc_entry)) {
1065                 rc = PTR_ERR(obd->obd_proc_entry);
1066                 CERROR("error %d setting up lprocfs for %s\n",rc,obd->obd_name);
1067                 obd->obd_proc_entry = NULL;
1068         }
1069         return rc;
1070 }
1071 EXPORT_SYMBOL(lprocfs_obd_setup);
1072
1073 int lprocfs_obd_cleanup(struct obd_device *obd)
1074 {
1075         if (!obd)
1076                 return -EINVAL;
1077         if (obd->obd_proc_exports_entry) {
1078                 /* Should be no exports left */
1079                 lprocfs_remove(&obd->obd_proc_exports_entry);
1080                 obd->obd_proc_exports_entry = NULL;
1081         }
1082         if (obd->obd_proc_entry) {
1083                 lprocfs_remove(&obd->obd_proc_entry);
1084                 obd->obd_proc_entry = NULL;
1085         }
1086         return 0;
1087 }
1088 EXPORT_SYMBOL(lprocfs_obd_cleanup);
1089
1090 int lprocfs_stats_alloc_one(struct lprocfs_stats *stats, unsigned int cpuid)
1091 {
1092         struct lprocfs_counter  *cntr;
1093         unsigned int            percpusize;
1094         int                     rc = -ENOMEM;
1095         unsigned long           flags = 0;
1096         int                     i;
1097
1098         LASSERT(stats->ls_percpu[cpuid] == NULL);
1099         LASSERT((stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU) == 0);
1100
1101         percpusize = lprocfs_stats_counter_size(stats);
1102         LIBCFS_ALLOC_ATOMIC(stats->ls_percpu[cpuid], percpusize);
1103         if (stats->ls_percpu[cpuid] != NULL) {
1104                 rc = 0;
1105                 if (unlikely(stats->ls_biggest_alloc_num <= cpuid)) {
1106                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
1107                                 spin_lock_irqsave(&stats->ls_lock, flags);
1108                         else
1109                                 spin_lock(&stats->ls_lock);
1110                         if (stats->ls_biggest_alloc_num <= cpuid)
1111                                 stats->ls_biggest_alloc_num = cpuid + 1;
1112                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE) {
1113                                 spin_unlock_irqrestore(&stats->ls_lock, flags);
1114                         } else {
1115                                 spin_unlock(&stats->ls_lock);
1116                         }
1117                 }
1118                 /* initialize the ls_percpu[cpuid] non-zero counter */
1119                 for (i = 0; i < stats->ls_num; ++i) {
1120                         cntr = lprocfs_stats_counter_get(stats, cpuid, i);
1121                         cntr->lc_min = LC_MIN_INIT;
1122                 }
1123         }
1124         return rc;
1125 }
1126 EXPORT_SYMBOL(lprocfs_stats_alloc_one);
1127
1128 struct lprocfs_stats *lprocfs_alloc_stats(unsigned int num,
1129                                           enum lprocfs_stats_flags flags)
1130 {
1131         struct lprocfs_stats    *stats;
1132         unsigned int            num_entry;
1133         unsigned int            percpusize = 0;
1134         int                     i;
1135
1136         if (num == 0)
1137                 return NULL;
1138
1139         if (lprocfs_no_percpu_stats != 0)
1140                 flags |= LPROCFS_STATS_FLAG_NOPERCPU;
1141
1142         if (flags & LPROCFS_STATS_FLAG_NOPERCPU)
1143                 num_entry = 1;
1144         else
1145                 num_entry = num_possible_cpus();
1146
1147         /* alloc percpu pointers for all possible cpu slots */
1148         LIBCFS_ALLOC(stats, offsetof(typeof(*stats), ls_percpu[num_entry]));
1149         if (stats == NULL)
1150                 return NULL;
1151
1152         stats->ls_num = num;
1153         stats->ls_flags = flags;
1154         spin_lock_init(&stats->ls_lock);
1155
1156         /* alloc num of counter headers */
1157         LIBCFS_ALLOC(stats->ls_cnt_header,
1158                      stats->ls_num * sizeof(struct lprocfs_counter_header));
1159         if (stats->ls_cnt_header == NULL)
1160                 goto fail;
1161
1162         if ((flags & LPROCFS_STATS_FLAG_NOPERCPU) != 0) {
1163                 /* contains only one set counters */
1164                 percpusize = lprocfs_stats_counter_size(stats);
1165                 LIBCFS_ALLOC_ATOMIC(stats->ls_percpu[0], percpusize);
1166                 if (stats->ls_percpu[0] == NULL)
1167                         goto fail;
1168                 stats->ls_biggest_alloc_num = 1;
1169         } else if ((flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0) {
1170                 /* alloc all percpu data, currently only obd_memory use this */
1171                 for (i = 0; i < num_entry; ++i)
1172                         if (lprocfs_stats_alloc_one(stats, i) < 0)
1173                                 goto fail;
1174         }
1175
1176         return stats;
1177
1178 fail:
1179         lprocfs_free_stats(&stats);
1180         return NULL;
1181 }
1182 EXPORT_SYMBOL(lprocfs_alloc_stats);
1183
1184 void lprocfs_free_stats(struct lprocfs_stats **statsh)
1185 {
1186         struct lprocfs_stats *stats = *statsh;
1187         unsigned int num_entry;
1188         unsigned int percpusize;
1189         unsigned int i;
1190
1191         if (stats == NULL || stats->ls_num == 0)
1192                 return;
1193         *statsh = NULL;
1194
1195         if (stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU)
1196                 num_entry = 1;
1197         else
1198                 num_entry = num_possible_cpus();
1199
1200         percpusize = lprocfs_stats_counter_size(stats);
1201         for (i = 0; i < num_entry; i++)
1202                 if (stats->ls_percpu[i] != NULL)
1203                         LIBCFS_FREE(stats->ls_percpu[i], percpusize);
1204         if (stats->ls_cnt_header != NULL)
1205                 LIBCFS_FREE(stats->ls_cnt_header, stats->ls_num *
1206                                         sizeof(struct lprocfs_counter_header));
1207         LIBCFS_FREE(stats, offsetof(typeof(*stats), ls_percpu[num_entry]));
1208 }
1209 EXPORT_SYMBOL(lprocfs_free_stats);
1210
1211 void lprocfs_clear_stats(struct lprocfs_stats *stats)
1212 {
1213         struct lprocfs_counter          *percpu_cntr;
1214         int                             i;
1215         int                             j;
1216         unsigned int                    num_entry;
1217         unsigned long                   flags = 0;
1218
1219         num_entry = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1220
1221         for (i = 0; i < num_entry; i++) {
1222                 if (stats->ls_percpu[i] == NULL)
1223                         continue;
1224                 for (j = 0; j < stats->ls_num; j++) {
1225                         percpu_cntr = lprocfs_stats_counter_get(stats, i, j);
1226                         percpu_cntr->lc_count           = 0;
1227                         percpu_cntr->lc_min             = LC_MIN_INIT;
1228                         percpu_cntr->lc_max             = 0;
1229                         percpu_cntr->lc_sumsquare       = 0;
1230                         percpu_cntr->lc_sum             = 0;
1231                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
1232                                 percpu_cntr->lc_sum_irq = 0;
1233                 }
1234         }
1235
1236         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1237 }
1238 EXPORT_SYMBOL(lprocfs_clear_stats);
1239
1240 static ssize_t lprocfs_stats_seq_write(struct file *file,
1241                                        const char __user *buf,
1242                                        size_t len, loff_t *off)
1243 {
1244         struct seq_file *seq = file->private_data;
1245         struct lprocfs_stats *stats = seq->private;
1246
1247         lprocfs_clear_stats(stats);
1248
1249         return len;
1250 }
1251
1252 static void *lprocfs_stats_seq_start(struct seq_file *p, loff_t *pos)
1253 {
1254         struct lprocfs_stats *stats = p->private;
1255
1256         return (*pos < stats->ls_num) ? pos : NULL;
1257 }
1258
1259 static void lprocfs_stats_seq_stop(struct seq_file *p, void *v)
1260 {
1261 }
1262
1263 static void *lprocfs_stats_seq_next(struct seq_file *p, void *v, loff_t *pos)
1264 {
1265         (*pos)++;
1266
1267         return lprocfs_stats_seq_start(p, pos);
1268 }
1269
1270 /* seq file export of one lprocfs counter */
1271 static int lprocfs_stats_seq_show(struct seq_file *p, void *v)
1272 {
1273         struct lprocfs_stats            *stats  = p->private;
1274         struct lprocfs_counter_header   *hdr;
1275         struct lprocfs_counter           ctr;
1276         int                              idx    = *(loff_t *)v;
1277
1278         if (idx == 0) {
1279                 struct timeval now;
1280
1281                 do_gettimeofday(&now);
1282                 seq_printf(p, "%-25s %lu.%lu secs.usecs\n",
1283                            "snapshot_time", now.tv_sec, now.tv_usec);
1284         }
1285
1286         hdr = &stats->ls_cnt_header[idx];
1287         lprocfs_stats_collect(stats, idx, &ctr);
1288
1289         if (ctr.lc_count == 0)
1290                 return 0;
1291
1292         seq_printf(p, "%-25s %lld samples [%s]", hdr->lc_name,
1293                    ctr.lc_count, hdr->lc_units);
1294
1295         if ((hdr->lc_config & LPROCFS_CNTR_AVGMINMAX) && ctr.lc_count > 0) {
1296                 seq_printf(p, " %lld %lld %lld",
1297                            ctr.lc_min, ctr.lc_max, ctr.lc_sum);
1298                 if (hdr->lc_config & LPROCFS_CNTR_STDDEV)
1299                         seq_printf(p, " %llu", ctr.lc_sumsquare);
1300         }
1301         seq_putc(p, '\n');
1302         return 0;
1303 }
1304
1305 static const struct seq_operations lprocfs_stats_seq_sops = {
1306         .start  = lprocfs_stats_seq_start,
1307         .stop   = lprocfs_stats_seq_stop,
1308         .next   = lprocfs_stats_seq_next,
1309         .show   = lprocfs_stats_seq_show,
1310 };
1311
1312 static int lprocfs_stats_seq_open(struct inode *inode, struct file *file)
1313 {
1314         struct seq_file *seq;
1315         int rc;
1316
1317         rc = LPROCFS_ENTRY_CHECK(inode);
1318         if (rc < 0)
1319                 return rc;
1320
1321         rc = seq_open(file, &lprocfs_stats_seq_sops);
1322         if (rc)
1323                 return rc;
1324         seq = file->private_data;
1325         seq->private = PDE_DATA(inode);
1326         return 0;
1327 }
1328
1329 static const struct file_operations lprocfs_stats_seq_fops = {
1330         .owner   = THIS_MODULE,
1331         .open    = lprocfs_stats_seq_open,
1332         .read    = seq_read,
1333         .write   = lprocfs_stats_seq_write,
1334         .llseek  = seq_lseek,
1335         .release = lprocfs_seq_release,
1336 };
1337
1338 int lprocfs_register_stats(struct proc_dir_entry *root, const char *name,
1339                            struct lprocfs_stats *stats)
1340 {
1341         struct proc_dir_entry *entry;
1342         LASSERT(root != NULL);
1343
1344         entry = proc_create_data(name, 0644, root,
1345                                  &lprocfs_stats_seq_fops, stats);
1346         if (entry == NULL)
1347                 return -ENOMEM;
1348         return 0;
1349 }
1350 EXPORT_SYMBOL(lprocfs_register_stats);
1351
1352 void lprocfs_counter_init(struct lprocfs_stats *stats, int index,
1353                           unsigned conf, const char *name, const char *units)
1354 {
1355         struct lprocfs_counter_header   *header;
1356         struct lprocfs_counter          *percpu_cntr;
1357         unsigned long                   flags = 0;
1358         unsigned int                    i;
1359         unsigned int                    num_cpu;
1360
1361         LASSERT(stats != NULL);
1362
1363         header = &stats->ls_cnt_header[index];
1364         LASSERTF(header != NULL, "Failed to allocate stats header:[%d]%s/%s\n",
1365                  index, name, units);
1366
1367         header->lc_config = conf;
1368         header->lc_name   = name;
1369         header->lc_units  = units;
1370
1371         num_cpu = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1372         for (i = 0; i < num_cpu; ++i) {
1373                 if (stats->ls_percpu[i] == NULL)
1374                         continue;
1375                 percpu_cntr = lprocfs_stats_counter_get(stats, i, index);
1376                 percpu_cntr->lc_count           = 0;
1377                 percpu_cntr->lc_min             = LC_MIN_INIT;
1378                 percpu_cntr->lc_max             = 0;
1379                 percpu_cntr->lc_sumsquare       = 0;
1380                 percpu_cntr->lc_sum             = 0;
1381                 if ((stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0)
1382                         percpu_cntr->lc_sum_irq = 0;
1383         }
1384         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1385 }
1386 EXPORT_SYMBOL(lprocfs_counter_init);
1387
1388 /* Note that we only init md counters for ops whose offset is less
1389  * than NUM_MD_STATS. This is explained in a comment in the definition
1390  * of struct md_ops. */
1391 #define LPROCFS_MD_OP_INIT(base, stats, op)                                    \
1392         do {                                                                   \
1393                 unsigned int _idx = base + MD_COUNTER_OFFSET(op);              \
1394                                                                                \
1395                 if (MD_COUNTER_OFFSET(op) < NUM_MD_STATS) {                    \
1396                         LASSERT(_idx < stats->ls_num);                         \
1397                         lprocfs_counter_init(stats, _idx, 0, #op, "reqs");     \
1398                 }                                                              \
1399         } while (0)
1400
1401 void lprocfs_init_mps_stats(int num_private_stats, struct lprocfs_stats *stats)
1402 {
1403         LPROCFS_MD_OP_INIT(num_private_stats, stats, get_root);
1404         LPROCFS_MD_OP_INIT(num_private_stats, stats, null_inode);
1405         LPROCFS_MD_OP_INIT(num_private_stats, stats, close);
1406         LPROCFS_MD_OP_INIT(num_private_stats, stats, create);
1407         LPROCFS_MD_OP_INIT(num_private_stats, stats, enqueue);
1408         LPROCFS_MD_OP_INIT(num_private_stats, stats, getattr);
1409         LPROCFS_MD_OP_INIT(num_private_stats, stats, getattr_name);
1410         LPROCFS_MD_OP_INIT(num_private_stats, stats, intent_lock);
1411         LPROCFS_MD_OP_INIT(num_private_stats, stats, link);
1412         LPROCFS_MD_OP_INIT(num_private_stats, stats, rename);
1413         LPROCFS_MD_OP_INIT(num_private_stats, stats, setattr);
1414         LPROCFS_MD_OP_INIT(num_private_stats, stats, fsync);
1415         LPROCFS_MD_OP_INIT(num_private_stats, stats, read_page);
1416         LPROCFS_MD_OP_INIT(num_private_stats, stats, unlink);
1417         LPROCFS_MD_OP_INIT(num_private_stats, stats, setxattr);
1418         LPROCFS_MD_OP_INIT(num_private_stats, stats, getxattr);
1419         LPROCFS_MD_OP_INIT(num_private_stats, stats, init_ea_size);
1420         LPROCFS_MD_OP_INIT(num_private_stats, stats, get_lustre_md);
1421         LPROCFS_MD_OP_INIT(num_private_stats, stats, free_lustre_md);
1422         LPROCFS_MD_OP_INIT(num_private_stats, stats, merge_attr);
1423         LPROCFS_MD_OP_INIT(num_private_stats, stats, set_open_replay_data);
1424         LPROCFS_MD_OP_INIT(num_private_stats, stats, clear_open_replay_data);
1425         LPROCFS_MD_OP_INIT(num_private_stats, stats, set_lock_data);
1426         LPROCFS_MD_OP_INIT(num_private_stats, stats, lock_match);
1427         LPROCFS_MD_OP_INIT(num_private_stats, stats, cancel_unused);
1428         LPROCFS_MD_OP_INIT(num_private_stats, stats, intent_getattr_async);
1429         LPROCFS_MD_OP_INIT(num_private_stats, stats, revalidate_lock);
1430 }
1431
1432 int lprocfs_alloc_md_stats(struct obd_device *obd,
1433                            unsigned int num_private_stats)
1434 {
1435         struct lprocfs_stats *stats;
1436         unsigned int num_stats;
1437         int rc, i;
1438
1439         CLASSERT(offsetof(struct md_ops, MD_STATS_FIRST_OP) == 0);
1440         CLASSERT(_MD_COUNTER_OFFSET(MD_STATS_FIRST_OP) == 0);
1441         CLASSERT(_MD_COUNTER_OFFSET(MD_STATS_LAST_OP) > 0);
1442
1443         /* TODO Ensure that this function is only used where
1444          * appropriate by adding an assertion to the effect that
1445          * obd->obd_type->typ_md_ops is not NULL. We can't do this now
1446          * because mdt_procfs_init() uses this function to allocate
1447          * the stats backing /proc/fs/lustre/mdt/.../md_stats but the
1448          * mdt layer does not use the md_ops interface. This is
1449          * confusing and a waste of memory. See LU-2484.
1450          */
1451         LASSERT(obd->obd_proc_entry != NULL);
1452         LASSERT(obd->obd_md_stats == NULL);
1453         LASSERT(obd->obd_md_cntr_base == 0);
1454
1455         num_stats = NUM_MD_STATS + num_private_stats;
1456         stats = lprocfs_alloc_stats(num_stats, 0);
1457         if (stats == NULL)
1458                 return -ENOMEM;
1459
1460         lprocfs_init_mps_stats(num_private_stats, stats);
1461
1462         for (i = num_private_stats; i < num_stats; i++) {
1463                 if (stats->ls_cnt_header[i].lc_name == NULL) {
1464                         CERROR("Missing md_stat initializer md_op "
1465                                "operation at offset %d. Aborting.\n",
1466                                i - num_private_stats);
1467                         LBUG();
1468                 }
1469         }
1470
1471         rc = lprocfs_register_stats(obd->obd_proc_entry, "md_stats", stats);
1472         if (rc < 0) {
1473                 lprocfs_free_stats(&stats);
1474         } else {
1475                 obd->obd_md_stats = stats;
1476                 obd->obd_md_cntr_base = num_private_stats;
1477         }
1478
1479         return rc;
1480 }
1481 EXPORT_SYMBOL(lprocfs_alloc_md_stats);
1482
1483 void lprocfs_free_md_stats(struct obd_device *obd)
1484 {
1485         struct lprocfs_stats *stats = obd->obd_md_stats;
1486
1487         if (stats != NULL) {
1488                 obd->obd_md_stats = NULL;
1489                 obd->obd_md_cntr_base = 0;
1490                 lprocfs_free_stats(&stats);
1491         }
1492 }
1493 EXPORT_SYMBOL(lprocfs_free_md_stats);
1494
1495 void lprocfs_init_ldlm_stats(struct lprocfs_stats *ldlm_stats)
1496 {
1497         lprocfs_counter_init(ldlm_stats,
1498                              LDLM_ENQUEUE - LDLM_FIRST_OPC,
1499                              0, "ldlm_enqueue", "reqs");
1500         lprocfs_counter_init(ldlm_stats,
1501                              LDLM_CONVERT - LDLM_FIRST_OPC,
1502                              0, "ldlm_convert", "reqs");
1503         lprocfs_counter_init(ldlm_stats,
1504                              LDLM_CANCEL - LDLM_FIRST_OPC,
1505                              0, "ldlm_cancel", "reqs");
1506         lprocfs_counter_init(ldlm_stats,
1507                              LDLM_BL_CALLBACK - LDLM_FIRST_OPC,
1508                              0, "ldlm_bl_callback", "reqs");
1509         lprocfs_counter_init(ldlm_stats,
1510                              LDLM_CP_CALLBACK - LDLM_FIRST_OPC,
1511                              0, "ldlm_cp_callback", "reqs");
1512         lprocfs_counter_init(ldlm_stats,
1513                              LDLM_GL_CALLBACK - LDLM_FIRST_OPC,
1514                              0, "ldlm_gl_callback", "reqs");
1515 }
1516 EXPORT_SYMBOL(lprocfs_init_ldlm_stats);
1517
1518 __s64 lprocfs_read_helper(struct lprocfs_counter *lc,
1519                           struct lprocfs_counter_header *header,
1520                           enum lprocfs_stats_flags flags,
1521                           enum lprocfs_fields_flags field)
1522 {
1523         __s64 ret = 0;
1524
1525         if (lc == NULL || header == NULL)
1526                 RETURN(0);
1527
1528         switch (field) {
1529                 case LPROCFS_FIELDS_FLAGS_CONFIG:
1530                         ret = header->lc_config;
1531                         break;
1532                 case LPROCFS_FIELDS_FLAGS_SUM:
1533                         ret = lc->lc_sum;
1534                         if ((flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0)
1535                                 ret += lc->lc_sum_irq;
1536                         break;
1537                 case LPROCFS_FIELDS_FLAGS_MIN:
1538                         ret = lc->lc_min;
1539                         break;
1540                 case LPROCFS_FIELDS_FLAGS_MAX:
1541                         ret = lc->lc_max;
1542                         break;
1543                 case LPROCFS_FIELDS_FLAGS_AVG:
1544                         ret = (lc->lc_max - lc->lc_min) / 2;
1545                         break;
1546                 case LPROCFS_FIELDS_FLAGS_SUMSQUARE:
1547                         ret = lc->lc_sumsquare;
1548                         break;
1549                 case LPROCFS_FIELDS_FLAGS_COUNT:
1550                         ret = lc->lc_count;
1551                         break;
1552                 default:
1553                         break;
1554         };
1555         RETURN(ret);
1556 }
1557 EXPORT_SYMBOL(lprocfs_read_helper);
1558
1559 int lprocfs_read_frac_helper(char *buffer, unsigned long count, long val,
1560                              int mult)
1561 {
1562         long decimal_val, frac_val;
1563         int prtn;
1564
1565         if (count < 10)
1566                 return -EINVAL;
1567
1568         decimal_val = val / mult;
1569         prtn = snprintf(buffer, count, "%ld", decimal_val);
1570         frac_val = val % mult;
1571
1572         if (prtn < (count - 4) && frac_val > 0) {
1573                 long temp_frac;
1574                 int i, temp_mult = 1, frac_bits = 0;
1575
1576                 temp_frac = frac_val * 10;
1577                 buffer[prtn++] = '.';
1578                 while (frac_bits < 2 && (temp_frac / mult) < 1 ) {
1579                         /* only reserved 2 bits fraction */
1580                         buffer[prtn++] ='0';
1581                         temp_frac *= 10;
1582                         frac_bits++;
1583                 }
1584                 /*
1585                  * Need to think these cases :
1586                  *      1. #echo x.00 > /proc/xxx       output result : x
1587                  *      2. #echo x.0x > /proc/xxx       output result : x.0x
1588                  *      3. #echo x.x0 > /proc/xxx       output result : x.x
1589                  *      4. #echo x.xx > /proc/xxx       output result : x.xx
1590                  *      Only reserved 2 bits fraction.
1591                  */
1592                 for (i = 0; i < (5 - prtn); i++)
1593                         temp_mult *= 10;
1594
1595                 frac_bits = min((int)count - prtn, 3 - frac_bits);
1596                 prtn += snprintf(buffer + prtn, frac_bits, "%ld",
1597                                  frac_val * temp_mult / mult);
1598
1599                 prtn--;
1600                 while(buffer[prtn] < '1' || buffer[prtn] > '9') {
1601                         prtn--;
1602                         if (buffer[prtn] == '.') {
1603                                 prtn--;
1604                                 break;
1605                         }
1606                 }
1607                 prtn++;
1608         }
1609         buffer[prtn++] ='\n';
1610         return prtn;
1611 }
1612
1613 int lprocfs_seq_read_frac_helper(struct seq_file *m, long val, int mult)
1614 {
1615         long decimal_val, frac_val;
1616
1617         decimal_val = val / mult;
1618         seq_printf(m, "%ld", decimal_val);
1619         frac_val = val % mult;
1620
1621         if (frac_val > 0) {
1622                 frac_val *= 100;
1623                 frac_val /= mult;
1624         }
1625         if (frac_val > 0) {
1626                 /* Three cases: x0, xx, 0x */
1627                 if ((frac_val % 10) != 0)
1628                         seq_printf(m, ".%ld", frac_val);
1629                 else
1630                         seq_printf(m, ".%ld", frac_val / 10);
1631         }
1632
1633         seq_printf(m, "\n");
1634         return 0;
1635 }
1636 EXPORT_SYMBOL(lprocfs_seq_read_frac_helper);
1637
1638 /* Obtains the conversion factor for the unit specified */
1639 static int get_mult(char unit, __u64 *mult)
1640 {
1641         __u64 units = 1;
1642
1643         switch (unit) {
1644         /* peta, tera, giga, mega, and kilo */
1645         case 'p':
1646         case 'P':
1647                 units <<= 10;
1648         case 't':
1649         case 'T':
1650                 units <<= 10;
1651         case 'g':
1652         case 'G':
1653                 units <<= 10;
1654         case 'm':
1655         case 'M':
1656                 units <<= 10;
1657         case 'k':
1658         case 'K':
1659                 units <<= 10;
1660                 break;
1661         /* some tests expect % to be accepted */
1662         case '%':
1663                 units = 1;
1664                 break;
1665         default:
1666                 return -EINVAL;
1667         }
1668
1669         *mult = units;
1670
1671         return 0;
1672 }
1673
1674 /*
1675  * Ensures the numeric string is valid. The function provides the final
1676  * multiplier in the case a unit exists at the end of the string. It also
1677  * locates the start of the whole and fractional parts (if any). This
1678  * function modifies the string so kstrtoull can be used to parse both
1679  * the whole and fraction portions. This function also figures out
1680  * the base of the number.
1681  */
1682 static int preprocess_numeric_str(char *buffer, __u64 *mult, __u64 def_mult,
1683                                   bool allow_units, char **whole, char **frac,
1684                                   unsigned int *base)
1685 {
1686         bool hit_decimal = false;
1687         bool hit_unit = false;
1688         int rc = 0;
1689         char *start;
1690         *mult = def_mult;
1691         *whole = NULL;
1692         *frac = NULL;
1693         *base = 10;
1694
1695         /* a hex string if it starts with "0x" */
1696         if (buffer[0] == '0' && tolower(buffer[1]) == 'x') {
1697                 *base = 16;
1698                 buffer += 2;
1699         }
1700
1701         start = buffer;
1702
1703         while (*buffer) {
1704                 /* allow for a single new line before the null terminator */
1705                 if (*buffer == '\n') {
1706                         *buffer = '\0';
1707                         buffer++;
1708
1709                         if (*buffer)
1710                                 return -EINVAL;
1711
1712                         break;
1713                 }
1714
1715                 /* any chars after our unit indicates a malformed string */
1716                 if (hit_unit)
1717                         return -EINVAL;
1718
1719                 /* ensure we only hit one decimal */
1720                 if (*buffer == '.') {
1721                         if (hit_decimal)
1722                                 return -EINVAL;
1723
1724                         /* if past start, there's a whole part */
1725                         if (start != buffer)
1726                                 *whole = start;
1727
1728                         *buffer = '\0';
1729                         start = buffer + 1;
1730                         hit_decimal = true;
1731                 } else if (!isdigit(*buffer) &&
1732                            !(*base == 16 && isxdigit(*buffer))) {
1733                         if (allow_units) {
1734                                 /* if we allow units, attempt to get mult */
1735                                 hit_unit = true;
1736                                 rc = get_mult(*buffer, mult);
1737                                 if (rc)
1738                                         return rc;
1739
1740                                 /* string stops here, but keep processing */
1741                                 *buffer = '\0';
1742                         } else {
1743                                 /* bad string */
1744                                 return -EINVAL;
1745                         }
1746                 }
1747
1748                 buffer++;
1749         }
1750
1751         if (hit_decimal) {
1752                 /* hit a decimal, make sure there's a fractional part */
1753                 if (!*start)
1754                         return -EINVAL;
1755
1756                 *frac = start;
1757         } else {
1758                 /* didn't hit a decimal, but may have a whole part */
1759                 if (start != buffer && *start)
1760                         *whole = start;
1761         }
1762
1763         /* malformed string if we didn't get anything */
1764         if (!*frac && !*whole)
1765                 return -EINVAL;
1766
1767         return 0;
1768 }
1769
1770 /*
1771  * Parses a numeric string which can contain a whole and fraction portion
1772  * into a __u64. Accepts a multiplier to apply to the value parsed. Also
1773  * allows the string to have a unit at the end. The function handles
1774  * wrapping of the final unsigned value.
1775  */
1776 static int str_to_u64_parse(char *buffer, unsigned long count,
1777                             __u64 *val, __u64 def_mult, bool allow_units)
1778 {
1779         __u64 whole = 0;
1780         __u64 frac = 0;
1781         unsigned int frac_d = 1;
1782         __u64 wrap_indicator = ULLONG_MAX;
1783         int rc = 0;
1784         __u64 mult;
1785         char *strwhole;
1786         char *strfrac;
1787         unsigned int base = 10;
1788
1789         rc = preprocess_numeric_str(buffer, &mult, def_mult, allow_units,
1790                                     &strwhole, &strfrac, &base);
1791
1792         if (rc)
1793                 return rc;
1794
1795         if (mult == 0) {
1796                 *val = 0;
1797                 return 0;
1798         }
1799
1800         /* the multiplier limits how large the value can be */
1801         wrap_indicator /=  mult;
1802
1803         if (strwhole) {
1804                 rc = kstrtoull(strwhole, base, &whole);
1805                 if (rc)
1806                         return rc;
1807
1808                 if (whole > wrap_indicator)
1809                         return -ERANGE;
1810
1811                 whole *= mult;
1812         }
1813
1814         if (strfrac) {
1815                 if (strlen(strfrac) > 10)
1816                         strfrac[10] = '\0';
1817
1818                 rc = kstrtoull(strfrac, base, &frac);
1819                 if (rc)
1820                         return rc;
1821
1822                 /* determine power of fractional portion */
1823                 while (*strfrac) {
1824                         frac_d *= base;
1825                         strfrac++;
1826                 }
1827
1828                 /* fractional portion is too large to perform calculation */
1829                 if (frac > wrap_indicator)
1830                         return -ERANGE;
1831
1832                 frac *= mult;
1833                 do_div(frac, frac_d);
1834         }
1835
1836         /* check that the sum of whole and fraction fits in u64 */
1837         if (whole > (ULLONG_MAX - frac))
1838                 return -ERANGE;
1839
1840         *val = whole + frac;
1841
1842         return 0;
1843 }
1844
1845 /*
1846  * This function parses numeric/hex strings into __s64. It accepts a multiplier
1847  * which will apply to the value parsed. It also can allow the string to
1848  * have a unit as the last character. The function handles overflow/underflow
1849  * of the signed integer.
1850  */
1851 static int str_to_s64_internal(const char __user *buffer, unsigned long count,
1852                                __s64 *val, __u64 def_mult, bool allow_units)
1853 {
1854         char kernbuf[22];
1855         __u64 tmp;
1856         unsigned int offset = 0;
1857         int signed sign = 1;
1858         __u64 max = LLONG_MAX;
1859         int rc = 0;
1860
1861         if (count > (sizeof(kernbuf) - 1))
1862                 return -EINVAL;
1863
1864         if (copy_from_user(kernbuf, buffer, count))
1865                 return -EFAULT;
1866
1867         kernbuf[count] = '\0';
1868
1869         /* keep track of our sign */
1870         if (*kernbuf == '-') {
1871                 sign = -1;
1872                 offset++;
1873                 /* equivalent to max = -LLONG_MIN, avoids overflow */
1874                 max++;
1875         }
1876
1877         rc = str_to_u64_parse(kernbuf + offset, count - offset,
1878                               &tmp, def_mult, allow_units);
1879         if (rc)
1880                 return rc;
1881
1882         /* check for overflow/underflow */
1883         if (max < tmp)
1884                 return -ERANGE;
1885
1886         *val = (__s64)tmp * sign;
1887
1888         return 0;
1889 }
1890
1891 /**
1892  * Convert a user string into a signed 64 bit number. This function produces
1893  * an error when the value parsed from the string underflows or
1894  * overflows. This function accepts strings which contain digits and
1895  * optionally a decimal or hex strings which are prefixed with "0x".
1896  *
1897  * \param[in] buffer    string consisting of numbers and optionally a decimal
1898  * \param[in] count     buffer length
1899  * \param[in] val       if successful, the value represented by the string
1900  *
1901  * \retval              0 on success
1902  * \retval              negative number on error
1903  */
1904 int lprocfs_str_to_s64(const char __user *buffer, unsigned long count,
1905                        __s64 *val)
1906 {
1907         return str_to_s64_internal(buffer, count, val, 1, false);
1908 }
1909 EXPORT_SYMBOL(lprocfs_str_to_s64);
1910
1911 /**
1912  * Convert a user string into a signed 64 bit number. This function produces
1913  * an error when the value parsed from the string times multiplier underflows or
1914  * overflows. This function only accepts strings that contains digits, an
1915  * optional decimal, and a char representing a unit at the end. If a unit is
1916  * specified in the string, the multiplier provided by the caller is ignored.
1917  * This function can also accept hexadecimal strings which are prefixed with
1918  * "0x".
1919  *
1920  * \param[in] buffer    string consisting of numbers, a decimal, and a unit
1921  * \param[in] count     buffer length
1922  * \param[in] val       if successful, the value represented by the string
1923  * \param[in] defunit   default unit if string doesn't contain one
1924  *
1925  * \retval              0 on success
1926  * \retval              negative number on error
1927  */
1928 int lprocfs_str_with_units_to_s64(const char __user *buffer,
1929                                   unsigned long count, __s64 *val, char defunit)
1930 {
1931         __u64 mult = 1;
1932         int rc;
1933
1934         if (defunit != '1') {
1935                 rc = get_mult(defunit, &mult);
1936                 if (rc)
1937                         return rc;
1938         }
1939
1940         return str_to_s64_internal(buffer, count, val, mult, true);
1941 }
1942 EXPORT_SYMBOL(lprocfs_str_with_units_to_s64);
1943
1944 static char *lprocfs_strnstr(const char *s1, const char *s2, size_t len)
1945 {
1946         size_t l2;
1947
1948         l2 = strlen(s2);
1949         if (!l2)
1950                 return (char *)s1;
1951         while (len >= l2) {
1952                 len--;
1953                 if (!memcmp(s1, s2, l2))
1954                         return (char *)s1;
1955                 s1++;
1956         }
1957         return NULL;
1958 }
1959
1960 /**
1961  * Find the string \a name in the input \a buffer, and return a pointer to the
1962  * value immediately following \a name, reducing \a count appropriately.
1963  * If \a name is not found the original \a buffer is returned.
1964  */
1965 char *lprocfs_find_named_value(const char *buffer, const char *name,
1966                                 size_t *count)
1967 {
1968         char *val;
1969         size_t buflen = *count;
1970
1971         /* there is no strnstr() in rhel5 and ubuntu kernels */
1972         val = lprocfs_strnstr(buffer, name, buflen);
1973         if (val == NULL)
1974                 return (char *)buffer;
1975
1976         val += strlen(name);                             /* skip prefix */
1977         while (val < buffer + buflen && isspace(*val)) /* skip separator */
1978                 val++;
1979
1980         *count = 0;
1981         while (val < buffer + buflen && isalnum(*val)) {
1982                 ++*count;
1983                 ++val;
1984         }
1985
1986         return val - *count;
1987 }
1988 EXPORT_SYMBOL(lprocfs_find_named_value);
1989
1990 int lprocfs_seq_create(struct proc_dir_entry *parent,
1991                        const char *name,
1992                        mode_t mode,
1993                        const struct file_operations *seq_fops,
1994                        void *data)
1995 {
1996         struct proc_dir_entry *entry;
1997         ENTRY;
1998
1999         /* Disallow secretly (un)writable entries. */
2000         LASSERT((seq_fops->write == NULL) == ((mode & 0222) == 0));
2001
2002         entry = proc_create_data(name, mode, parent, seq_fops, data);
2003
2004         if (entry == NULL)
2005                 RETURN(-ENOMEM);
2006
2007         RETURN(0);
2008 }
2009 EXPORT_SYMBOL(lprocfs_seq_create);
2010
2011 int lprocfs_obd_seq_create(struct obd_device *dev,
2012                            const char *name,
2013                            mode_t mode,
2014                            const struct file_operations *seq_fops,
2015                            void *data)
2016 {
2017         return (lprocfs_seq_create(dev->obd_proc_entry, name,
2018                                    mode, seq_fops, data));
2019 }
2020 EXPORT_SYMBOL(lprocfs_obd_seq_create);
2021
2022 void lprocfs_oh_tally(struct obd_histogram *oh, unsigned int value)
2023 {
2024         if (value >= OBD_HIST_MAX)
2025                 value = OBD_HIST_MAX - 1;
2026
2027         spin_lock(&oh->oh_lock);
2028         oh->oh_buckets[value]++;
2029         spin_unlock(&oh->oh_lock);
2030 }
2031 EXPORT_SYMBOL(lprocfs_oh_tally);
2032
2033 void lprocfs_oh_tally_log2(struct obd_histogram *oh, unsigned int value)
2034 {
2035         unsigned int val = 0;
2036
2037         if (likely(value != 0))
2038                 val = min(fls(value - 1), OBD_HIST_MAX);
2039
2040         lprocfs_oh_tally(oh, val);
2041 }
2042 EXPORT_SYMBOL(lprocfs_oh_tally_log2);
2043
2044 unsigned long lprocfs_oh_sum(struct obd_histogram *oh)
2045 {
2046         unsigned long ret = 0;
2047         int i;
2048
2049         for (i = 0; i < OBD_HIST_MAX; i++)
2050                 ret +=  oh->oh_buckets[i];
2051         return ret;
2052 }
2053 EXPORT_SYMBOL(lprocfs_oh_sum);
2054
2055 void lprocfs_oh_clear(struct obd_histogram *oh)
2056 {
2057         spin_lock(&oh->oh_lock);
2058         memset(oh->oh_buckets, 0, sizeof(oh->oh_buckets));
2059         spin_unlock(&oh->oh_lock);
2060 }
2061 EXPORT_SYMBOL(lprocfs_oh_clear);
2062
2063 int lprocfs_obd_rd_max_pages_per_rpc(char *page, char **start, off_t off,
2064                                      int count, int *eof, void *data)
2065 {
2066         struct obd_device *dev = data;
2067         struct client_obd *cli = &dev->u.cli;
2068         int rc;
2069
2070         spin_lock(&cli->cl_loi_list_lock);
2071         rc = snprintf(page, count, "%d\n", cli->cl_max_pages_per_rpc);
2072         spin_unlock(&cli->cl_loi_list_lock);
2073
2074         return rc;
2075 }
2076
2077 int lprocfs_obd_max_pages_per_rpc_seq_show(struct seq_file *m, void *data)
2078 {
2079         struct obd_device *dev = data;
2080         struct client_obd *cli = &dev->u.cli;
2081
2082         spin_lock(&cli->cl_loi_list_lock);
2083         seq_printf(m, "%d\n", cli->cl_max_pages_per_rpc);
2084         spin_unlock(&cli->cl_loi_list_lock);
2085         return 0;
2086 }
2087 EXPORT_SYMBOL(lprocfs_obd_max_pages_per_rpc_seq_show);
2088
2089 int lprocfs_wr_root_squash(const char __user *buffer, unsigned long count,
2090                            struct root_squash_info *squash, char *name)
2091 {
2092         int rc;
2093         char kernbuf[64], *tmp, *errmsg;
2094         unsigned long uid, gid;
2095         ENTRY;
2096
2097         if (count >= sizeof(kernbuf)) {
2098                 errmsg = "string too long";
2099                 GOTO(failed_noprint, rc = -EINVAL);
2100         }
2101         if (copy_from_user(kernbuf, buffer, count)) {
2102                 errmsg = "bad address";
2103                 GOTO(failed_noprint, rc = -EFAULT);
2104         }
2105         kernbuf[count] = '\0';
2106
2107         /* look for uid gid separator */
2108         tmp = strchr(kernbuf, ':');
2109         if (tmp == NULL) {
2110                 errmsg = "needs uid:gid format";
2111                 GOTO(failed, rc = -EINVAL);
2112         }
2113         *tmp = '\0';
2114         tmp++;
2115
2116         /* parse uid */
2117         if (kstrtoul(kernbuf, 0, &uid) != 0) {
2118                 errmsg = "bad uid";
2119                 GOTO(failed, rc = -EINVAL);
2120         }
2121
2122         /* parse gid */
2123         if (kstrtoul(tmp, 0, &gid) != 0) {
2124                 errmsg = "bad gid";
2125                 GOTO(failed, rc = -EINVAL);
2126         }
2127
2128         squash->rsi_uid = uid;
2129         squash->rsi_gid = gid;
2130
2131         LCONSOLE_INFO("%s: root_squash is set to %u:%u\n",
2132                       name, squash->rsi_uid, squash->rsi_gid);
2133         RETURN(count);
2134
2135 failed:
2136         if (tmp != NULL) {
2137                 tmp--;
2138                 *tmp = ':';
2139         }
2140         CWARN("%s: failed to set root_squash to \"%s\", %s, rc = %d\n",
2141               name, kernbuf, errmsg, rc);
2142         RETURN(rc);
2143 failed_noprint:
2144         CWARN("%s: failed to set root_squash due to %s, rc = %d\n",
2145               name, errmsg, rc);
2146         RETURN(rc);
2147 }
2148 EXPORT_SYMBOL(lprocfs_wr_root_squash);
2149
2150
2151 int lprocfs_wr_nosquash_nids(const char __user *buffer, unsigned long count,
2152                              struct root_squash_info *squash, char *name)
2153 {
2154         int rc;
2155         char *kernbuf = NULL;
2156         char *errmsg;
2157         struct list_head tmp;
2158         int len = count;
2159         ENTRY;
2160
2161         if (count > 4096) {
2162                 errmsg = "string too long";
2163                 GOTO(failed, rc = -EINVAL);
2164         }
2165
2166         OBD_ALLOC(kernbuf, count + 1);
2167         if (kernbuf == NULL) {
2168                 errmsg = "no memory";
2169                 GOTO(failed, rc = -ENOMEM);
2170         }
2171         if (copy_from_user(kernbuf, buffer, count)) {
2172                 errmsg = "bad address";
2173                 GOTO(failed, rc = -EFAULT);
2174         }
2175         kernbuf[count] = '\0';
2176
2177         if (count > 0 && kernbuf[count - 1] == '\n')
2178                 len = count - 1;
2179
2180         if ((len == 4 && strncmp(kernbuf, "NONE", len) == 0) ||
2181             (len == 5 && strncmp(kernbuf, "clear", len) == 0)) {
2182                 /* empty string is special case */
2183                 down_write(&squash->rsi_sem);
2184                 if (!list_empty(&squash->rsi_nosquash_nids))
2185                         cfs_free_nidlist(&squash->rsi_nosquash_nids);
2186                 up_write(&squash->rsi_sem);
2187                 LCONSOLE_INFO("%s: nosquash_nids is cleared\n", name);
2188                 OBD_FREE(kernbuf, count + 1);
2189                 RETURN(count);
2190         }
2191
2192         INIT_LIST_HEAD(&tmp);
2193         if (cfs_parse_nidlist(kernbuf, count, &tmp) <= 0) {
2194                 errmsg = "can't parse";
2195                 GOTO(failed, rc = -EINVAL);
2196         }
2197         LCONSOLE_INFO("%s: nosquash_nids set to %s\n",
2198                       name, kernbuf);
2199         OBD_FREE(kernbuf, count + 1);
2200         kernbuf = NULL;
2201
2202         down_write(&squash->rsi_sem);
2203         if (!list_empty(&squash->rsi_nosquash_nids))
2204                 cfs_free_nidlist(&squash->rsi_nosquash_nids);
2205         list_splice(&tmp, &squash->rsi_nosquash_nids);
2206         up_write(&squash->rsi_sem);
2207
2208         RETURN(count);
2209
2210 failed:
2211         if (kernbuf) {
2212                 CWARN("%s: failed to set nosquash_nids to \"%s\", %s rc = %d\n",
2213                       name, kernbuf, errmsg, rc);
2214                 OBD_FREE(kernbuf, count + 1);
2215         } else {
2216                 CWARN("%s: failed to set nosquash_nids due to %s rc = %d\n",
2217                       name, errmsg, rc);
2218         }
2219         RETURN(rc);
2220 }
2221 EXPORT_SYMBOL(lprocfs_wr_nosquash_nids);
2222
2223 #endif /* CONFIG_PROC_FS*/