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