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