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