Whamcloud - gitweb
LU-10810 ptlrpc: introduce OST_SEEK RPC
[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         "fidmap",               /* 0x10000 */
637         "getattr_pfid",         /* 0x20000 */
638         "lseek",                /* 0x40000 */
639         NULL
640 };
641
642 void obd_connect_seq_flags2str(struct seq_file *m, __u64 flags, __u64 flags2,
643                                const char *sep)
644 {
645         bool first = true;
646         __u64 mask;
647         int i;
648
649         for (i = 0, mask = 1; i < 64; i++, mask <<= 1) {
650                 if (flags & mask) {
651                         seq_printf(m, "%s%s",
652                                    first ? "" : sep, obd_connect_names[i]);
653                         first = false;
654                 }
655         }
656
657         if (flags & ~(mask - 1)) {
658                 seq_printf(m, "%sunknown_%#llx",
659                            first ? "" : sep, flags & ~(mask - 1));
660                 first = false;
661         }
662
663         if (!(flags & OBD_CONNECT_FLAGS2) || flags2 == 0)
664                 return;
665
666         for (i = 64, mask = 1; obd_connect_names[i] != NULL; i++, mask <<= 1) {
667                 if (flags2 & mask) {
668                         seq_printf(m, "%s%s",
669                                    first ? "" : sep, obd_connect_names[i]);
670                         first = false;
671                 }
672         }
673
674         if (flags2 & ~(mask - 1)) {
675                 seq_printf(m, "%sunknown2_%#llx",
676                            first ? "" : sep, flags2 & ~(mask - 1));
677                 first = false;
678         }
679 }
680 EXPORT_SYMBOL(obd_connect_seq_flags2str);
681
682 int obd_connect_flags2str(char *page, int count, __u64 flags, __u64 flags2,
683                           const char *sep)
684 {
685         __u64 mask;
686         int i, ret = 0;
687
688         for (i = 0, mask = 1; i < 64; i++, mask <<= 1) {
689                 if (flags & mask)
690                         ret += snprintf(page + ret, count - ret, "%s%s",
691                                         ret ? sep : "", obd_connect_names[i]);
692         }
693
694         if (flags & ~(mask - 1))
695                 ret += snprintf(page + ret, count - ret,
696                                 "%sunknown_%#llx",
697                                 ret ? sep : "", flags & ~(mask - 1));
698
699         if (!(flags & OBD_CONNECT_FLAGS2) || flags2 == 0)
700                 return ret;
701
702         for (i = 64, mask = 1; obd_connect_names[i] != NULL; i++, mask <<= 1) {
703                 if (flags2 & mask)
704                         ret += snprintf(page + ret, count - ret, "%s%s",
705                                         ret ? sep : "", obd_connect_names[i]);
706         }
707
708         if (flags2 & ~(mask - 1))
709                 ret += snprintf(page + ret, count - ret,
710                                 "%sunknown2_%#llx",
711                                 ret ? sep : "", flags2 & ~(mask - 1));
712
713         return ret;
714 }
715 EXPORT_SYMBOL(obd_connect_flags2str);
716
717 void
718 obd_connect_data_seqprint(struct seq_file *m, struct obd_connect_data *ocd)
719 {
720         __u64 flags;
721
722         LASSERT(ocd != NULL);
723         flags = ocd->ocd_connect_flags;
724
725         seq_printf(m, "    connect_data:\n"
726                    "       flags: %#llx\n"
727                    "       instance: %u\n",
728                    ocd->ocd_connect_flags,
729                    ocd->ocd_instance);
730         if (flags & OBD_CONNECT_VERSION)
731                 seq_printf(m, "       target_version: %u.%u.%u.%u\n",
732                            OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
733                            OBD_OCD_VERSION_MINOR(ocd->ocd_version),
734                            OBD_OCD_VERSION_PATCH(ocd->ocd_version),
735                            OBD_OCD_VERSION_FIX(ocd->ocd_version));
736         if (flags & OBD_CONNECT_MDS)
737                 seq_printf(m, "       mdt_index: %d\n", ocd->ocd_group);
738         if (flags & OBD_CONNECT_GRANT)
739                 seq_printf(m, "       initial_grant: %d\n", ocd->ocd_grant);
740         if (flags & OBD_CONNECT_INDEX)
741                 seq_printf(m, "       target_index: %u\n", ocd->ocd_index);
742         if (flags & OBD_CONNECT_BRW_SIZE)
743                 seq_printf(m, "       max_brw_size: %d\n", ocd->ocd_brw_size);
744         if (flags & OBD_CONNECT_IBITS)
745                 seq_printf(m, "       ibits_known: %#llx\n",
746                            ocd->ocd_ibits_known);
747         if (flags & OBD_CONNECT_GRANT_PARAM)
748                 seq_printf(m, "       grant_block_size: %d\n"
749                            "       grant_inode_size: %d\n"
750                            "       grant_max_extent_size: %d\n"
751                            "       grant_extent_tax: %d\n",
752                            1 << ocd->ocd_grant_blkbits,
753                            1 << ocd->ocd_grant_inobits,
754                            ocd->ocd_grant_max_blks << ocd->ocd_grant_blkbits,
755                            ocd->ocd_grant_tax_kb << 10);
756         if (flags & OBD_CONNECT_TRANSNO)
757                 seq_printf(m, "       first_transno: %#llx\n",
758                            ocd->ocd_transno);
759         if (flags & OBD_CONNECT_CKSUM)
760                 seq_printf(m, "       cksum_types: %#x\n",
761                            ocd->ocd_cksum_types);
762         if (flags & OBD_CONNECT_MAX_EASIZE)
763                 seq_printf(m, "       max_easize: %d\n", ocd->ocd_max_easize);
764         if (flags & OBD_CONNECT_MAXBYTES)
765                 seq_printf(m, "       max_object_bytes: %llu\n",
766                            ocd->ocd_maxbytes);
767         if (flags & OBD_CONNECT_MULTIMODRPCS)
768                 seq_printf(m, "       max_mod_rpcs: %hu\n",
769                            ocd->ocd_maxmodrpcs);
770 }
771
772 static void lprocfs_import_seq_show_locked(struct seq_file *m,
773                                            struct obd_device *obd,
774                                            struct obd_import *imp)
775 {
776         char nidstr[LNET_NIDSTR_SIZE];
777         struct lprocfs_counter ret;
778         struct lprocfs_counter_header *header;
779         struct obd_import_conn *conn;
780         struct obd_connect_data *ocd;
781         int j;
782         int k;
783         int rw = 0;
784
785         ocd = &imp->imp_connect_data;
786
787         seq_printf(m, "import:\n"
788                    "    name: %s\n"
789                    "    target: %s\n"
790                    "    state: %s\n"
791                    "    connect_flags: [ ",
792                    obd->obd_name,
793                    obd2cli_tgt(obd),
794                    ptlrpc_import_state_name(imp->imp_state));
795         obd_connect_seq_flags2str(m, imp->imp_connect_data.ocd_connect_flags,
796                                   imp->imp_connect_data.ocd_connect_flags2,
797                                   ", ");
798         seq_printf(m, " ]\n");
799         obd_connect_data_seqprint(m, ocd);
800         seq_printf(m, "    import_flags: [ ");
801         obd_import_flags2str(imp, m);
802
803         seq_printf(m, " ]\n"
804                    "    connection:\n"
805                    "       failover_nids: [ ");
806         spin_lock(&imp->imp_lock);
807         j = 0;
808         list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
809                 libcfs_nid2str_r(conn->oic_conn->c_peer.nid,
810                                  nidstr, sizeof(nidstr));
811                 seq_printf(m, "%s%s", j ? ", " : "", nidstr);
812                 j++;
813         }
814         if (imp->imp_connection)
815                 libcfs_nid2str_r(imp->imp_connection->c_peer.nid,
816                                  nidstr, sizeof(nidstr));
817         else
818                 strncpy(nidstr, "<none>", sizeof(nidstr));
819         seq_printf(m, " ]\n"
820                    "       current_connection: %s\n"
821                    "       connection_attempts: %u\n"
822                    "       generation: %u\n"
823                    "       in-progress_invalidations: %u\n"
824                    "       idle: %lld sec\n",
825                    nidstr,
826                    imp->imp_conn_cnt,
827                    imp->imp_generation,
828                    atomic_read(&imp->imp_inval_count),
829                    ktime_get_real_seconds() - imp->imp_last_reply_time);
830         spin_unlock(&imp->imp_lock);
831
832         if (!obd->obd_svc_stats)
833                 return;
834
835         header = &obd->obd_svc_stats->ls_cnt_header[PTLRPC_REQWAIT_CNTR];
836         lprocfs_stats_collect(obd->obd_svc_stats, PTLRPC_REQWAIT_CNTR, &ret);
837         if (ret.lc_count != 0)
838                 ret.lc_sum = div64_s64(ret.lc_sum, ret.lc_count);
839         else
840                 ret.lc_sum = 0;
841         seq_printf(m, "    rpcs:\n"
842                    "       inflight: %u\n"
843                    "       unregistering: %u\n"
844                    "       timeouts: %u\n"
845                    "       avg_waittime: %llu %s\n",
846                    atomic_read(&imp->imp_inflight),
847                    atomic_read(&imp->imp_unregistering),
848                    atomic_read(&imp->imp_timeouts),
849                    ret.lc_sum, header->lc_units);
850
851         k = 0;
852         for(j = 0; j < IMP_AT_MAX_PORTALS; j++) {
853                 if (imp->imp_at.iat_portal[j] == 0)
854                         break;
855                 k = max_t(unsigned int, k,
856                           at_get(&imp->imp_at.iat_service_estimate[j]));
857         }
858         seq_printf(m, "    service_estimates:\n"
859                    "       services: %u sec\n"
860                    "       network: %d sec\n",
861                    k,
862                    at_get(&imp->imp_at.iat_net_latency));
863
864         seq_printf(m, "    transactions:\n"
865                    "       last_replay: %llu\n"
866                    "       peer_committed: %llu\n"
867                    "       last_checked: %llu\n",
868                    imp->imp_last_replay_transno,
869                    imp->imp_peer_committed_transno,
870                    imp->imp_last_transno_checked);
871
872         /* avg data rates */
873         for (rw = 0; rw <= 1; rw++) {
874                 lprocfs_stats_collect(obd->obd_svc_stats,
875                                       PTLRPC_LAST_CNTR + BRW_READ_BYTES + rw,
876                                       &ret);
877                 if (ret.lc_sum > 0 && ret.lc_count > 0) {
878                         ret.lc_sum = div64_s64(ret.lc_sum, ret.lc_count);
879                         seq_printf(m, "    %s_data_averages:\n"
880                                    "       bytes_per_rpc: %llu\n",
881                                    rw ? "write" : "read",
882                                    ret.lc_sum);
883                 }
884                 k = (int)ret.lc_sum;
885                 j = opcode_offset(OST_READ + rw) + EXTRA_MAX_OPCODES;
886                 header = &obd->obd_svc_stats->ls_cnt_header[j];
887                 lprocfs_stats_collect(obd->obd_svc_stats, j, &ret);
888                 if (ret.lc_sum > 0 && ret.lc_count != 0) {
889                         ret.lc_sum = div64_s64(ret.lc_sum, ret.lc_count);
890                         seq_printf(m, "       %s_per_rpc: %llu\n",
891                                    header->lc_units, ret.lc_sum);
892                         j = (int)ret.lc_sum;
893                         if (j > 0)
894                                 seq_printf(m, "       MB_per_sec: %u.%.02u\n",
895                                            k / j, (100 * k / j) % 100);
896                 }
897         }
898 }
899
900 int lprocfs_import_seq_show(struct seq_file *m, void *data)
901 {
902         struct obd_device *obd = (struct obd_device *)data;
903         struct obd_import *imp;
904         int rv;
905
906         LASSERT(obd != NULL);
907         with_imp_locked(obd, imp, rv)
908                 lprocfs_import_seq_show_locked(m, obd, imp);
909         return rv;
910 }
911 EXPORT_SYMBOL(lprocfs_import_seq_show);
912
913 int lprocfs_state_seq_show(struct seq_file *m, void *data)
914 {
915         struct obd_device *obd = (struct obd_device *)data;
916         struct obd_import *imp;
917         int j, k;
918         int rc;
919
920         LASSERT(obd != NULL);
921         with_imp_locked(obd, imp, rc) {
922                 seq_printf(m, "current_state: %s\n",
923                            ptlrpc_import_state_name(imp->imp_state));
924                 seq_printf(m, "state_history:\n");
925                 k = imp->imp_state_hist_idx;
926                 for (j = 0; j < IMP_STATE_HIST_LEN; j++) {
927                         struct import_state_hist *ish =
928                                 &imp->imp_state_hist[(k + j) % IMP_STATE_HIST_LEN];
929                         if (ish->ish_state == 0)
930                                 continue;
931                         seq_printf(m, " - [ %lld, %s ]\n", (s64)ish->ish_time,
932                                    ptlrpc_import_state_name(ish->ish_state));
933                 }
934         }
935
936         return rc;
937 }
938 EXPORT_SYMBOL(lprocfs_state_seq_show);
939
940 int lprocfs_at_hist_helper(struct seq_file *m, struct adaptive_timeout *at)
941 {
942         int i;
943         for (i = 0; i < AT_BINS; i++)
944                 seq_printf(m, "%3u ", at->at_hist[i]);
945         seq_printf(m, "\n");
946         return 0;
947 }
948 EXPORT_SYMBOL(lprocfs_at_hist_helper);
949
950 /* See also ptlrpc_lprocfs_timeouts_show_seq */
951 static void lprocfs_timeouts_seq_show_locked(struct seq_file *m,
952                                              struct obd_device *obd,
953                                              struct obd_import *imp)
954 {
955         timeout_t cur_timeout, worst_timeout;
956         time64_t now, worst_timestamp;
957         int i;
958
959         LASSERT(obd != NULL);
960
961         now = ktime_get_real_seconds();
962
963         /* Some network health info for kicks */
964         seq_printf(m, "%-10s : %lld, %llds ago\n",
965                    "last reply", (s64)imp->imp_last_reply_time,
966                    (s64)(now - imp->imp_last_reply_time));
967
968         cur_timeout = at_get(&imp->imp_at.iat_net_latency);
969         worst_timeout = imp->imp_at.iat_net_latency.at_worst_timeout_ever;
970         worst_timestamp = imp->imp_at.iat_net_latency.at_worst_timestamp;
971         seq_printf(m, "%-10s : cur %3u  worst %3u (at %lld, %llds ago) ",
972                    "network", cur_timeout, worst_timeout, worst_timestamp,
973                    now - worst_timestamp);
974         lprocfs_at_hist_helper(m, &imp->imp_at.iat_net_latency);
975
976         for(i = 0; i < IMP_AT_MAX_PORTALS; i++) {
977                 struct adaptive_timeout *service_est;
978
979                 if (imp->imp_at.iat_portal[i] == 0)
980                         break;
981
982                 service_est = &imp->imp_at.iat_service_estimate[i];
983                 cur_timeout = at_get(service_est);
984                 worst_timeout = service_est->at_worst_timeout_ever;
985                 worst_timestamp = service_est->at_worst_timestamp;
986                 seq_printf(m, "portal %-2d  : cur %3u  worst %3u (at %lld, %llds ago) ",
987                            imp->imp_at.iat_portal[i], cur_timeout,
988                            worst_timeout, worst_timestamp,
989                            now - worst_timestamp);
990                 lprocfs_at_hist_helper(m, service_est);
991         }
992 }
993
994 int lprocfs_timeouts_seq_show(struct seq_file *m, void *data)
995 {
996         struct obd_device *obd = (struct obd_device *)data;
997         struct obd_import *imp;
998         int rc;
999
1000         with_imp_locked(obd, imp, rc)
1001                 lprocfs_timeouts_seq_show_locked(m, obd, imp);
1002         return rc;
1003 }
1004 EXPORT_SYMBOL(lprocfs_timeouts_seq_show);
1005
1006 int lprocfs_connect_flags_seq_show(struct seq_file *m, void *data)
1007 {
1008         struct obd_device *obd = data;
1009         __u64 flags;
1010         __u64 flags2;
1011         struct obd_import *imp;
1012         int rc;
1013
1014         with_imp_locked(obd, imp, rc) {
1015                 flags = imp->imp_connect_data.ocd_connect_flags;
1016                 flags2 = imp->imp_connect_data.ocd_connect_flags2;
1017                 seq_printf(m, "flags=%#llx\n", flags);
1018                 seq_printf(m, "flags2=%#llx\n", flags2);
1019                 obd_connect_seq_flags2str(m, flags, flags2, "\n");
1020                 seq_printf(m, "\n");
1021         }
1022
1023         return rc;
1024 }
1025 EXPORT_SYMBOL(lprocfs_connect_flags_seq_show);
1026
1027 static const struct attribute *obd_def_uuid_attrs[] = {
1028         &lustre_attr_uuid.attr,
1029         NULL,
1030 };
1031
1032 static const struct attribute *obd_def_attrs[] = {
1033         &lustre_attr_blocksize.attr,
1034         &lustre_attr_kbytestotal.attr,
1035         &lustre_attr_kbytesfree.attr,
1036         &lustre_attr_kbytesavail.attr,
1037         &lustre_attr_filestotal.attr,
1038         &lustre_attr_filesfree.attr,
1039         &lustre_attr_uuid.attr,
1040         NULL,
1041 };
1042
1043 static void obd_sysfs_release(struct kobject *kobj)
1044 {
1045         struct obd_device *obd = container_of(kobj, struct obd_device,
1046                                               obd_kset.kobj);
1047
1048         complete(&obd->obd_kobj_unregister);
1049 }
1050
1051 int lprocfs_obd_setup(struct obd_device *obd, bool uuid_only)
1052 {
1053         struct ldebugfs_vars *debugfs_vars = NULL;
1054         int rc;
1055
1056         if (!obd || obd->obd_magic != OBD_DEVICE_MAGIC)
1057                 return -ENODEV;
1058
1059         rc = kobject_set_name(&obd->obd_kset.kobj, "%s", obd->obd_name);
1060         if (rc)
1061                 return rc;
1062
1063         obd->obd_ktype.sysfs_ops = &lustre_sysfs_ops;
1064         obd->obd_ktype.release = obd_sysfs_release;
1065
1066         obd->obd_kset.kobj.parent = &obd->obd_type->typ_kobj;
1067         obd->obd_kset.kobj.ktype = &obd->obd_ktype;
1068         init_completion(&obd->obd_kobj_unregister);
1069         rc = kset_register(&obd->obd_kset);
1070         if (rc)
1071                 return rc;
1072
1073         if (uuid_only)
1074                 obd->obd_attrs = obd_def_uuid_attrs;
1075         else
1076                 obd->obd_attrs = obd_def_attrs;
1077
1078         rc = sysfs_create_files(&obd->obd_kset.kobj, obd->obd_attrs);
1079         if (rc) {
1080                 kset_unregister(&obd->obd_kset);
1081                 return rc;
1082         }
1083
1084         if (!obd->obd_type->typ_procroot)
1085                 debugfs_vars = obd->obd_debugfs_vars;
1086         obd->obd_debugfs_entry = debugfs_create_dir(
1087                 obd->obd_name, obd->obd_type->typ_debugfs_entry);
1088         ldebugfs_add_vars(obd->obd_debugfs_entry, debugfs_vars, obd);
1089
1090         if (obd->obd_proc_entry || !obd->obd_type->typ_procroot)
1091                 GOTO(already_registered, rc);
1092
1093         obd->obd_proc_entry = lprocfs_register(obd->obd_name,
1094                                                obd->obd_type->typ_procroot,
1095                                                obd->obd_vars, obd);
1096         if (IS_ERR(obd->obd_proc_entry)) {
1097                 rc = PTR_ERR(obd->obd_proc_entry);
1098                 CERROR("error %d setting up lprocfs for %s\n",rc,obd->obd_name);
1099                 obd->obd_proc_entry = NULL;
1100
1101                 debugfs_remove_recursive(obd->obd_debugfs_entry);
1102                 obd->obd_debugfs_entry = NULL;
1103
1104                 sysfs_remove_files(&obd->obd_kset.kobj, obd->obd_attrs);
1105                 obd->obd_attrs = NULL;
1106                 kset_unregister(&obd->obd_kset);
1107                 return rc;
1108         }
1109 already_registered:
1110         return rc;
1111 }
1112 EXPORT_SYMBOL(lprocfs_obd_setup);
1113
1114 int lprocfs_obd_cleanup(struct obd_device *obd)
1115 {
1116         if (!obd)
1117                 return -EINVAL;
1118
1119         if (obd->obd_proc_exports_entry) {
1120                 /* Should be no exports left */
1121                 lprocfs_remove(&obd->obd_proc_exports_entry);
1122                 obd->obd_proc_exports_entry = NULL;
1123         }
1124
1125         if (obd->obd_proc_entry) {
1126                 lprocfs_remove(&obd->obd_proc_entry);
1127                 obd->obd_proc_entry = NULL;
1128         }
1129
1130         debugfs_remove_recursive(obd->obd_debugfs_entry);
1131         obd->obd_debugfs_entry = NULL;
1132
1133         /* obd device never allocated a kset */
1134         if (!obd->obd_kset.kobj.state_initialized)
1135                 return 0;
1136
1137         if (obd->obd_attrs) {
1138                 sysfs_remove_files(&obd->obd_kset.kobj, obd->obd_attrs);
1139                 obd->obd_attrs = NULL;
1140         }
1141
1142         kset_unregister(&obd->obd_kset);
1143         wait_for_completion(&obd->obd_kobj_unregister);
1144         return 0;
1145 }
1146 EXPORT_SYMBOL(lprocfs_obd_cleanup);
1147
1148 int lprocfs_stats_alloc_one(struct lprocfs_stats *stats, unsigned int cpuid)
1149 {
1150         struct lprocfs_counter *cntr;
1151         unsigned int percpusize;
1152         int rc = -ENOMEM;
1153         unsigned long flags = 0;
1154         int i;
1155
1156         LASSERT(stats->ls_percpu[cpuid] == NULL);
1157         LASSERT((stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU) == 0);
1158
1159         percpusize = lprocfs_stats_counter_size(stats);
1160         LIBCFS_ALLOC_ATOMIC(stats->ls_percpu[cpuid], percpusize);
1161         if (stats->ls_percpu[cpuid]) {
1162                 rc = 0;
1163                 if (unlikely(stats->ls_biggest_alloc_num <= cpuid)) {
1164                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
1165                                 spin_lock_irqsave(&stats->ls_lock, flags);
1166                         else
1167                                 spin_lock(&stats->ls_lock);
1168                         if (stats->ls_biggest_alloc_num <= cpuid)
1169                                 stats->ls_biggest_alloc_num = cpuid + 1;
1170                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE) {
1171                                 spin_unlock_irqrestore(&stats->ls_lock, flags);
1172                         } else {
1173                                 spin_unlock(&stats->ls_lock);
1174                         }
1175                 }
1176                 /* initialize the ls_percpu[cpuid] non-zero counter */
1177                 for (i = 0; i < stats->ls_num; ++i) {
1178                         cntr = lprocfs_stats_counter_get(stats, cpuid, i);
1179                         cntr->lc_min = LC_MIN_INIT;
1180                 }
1181         }
1182         return rc;
1183 }
1184
1185 struct lprocfs_stats *lprocfs_alloc_stats(unsigned int num,
1186                                           enum lprocfs_stats_flags flags)
1187 {
1188         struct lprocfs_stats *stats;
1189         unsigned int num_entry;
1190         unsigned int percpusize = 0;
1191         int i;
1192
1193         if (num == 0)
1194                 return NULL;
1195
1196         if (lprocfs_no_percpu_stats != 0)
1197                 flags |= LPROCFS_STATS_FLAG_NOPERCPU;
1198
1199         if (flags & LPROCFS_STATS_FLAG_NOPERCPU)
1200                 num_entry = 1;
1201         else
1202                 num_entry = num_possible_cpus();
1203
1204         /* alloc percpu pointers for all possible cpu slots */
1205         LIBCFS_ALLOC(stats, offsetof(typeof(*stats), ls_percpu[num_entry]));
1206         if (!stats)
1207                 return NULL;
1208
1209         stats->ls_num = num;
1210         stats->ls_flags = flags;
1211         spin_lock_init(&stats->ls_lock);
1212
1213         /* alloc num of counter headers */
1214         CFS_ALLOC_PTR_ARRAY(stats->ls_cnt_header, stats->ls_num);
1215         if (!stats->ls_cnt_header)
1216                 goto fail;
1217
1218         if ((flags & LPROCFS_STATS_FLAG_NOPERCPU) != 0) {
1219                 /* contains only one set counters */
1220                 percpusize = lprocfs_stats_counter_size(stats);
1221                 LIBCFS_ALLOC_ATOMIC(stats->ls_percpu[0], percpusize);
1222                 if (!stats->ls_percpu[0])
1223                         goto fail;
1224                 stats->ls_biggest_alloc_num = 1;
1225         } else if ((flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0) {
1226                 /* alloc all percpu data, currently only obd_memory use this */
1227                 for (i = 0; i < num_entry; ++i)
1228                         if (lprocfs_stats_alloc_one(stats, i) < 0)
1229                                 goto fail;
1230         }
1231
1232         return stats;
1233
1234 fail:
1235         lprocfs_free_stats(&stats);
1236         return NULL;
1237 }
1238 EXPORT_SYMBOL(lprocfs_alloc_stats);
1239
1240 void lprocfs_free_stats(struct lprocfs_stats **statsh)
1241 {
1242         struct lprocfs_stats *stats = *statsh;
1243         unsigned int num_entry;
1244         unsigned int percpusize;
1245         unsigned int i;
1246
1247         if (!stats || stats->ls_num == 0)
1248                 return;
1249         *statsh = NULL;
1250
1251         if (stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU)
1252                 num_entry = 1;
1253         else
1254                 num_entry = num_possible_cpus();
1255
1256         percpusize = lprocfs_stats_counter_size(stats);
1257         for (i = 0; i < num_entry; i++)
1258                 if (stats->ls_percpu[i])
1259                         LIBCFS_FREE(stats->ls_percpu[i], percpusize);
1260         if (stats->ls_cnt_header)
1261                 CFS_FREE_PTR_ARRAY(stats->ls_cnt_header, stats->ls_num);
1262         LIBCFS_FREE(stats, offsetof(typeof(*stats), ls_percpu[num_entry]));
1263 }
1264 EXPORT_SYMBOL(lprocfs_free_stats);
1265
1266 u64 lprocfs_stats_collector(struct lprocfs_stats *stats, int idx,
1267                             enum lprocfs_fields_flags field)
1268 {
1269         unsigned long flags = 0;
1270         unsigned int num_cpu;
1271         unsigned int i;
1272         u64 ret = 0;
1273
1274         LASSERT(stats);
1275
1276         num_cpu = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1277         for (i = 0; i < num_cpu; i++) {
1278                 struct lprocfs_counter *cntr;
1279
1280                 if (!stats->ls_percpu[i])
1281                         continue;
1282
1283                 cntr = lprocfs_stats_counter_get(stats, i, idx);
1284                 ret += lprocfs_read_helper(cntr, &stats->ls_cnt_header[idx],
1285                                            stats->ls_flags, field);
1286         }
1287         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1288         return ret;
1289 }
1290 EXPORT_SYMBOL(lprocfs_stats_collector);
1291
1292 void lprocfs_clear_stats(struct lprocfs_stats *stats)
1293 {
1294         struct lprocfs_counter *percpu_cntr;
1295         int i;
1296         int j;
1297         unsigned int num_entry;
1298         unsigned long flags = 0;
1299
1300         num_entry = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1301
1302         for (i = 0; i < num_entry; i++) {
1303                 if (!stats->ls_percpu[i])
1304                         continue;
1305                 for (j = 0; j < stats->ls_num; j++) {
1306                         percpu_cntr = lprocfs_stats_counter_get(stats, i, j);
1307                         percpu_cntr->lc_count           = 0;
1308                         percpu_cntr->lc_min             = LC_MIN_INIT;
1309                         percpu_cntr->lc_max             = 0;
1310                         percpu_cntr->lc_sumsquare       = 0;
1311                         percpu_cntr->lc_sum             = 0;
1312                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
1313                                 percpu_cntr->lc_sum_irq = 0;
1314                 }
1315         }
1316
1317         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1318 }
1319 EXPORT_SYMBOL(lprocfs_clear_stats);
1320
1321 static ssize_t lprocfs_stats_seq_write(struct file *file,
1322                                        const char __user *buf,
1323                                        size_t len, loff_t *off)
1324 {
1325         struct seq_file *seq = file->private_data;
1326         struct lprocfs_stats *stats = seq->private;
1327
1328         lprocfs_clear_stats(stats);
1329
1330         return len;
1331 }
1332
1333 static void *lprocfs_stats_seq_start(struct seq_file *p, loff_t *pos)
1334 {
1335         struct lprocfs_stats *stats = p->private;
1336
1337         return (*pos < stats->ls_num) ? pos : NULL;
1338 }
1339
1340 static void lprocfs_stats_seq_stop(struct seq_file *p, void *v)
1341 {
1342 }
1343
1344 static void *lprocfs_stats_seq_next(struct seq_file *p, void *v, loff_t *pos)
1345 {
1346         (*pos)++;
1347
1348         return lprocfs_stats_seq_start(p, pos);
1349 }
1350
1351 /* seq file export of one lprocfs counter */
1352 static int lprocfs_stats_seq_show(struct seq_file *p, void *v)
1353 {
1354         struct lprocfs_stats *stats = p->private;
1355         struct lprocfs_counter_header *hdr;
1356         struct lprocfs_counter ctr;
1357         int idx = *(loff_t *)v;
1358
1359         if (idx == 0) {
1360                 struct timespec64 now;
1361
1362                 ktime_get_real_ts64(&now);
1363                 seq_printf(p, "%-25s %llu.%09lu secs.nsecs\n",
1364                            "snapshot_time", (s64)now.tv_sec, now.tv_nsec);
1365         }
1366
1367         hdr = &stats->ls_cnt_header[idx];
1368         lprocfs_stats_collect(stats, idx, &ctr);
1369
1370         if (ctr.lc_count == 0)
1371                 return 0;
1372
1373         seq_printf(p, "%-25s %lld samples [%s]", hdr->lc_name,
1374                    ctr.lc_count, hdr->lc_units);
1375
1376         if ((hdr->lc_config & LPROCFS_CNTR_AVGMINMAX) && ctr.lc_count > 0) {
1377                 seq_printf(p, " %lld %lld %lld",
1378                            ctr.lc_min, ctr.lc_max, ctr.lc_sum);
1379                 if (hdr->lc_config & LPROCFS_CNTR_STDDEV)
1380                         seq_printf(p, " %llu", ctr.lc_sumsquare);
1381         }
1382         seq_putc(p, '\n');
1383         return 0;
1384 }
1385
1386 static const struct seq_operations lprocfs_stats_seq_sops = {
1387         .start  = lprocfs_stats_seq_start,
1388         .stop   = lprocfs_stats_seq_stop,
1389         .next   = lprocfs_stats_seq_next,
1390         .show   = lprocfs_stats_seq_show,
1391 };
1392
1393 static int lprocfs_stats_seq_open(struct inode *inode, struct file *file)
1394 {
1395         struct seq_file *seq;
1396         int rc;
1397
1398         rc = seq_open(file, &lprocfs_stats_seq_sops);
1399         if (rc)
1400                 return rc;
1401         seq = file->private_data;
1402         seq->private = inode->i_private ? inode->i_private : PDE_DATA(inode);
1403         return 0;
1404 }
1405
1406 const struct file_operations ldebugfs_stats_seq_fops = {
1407         .owner   = THIS_MODULE,
1408         .open    = lprocfs_stats_seq_open,
1409         .read    = seq_read,
1410         .write   = lprocfs_stats_seq_write,
1411         .llseek  = seq_lseek,
1412         .release = lprocfs_seq_release,
1413 };
1414 EXPORT_SYMBOL(ldebugfs_stats_seq_fops);
1415
1416 static const struct file_operations lprocfs_stats_seq_fops = {
1417         .owner   = THIS_MODULE,
1418         .open    = lprocfs_stats_seq_open,
1419         .read    = seq_read,
1420         .write   = lprocfs_stats_seq_write,
1421         .llseek  = seq_lseek,
1422         .release = lprocfs_seq_release,
1423 };
1424
1425 int lprocfs_register_stats(struct proc_dir_entry *root, const char *name,
1426                            struct lprocfs_stats *stats)
1427 {
1428         struct proc_dir_entry *entry;
1429         LASSERT(root != NULL);
1430
1431         entry = proc_create_data(name, 0644, root,
1432                                  &lprocfs_stats_seq_fops, stats);
1433         if (!entry)
1434                 return -ENOMEM;
1435         return 0;
1436 }
1437 EXPORT_SYMBOL(lprocfs_register_stats);
1438
1439 void lprocfs_counter_init(struct lprocfs_stats *stats, int index,
1440                           unsigned conf, const char *name, const char *units)
1441 {
1442         struct lprocfs_counter_header *header;
1443         struct lprocfs_counter *percpu_cntr;
1444         unsigned long flags = 0;
1445         unsigned int i;
1446         unsigned int num_cpu;
1447
1448         LASSERT(stats != NULL);
1449
1450         header = &stats->ls_cnt_header[index];
1451         LASSERTF(header != NULL, "Failed to allocate stats header:[%d]%s/%s\n",
1452                  index, name, units);
1453
1454         header->lc_config = conf;
1455         header->lc_name   = name;
1456         header->lc_units  = units;
1457
1458         num_cpu = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1459         for (i = 0; i < num_cpu; ++i) {
1460                 if (!stats->ls_percpu[i])
1461                         continue;
1462                 percpu_cntr = lprocfs_stats_counter_get(stats, i, index);
1463                 percpu_cntr->lc_count           = 0;
1464                 percpu_cntr->lc_min             = LC_MIN_INIT;
1465                 percpu_cntr->lc_max             = 0;
1466                 percpu_cntr->lc_sumsquare       = 0;
1467                 percpu_cntr->lc_sum             = 0;
1468                 if ((stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0)
1469                         percpu_cntr->lc_sum_irq = 0;
1470         }
1471         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1472 }
1473 EXPORT_SYMBOL(lprocfs_counter_init);
1474
1475 static const char * const mps_stats[] = {
1476         [LPROC_MD_CLOSE]                = "close",
1477         [LPROC_MD_CREATE]               = "create",
1478         [LPROC_MD_ENQUEUE]              = "enqueue",
1479         [LPROC_MD_GETATTR]              = "getattr",
1480         [LPROC_MD_INTENT_LOCK]          = "intent_lock",
1481         [LPROC_MD_LINK]                 = "link",
1482         [LPROC_MD_RENAME]               = "rename",
1483         [LPROC_MD_SETATTR]              = "setattr",
1484         [LPROC_MD_FSYNC]                = "fsync",
1485         [LPROC_MD_READ_PAGE]            = "read_page",
1486         [LPROC_MD_UNLINK]               = "unlink",
1487         [LPROC_MD_SETXATTR]             = "setxattr",
1488         [LPROC_MD_GETXATTR]             = "getxattr",
1489         [LPROC_MD_INTENT_GETATTR_ASYNC] = "intent_getattr_async",
1490         [LPROC_MD_REVALIDATE_LOCK]      = "revalidate_lock",
1491 };
1492
1493 int lprocfs_alloc_md_stats(struct obd_device *obd,
1494                            unsigned int num_private_stats)
1495 {
1496         struct lprocfs_stats *stats;
1497         unsigned int num_stats;
1498         int rc, i;
1499
1500         /*
1501          * TODO Ensure that this function is only used where
1502          * appropriate by adding an assertion to the effect that
1503          * obd->obd_type->typ_md_ops is not NULL. We can't do this now
1504          * because mdt_procfs_init() uses this function to allocate
1505          * the stats backing /proc/fs/lustre/mdt/.../md_stats but the
1506          * mdt layer does not use the md_ops interface. This is
1507          * confusing and a waste of memory. See LU-2484.
1508          */
1509         LASSERT(obd->obd_proc_entry != NULL);
1510         LASSERT(obd->obd_md_stats == NULL);
1511
1512         num_stats = ARRAY_SIZE(mps_stats) + num_private_stats;
1513         stats = lprocfs_alloc_stats(num_stats, 0);
1514         if (!stats)
1515                 return -ENOMEM;
1516
1517         for (i = 0; i < ARRAY_SIZE(mps_stats); i++) {
1518                 lprocfs_counter_init(stats, i, 0, mps_stats[i], "reqs");
1519                 if (!stats->ls_cnt_header[i].lc_name) {
1520                         CERROR("Missing md_stat initializer md_op operation at offset %d. Aborting.\n",
1521                                i);
1522                         LBUG();
1523                 }
1524         }
1525
1526         rc = lprocfs_register_stats(obd->obd_proc_entry, "md_stats", stats);
1527         if (rc < 0) {
1528                 lprocfs_free_stats(&stats);
1529         } else {
1530                 obd->obd_md_stats = stats;
1531         }
1532
1533         return rc;
1534 }
1535 EXPORT_SYMBOL(lprocfs_alloc_md_stats);
1536
1537 void lprocfs_free_md_stats(struct obd_device *obd)
1538 {
1539         struct lprocfs_stats *stats = obd->obd_md_stats;
1540
1541         if (stats) {
1542                 obd->obd_md_stats = NULL;
1543                 lprocfs_free_stats(&stats);
1544         }
1545 }
1546 EXPORT_SYMBOL(lprocfs_free_md_stats);
1547
1548 void lprocfs_init_ldlm_stats(struct lprocfs_stats *ldlm_stats)
1549 {
1550         lprocfs_counter_init(ldlm_stats,
1551                              LDLM_ENQUEUE - LDLM_FIRST_OPC,
1552                              0, "ldlm_enqueue", "reqs");
1553         lprocfs_counter_init(ldlm_stats,
1554                              LDLM_CONVERT - LDLM_FIRST_OPC,
1555                              0, "ldlm_convert", "reqs");
1556         lprocfs_counter_init(ldlm_stats,
1557                              LDLM_CANCEL - LDLM_FIRST_OPC,
1558                              0, "ldlm_cancel", "reqs");
1559         lprocfs_counter_init(ldlm_stats,
1560                              LDLM_BL_CALLBACK - LDLM_FIRST_OPC,
1561                              0, "ldlm_bl_callback", "reqs");
1562         lprocfs_counter_init(ldlm_stats,
1563                              LDLM_CP_CALLBACK - LDLM_FIRST_OPC,
1564                              0, "ldlm_cp_callback", "reqs");
1565         lprocfs_counter_init(ldlm_stats,
1566                              LDLM_GL_CALLBACK - LDLM_FIRST_OPC,
1567                              0, "ldlm_gl_callback", "reqs");
1568 }
1569 EXPORT_SYMBOL(lprocfs_init_ldlm_stats);
1570
1571 __s64 lprocfs_read_helper(struct lprocfs_counter *lc,
1572                           struct lprocfs_counter_header *header,
1573                           enum lprocfs_stats_flags flags,
1574                           enum lprocfs_fields_flags field)
1575 {
1576         __s64 ret = 0;
1577
1578         if (!lc || !header)
1579                 RETURN(0);
1580
1581         switch (field) {
1582                 case LPROCFS_FIELDS_FLAGS_CONFIG:
1583                         ret = header->lc_config;
1584                         break;
1585                 case LPROCFS_FIELDS_FLAGS_SUM:
1586                         ret = lc->lc_sum;
1587                         if ((flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0)
1588                                 ret += lc->lc_sum_irq;
1589                         break;
1590                 case LPROCFS_FIELDS_FLAGS_MIN:
1591                         ret = lc->lc_min;
1592                         break;
1593                 case LPROCFS_FIELDS_FLAGS_MAX:
1594                         ret = lc->lc_max;
1595                         break;
1596                 case LPROCFS_FIELDS_FLAGS_AVG:
1597                         ret = (lc->lc_max - lc->lc_min) / 2;
1598                         break;
1599                 case LPROCFS_FIELDS_FLAGS_SUMSQUARE:
1600                         ret = lc->lc_sumsquare;
1601                         break;
1602                 case LPROCFS_FIELDS_FLAGS_COUNT:
1603                         ret = lc->lc_count;
1604                         break;
1605                 default:
1606                         break;
1607         };
1608         RETURN(ret);
1609 }
1610 EXPORT_SYMBOL(lprocfs_read_helper);
1611
1612 /**
1613  * string_to_size - convert ASCII string representing a numerical
1614  *                  value with optional units to 64-bit binary value
1615  *
1616  * @size:       The numerical value extract out of @buffer
1617  * @buffer:     passed in string to parse
1618  * @count:      length of the @buffer
1619  *
1620  * This function returns a 64-bit binary value if @buffer contains a valid
1621  * numerical string. The string is parsed to 3 significant figures after
1622  * the decimal point. Support the string containing an optional units at
1623  * the end which can be base 2 or base 10 in value. If no units are given
1624  * the string is assumed to just a numerical value.
1625  *
1626  * Returns:     @count if the string is successfully parsed,
1627  *              -errno on invalid input strings. Error values:
1628  *
1629  *  - ``-EINVAL``: @buffer is not a proper numerical string
1630  *  - ``-EOVERFLOW``: results does not fit into 64 bits.
1631  *  - ``-E2BIG ``: @buffer is too large (not a valid number)
1632  */
1633 int string_to_size(u64 *size, const char *buffer, size_t count)
1634 {
1635         /* For string_get_size() it can support values above exabytes,
1636          * (ZiB, YiB) due to breaking the return value into a size and
1637          * bulk size to avoid 64 bit overflow. We don't break the size
1638          * up into block size units so we don't support ZiB or YiB.
1639          */
1640         static const char *const units_10[] = {
1641                 "kB", "MB", "GB", "TB", "PB", "EB",
1642         };
1643         static const char *const units_2[] = {
1644                 "K",  "M",  "G",  "T",  "P",  "E",
1645         };
1646         static const char *const *const units_str[] = {
1647                 [STRING_UNITS_2] = units_2,
1648                 [STRING_UNITS_10] = units_10,
1649         };
1650         static const unsigned int coeff[] = {
1651                 [STRING_UNITS_10] = 1000,
1652                 [STRING_UNITS_2] = 1024,
1653         };
1654         enum string_size_units unit = STRING_UNITS_2;
1655         u64 whole, blk_size = 1;
1656         char kernbuf[22], *end;
1657         size_t len = count;
1658         int rc;
1659         int i;
1660
1661         if (count >= sizeof(kernbuf)) {
1662                 CERROR("count %zd > buffer %zd\n", count, sizeof(kernbuf));
1663                 return -E2BIG;
1664         }
1665
1666         *size = 0;
1667         /* The "iB" suffix is optionally allowed for indicating base-2 numbers.
1668          * If suffix is only "B" and not "iB" then we treat it as base-10.
1669          */
1670         end = strstr(buffer, "B");
1671         if (end && *(end - 1) != 'i')
1672                 unit = STRING_UNITS_10;
1673
1674         i = unit == STRING_UNITS_2 ? ARRAY_SIZE(units_2) - 1 :
1675                                      ARRAY_SIZE(units_10) - 1;
1676         do {
1677                 end = strnstr(buffer, units_str[unit][i], count);
1678                 if (end) {
1679                         for (; i >= 0; i--)
1680                                 blk_size *= coeff[unit];
1681                         len = end - buffer;
1682                         break;
1683                 }
1684         } while (i--);
1685
1686         /* as 'B' is a substring of all units, we need to handle it
1687          * separately.
1688          */
1689         if (!end) {
1690                 /* 'B' is only acceptable letter at this point */
1691                 end = strnchr(buffer, count, 'B');
1692                 if (end) {
1693                         len = end - buffer;
1694
1695                         if (count - len > 2 ||
1696                             (count - len == 2 && strcmp(end, "B\n") != 0)) {
1697                                 CDEBUG(D_INFO, "unknown suffix '%s'\n", buffer);
1698                                 return -EINVAL;
1699                         }
1700                 }
1701                 /* kstrtoull will error out if it has non digits */
1702                 goto numbers_only;
1703         }
1704
1705         end = strnchr(buffer, count, '.');
1706         if (end) {
1707                 /* need to limit 3 decimal places */
1708                 char rem[4] = "000";
1709                 u64 frac = 0;
1710                 size_t off;
1711
1712                 len = end - buffer;
1713                 end++;
1714
1715                 /* limit to 3 decimal points */
1716                 off = min_t(size_t, 3, strspn(end, "0123456789"));
1717                 /* need to limit frac_d to a u32 */
1718                 memcpy(rem, end, off);
1719                 rc = kstrtoull(rem, 10, &frac);
1720                 if (rc)
1721                         return rc;
1722
1723                 if (fls64(frac) + fls64(blk_size) - 1 > 64)
1724                         return -EOVERFLOW;
1725
1726                 frac *= blk_size;
1727                 do_div(frac, 1000);
1728                 *size += frac;
1729         }
1730 numbers_only:
1731         snprintf(kernbuf, sizeof(kernbuf), "%.*s", (int)len, buffer);
1732         rc = kstrtoull(kernbuf, 10, &whole);
1733         if (rc)
1734                 return rc;
1735
1736         if (whole != 0 && fls64(whole) + fls64(blk_size) - 1 > 64)
1737                 return -EOVERFLOW;
1738
1739         *size += whole * blk_size;
1740
1741         return count;
1742 }
1743 EXPORT_SYMBOL(string_to_size);
1744
1745 /**
1746  * sysfs_memparse - parse a ASCII string to 64-bit binary value,
1747  *                  with optional units
1748  *
1749  * @buffer:     kernel pointer to input string
1750  * @count:      number of bytes in the input @buffer
1751  * @val:        (output) binary value returned to caller
1752  * @defunit:    default unit suffix to use if none is provided
1753  *
1754  * Parses a string into a number. The number stored at @buffer is
1755  * potentially suffixed with K, M, G, T, P, E. Besides these other
1756  * valid suffix units are shown in the string_to_size() function.
1757  * If the string lacks a suffix then the defunit is used. The defunit
1758  * should be given as a binary unit (e.g. MiB) as that is the standard
1759  * for tunables in Lustre. If no unit suffix is given (e.g. 'G'), then
1760  * it is assumed to be in binary units.
1761  *
1762  * Returns:     0 on success or -errno on failure.
1763  */
1764 int sysfs_memparse(const char *buffer, size_t count, u64 *val,
1765                    const char *defunit)
1766 {
1767         const char *param = buffer;
1768         char tmp_buf[23];
1769         int rc;
1770
1771         count = strlen(buffer);
1772         while (count > 0 && isspace(buffer[count - 1]))
1773                 count--;
1774
1775         if (!count)
1776                 RETURN(-EINVAL);
1777
1778         /* If there isn't already a unit on this value, append @defunit.
1779          * Units of 'B' don't affect the value, so don't bother adding.
1780          */
1781         if (!isalpha(buffer[count - 1]) && defunit[0] != 'B') {
1782                 if (count + 3 >= sizeof(tmp_buf)) {
1783                         CERROR("count %zd > size %zd\n", count, sizeof(param));
1784                         RETURN(-E2BIG);
1785                 }
1786
1787                 scnprintf(tmp_buf, sizeof(tmp_buf), "%.*s%s", (int)count,
1788                           buffer, defunit);
1789                 param = tmp_buf;
1790                 count = strlen(param);
1791         }
1792
1793         rc = string_to_size(val, param, count);
1794
1795         return rc < 0 ? rc : 0;
1796 }
1797 EXPORT_SYMBOL(sysfs_memparse);
1798
1799 char *lprocfs_strnstr(const char *s1, const char *s2, size_t len)
1800 {
1801         size_t l2;
1802
1803         l2 = strlen(s2);
1804         if (!l2)
1805                 return (char *)s1;
1806         while (len >= l2) {
1807                 len--;
1808                 if (!memcmp(s1, s2, l2))
1809                         return (char *)s1;
1810                 s1++;
1811         }
1812         return NULL;
1813 }
1814 EXPORT_SYMBOL(lprocfs_strnstr);
1815
1816 /**
1817  * Find the string \a name in the input \a buffer, and return a pointer to the
1818  * value immediately following \a name, reducing \a count appropriately.
1819  * If \a name is not found the original \a buffer is returned.
1820  */
1821 char *lprocfs_find_named_value(const char *buffer, const char *name,
1822                                 size_t *count)
1823 {
1824         char *val;
1825         size_t buflen = *count;
1826
1827         /* there is no strnstr() in rhel5 and ubuntu kernels */
1828         val = lprocfs_strnstr(buffer, name, buflen);
1829         if (!val)
1830                 return (char *)buffer;
1831
1832         val += strlen(name);                             /* skip prefix */
1833         while (val < buffer + buflen && isspace(*val)) /* skip separator */
1834                 val++;
1835
1836         *count = 0;
1837         while (val < buffer + buflen && isalnum(*val)) {
1838                 ++*count;
1839                 ++val;
1840         }
1841
1842         return val - *count;
1843 }
1844 EXPORT_SYMBOL(lprocfs_find_named_value);
1845
1846 int lprocfs_seq_create(struct proc_dir_entry *parent,
1847                        const char *name,
1848                        mode_t mode,
1849                        const struct file_operations *seq_fops,
1850                        void *data)
1851 {
1852         struct proc_dir_entry *entry;
1853         ENTRY;
1854
1855         /* Disallow secretly (un)writable entries. */
1856         LASSERT((seq_fops->write == NULL) == ((mode & 0222) == 0));
1857
1858         entry = proc_create_data(name, mode, parent, seq_fops, data);
1859
1860         if (!entry)
1861                 RETURN(-ENOMEM);
1862
1863         RETURN(0);
1864 }
1865 EXPORT_SYMBOL(lprocfs_seq_create);
1866
1867 int lprocfs_obd_seq_create(struct obd_device *obd,
1868                            const char *name,
1869                            mode_t mode,
1870                            const struct file_operations *seq_fops,
1871                            void *data)
1872 {
1873         return lprocfs_seq_create(obd->obd_proc_entry, name,
1874                                   mode, seq_fops, data);
1875 }
1876 EXPORT_SYMBOL(lprocfs_obd_seq_create);
1877
1878 void lprocfs_oh_tally(struct obd_histogram *oh, unsigned int value)
1879 {
1880         if (value >= OBD_HIST_MAX)
1881                 value = OBD_HIST_MAX - 1;
1882
1883         spin_lock(&oh->oh_lock);
1884         oh->oh_buckets[value]++;
1885         spin_unlock(&oh->oh_lock);
1886 }
1887 EXPORT_SYMBOL(lprocfs_oh_tally);
1888
1889 void lprocfs_oh_tally_log2(struct obd_histogram *oh, unsigned int value)
1890 {
1891         unsigned int val = 0;
1892
1893         if (likely(value != 0))
1894                 val = min(fls(value - 1), OBD_HIST_MAX);
1895
1896         lprocfs_oh_tally(oh, val);
1897 }
1898 EXPORT_SYMBOL(lprocfs_oh_tally_log2);
1899
1900 unsigned long lprocfs_oh_sum(struct obd_histogram *oh)
1901 {
1902         unsigned long ret = 0;
1903         int i;
1904
1905         for (i = 0; i < OBD_HIST_MAX; i++)
1906                 ret +=  oh->oh_buckets[i];
1907         return ret;
1908 }
1909 EXPORT_SYMBOL(lprocfs_oh_sum);
1910
1911 void lprocfs_oh_clear(struct obd_histogram *oh)
1912 {
1913         spin_lock(&oh->oh_lock);
1914         memset(oh->oh_buckets, 0, sizeof(oh->oh_buckets));
1915         spin_unlock(&oh->oh_lock);
1916 }
1917 EXPORT_SYMBOL(lprocfs_oh_clear);
1918
1919 ssize_t lustre_attr_show(struct kobject *kobj,
1920                          struct attribute *attr, char *buf)
1921 {
1922         struct lustre_attr *a = container_of(attr, struct lustre_attr, attr);
1923
1924         return a->show ? a->show(kobj, attr, buf) : 0;
1925 }
1926 EXPORT_SYMBOL_GPL(lustre_attr_show);
1927
1928 ssize_t lustre_attr_store(struct kobject *kobj, struct attribute *attr,
1929                           const char *buf, size_t len)
1930 {
1931         struct lustre_attr *a = container_of(attr, struct lustre_attr, attr);
1932
1933         return a->store ? a->store(kobj, attr, buf, len) : len;
1934 }
1935 EXPORT_SYMBOL_GPL(lustre_attr_store);
1936
1937 const struct sysfs_ops lustre_sysfs_ops = {
1938         .show  = lustre_attr_show,
1939         .store = lustre_attr_store,
1940 };
1941 EXPORT_SYMBOL_GPL(lustre_sysfs_ops);
1942
1943 int lprocfs_obd_max_pages_per_rpc_seq_show(struct seq_file *m, void *data)
1944 {
1945         struct obd_device *obd = data;
1946         struct client_obd *cli = &obd->u.cli;
1947
1948         spin_lock(&cli->cl_loi_list_lock);
1949         seq_printf(m, "%d\n", cli->cl_max_pages_per_rpc);
1950         spin_unlock(&cli->cl_loi_list_lock);
1951         return 0;
1952 }
1953 EXPORT_SYMBOL(lprocfs_obd_max_pages_per_rpc_seq_show);
1954
1955 ssize_t lprocfs_obd_max_pages_per_rpc_seq_write(struct file *file,
1956                                                 const char __user *buffer,
1957                                                 size_t count, loff_t *off)
1958 {
1959         struct seq_file *m = file->private_data;
1960         struct obd_device *obd = m->private;
1961         struct client_obd *cli = &obd->u.cli;
1962         struct obd_import *imp;
1963         struct obd_connect_data *ocd;
1964         int chunk_mask, rc;
1965         char kernbuf[22];
1966         u64 val;
1967
1968         if (count > sizeof(kernbuf) - 1)
1969                 return -EINVAL;
1970
1971         if (copy_from_user(kernbuf, buffer, count))
1972                 return -EFAULT;
1973
1974         kernbuf[count] = '\0';
1975
1976         rc = sysfs_memparse(kernbuf, count, &val, "B");
1977         if (rc)
1978                 return rc;
1979
1980         /* if the max_pages is specified in bytes, convert to pages */
1981         if (val >= ONE_MB_BRW_SIZE)
1982                 val >>= PAGE_SHIFT;
1983
1984         with_imp_locked(obd, imp, rc) {
1985                 ocd = &imp->imp_connect_data;
1986                 chunk_mask = ~((1 << (cli->cl_chunkbits - PAGE_SHIFT)) - 1);
1987                 /* max_pages_per_rpc must be chunk aligned */
1988                 val = (val + ~chunk_mask) & chunk_mask;
1989                 if (val == 0 || (ocd->ocd_brw_size != 0 &&
1990                                  val > ocd->ocd_brw_size >> PAGE_SHIFT)) {
1991                         rc = -ERANGE;
1992                 } else {
1993                         spin_lock(&cli->cl_loi_list_lock);
1994                         cli->cl_max_pages_per_rpc = val;
1995                         client_adjust_max_dirty(cli);
1996                         spin_unlock(&cli->cl_loi_list_lock);
1997                 }
1998         }
1999
2000         return rc ?: count;
2001 }
2002 EXPORT_SYMBOL(lprocfs_obd_max_pages_per_rpc_seq_write);
2003
2004 ssize_t short_io_bytes_show(struct kobject *kobj, struct attribute *attr,
2005                             char *buf)
2006 {
2007         struct obd_device *obd = container_of(kobj, struct obd_device,
2008                                               obd_kset.kobj);
2009         struct client_obd *cli = &obd->u.cli;
2010         int rc;
2011
2012         spin_lock(&cli->cl_loi_list_lock);
2013         rc = sprintf(buf, "%d\n", cli->cl_max_short_io_bytes);
2014         spin_unlock(&cli->cl_loi_list_lock);
2015         return rc;
2016 }
2017 EXPORT_SYMBOL(short_io_bytes_show);
2018
2019 /* Used to catch people who think they're specifying pages. */
2020 #define MIN_SHORT_IO_BYTES 64U
2021
2022 ssize_t short_io_bytes_store(struct kobject *kobj, struct attribute *attr,
2023                              const char *buffer, size_t count)
2024 {
2025         struct obd_device *obd = container_of(kobj, struct obd_device,
2026                                               obd_kset.kobj);
2027         struct client_obd *cli = &obd->u.cli;
2028         u64 val;
2029         int rc;
2030
2031         if (strcmp(buffer, "-1") == 0) {
2032                 val = OBD_DEF_SHORT_IO_BYTES;
2033         } else {
2034                 rc = sysfs_memparse(buffer, count, &val, "B");
2035                 if (rc)
2036                         GOTO(out, rc);
2037         }
2038
2039         if (val && (val < MIN_SHORT_IO_BYTES || val > LNET_MTU))
2040                 GOTO(out, rc = -ERANGE);
2041
2042         rc = count;
2043
2044         spin_lock(&cli->cl_loi_list_lock);
2045         cli->cl_max_short_io_bytes = min_t(u64, val, OST_MAX_SHORT_IO_BYTES);
2046         spin_unlock(&cli->cl_loi_list_lock);
2047
2048 out:
2049         return rc;
2050 }
2051 EXPORT_SYMBOL(short_io_bytes_store);
2052
2053 int lprocfs_wr_root_squash(const char __user *buffer, unsigned long count,
2054                            struct root_squash_info *squash, char *name)
2055 {
2056         int rc;
2057         char kernbuf[64], *tmp, *errmsg;
2058         unsigned long uid, gid;
2059         ENTRY;
2060
2061         if (count >= sizeof(kernbuf)) {
2062                 errmsg = "string too long";
2063                 GOTO(failed_noprint, rc = -EINVAL);
2064         }
2065         if (copy_from_user(kernbuf, buffer, count)) {
2066                 errmsg = "bad address";
2067                 GOTO(failed_noprint, rc = -EFAULT);
2068         }
2069         kernbuf[count] = '\0';
2070
2071         /* look for uid gid separator */
2072         tmp = strchr(kernbuf, ':');
2073         if (!tmp) {
2074                 errmsg = "needs uid:gid format";
2075                 GOTO(failed, rc = -EINVAL);
2076         }
2077         *tmp = '\0';
2078         tmp++;
2079
2080         /* parse uid */
2081         if (kstrtoul(kernbuf, 0, &uid) != 0) {
2082                 errmsg = "bad uid";
2083                 GOTO(failed, rc = -EINVAL);
2084         }
2085
2086         /* parse gid */
2087         if (kstrtoul(tmp, 0, &gid) != 0) {
2088                 errmsg = "bad gid";
2089                 GOTO(failed, rc = -EINVAL);
2090         }
2091
2092         squash->rsi_uid = uid;
2093         squash->rsi_gid = gid;
2094
2095         LCONSOLE_INFO("%s: root_squash is set to %u:%u\n",
2096                       name, squash->rsi_uid, squash->rsi_gid);
2097         RETURN(count);
2098
2099 failed:
2100         if (tmp) {
2101                 tmp--;
2102                 *tmp = ':';
2103         }
2104         CWARN("%s: failed to set root_squash to \"%s\", %s, rc = %d\n",
2105               name, kernbuf, errmsg, rc);
2106         RETURN(rc);
2107 failed_noprint:
2108         CWARN("%s: failed to set root_squash due to %s, rc = %d\n",
2109               name, errmsg, rc);
2110         RETURN(rc);
2111 }
2112 EXPORT_SYMBOL(lprocfs_wr_root_squash);
2113
2114
2115 int lprocfs_wr_nosquash_nids(const char __user *buffer, unsigned long count,
2116                              struct root_squash_info *squash, char *name)
2117 {
2118         int rc;
2119         char *kernbuf = NULL;
2120         char *errmsg;
2121         LIST_HEAD(tmp);
2122         int len = count;
2123         ENTRY;
2124
2125         if (count > 4096) {
2126                 errmsg = "string too long";
2127                 GOTO(failed, rc = -EINVAL);
2128         }
2129
2130         OBD_ALLOC(kernbuf, count + 1);
2131         if (!kernbuf) {
2132                 errmsg = "no memory";
2133                 GOTO(failed, rc = -ENOMEM);
2134         }
2135         if (copy_from_user(kernbuf, buffer, count)) {
2136                 errmsg = "bad address";
2137                 GOTO(failed, rc = -EFAULT);
2138         }
2139         kernbuf[count] = '\0';
2140
2141         if (count > 0 && kernbuf[count - 1] == '\n')
2142                 len = count - 1;
2143
2144         if ((len == 4 && strncmp(kernbuf, "NONE", len) == 0) ||
2145             (len == 5 && strncmp(kernbuf, "clear", len) == 0)) {
2146                 /* empty string is special case */
2147                 spin_lock(&squash->rsi_lock);
2148                 if (!list_empty(&squash->rsi_nosquash_nids))
2149                         cfs_free_nidlist(&squash->rsi_nosquash_nids);
2150                 spin_unlock(&squash->rsi_lock);
2151                 LCONSOLE_INFO("%s: nosquash_nids is cleared\n", name);
2152                 OBD_FREE(kernbuf, count + 1);
2153                 RETURN(count);
2154         }
2155
2156         if (cfs_parse_nidlist(kernbuf, count, &tmp) <= 0) {
2157                 errmsg = "can't parse";
2158                 GOTO(failed, rc = -EINVAL);
2159         }
2160         LCONSOLE_INFO("%s: nosquash_nids set to %s\n",
2161                       name, kernbuf);
2162         OBD_FREE(kernbuf, count + 1);
2163         kernbuf = NULL;
2164
2165         spin_lock(&squash->rsi_lock);
2166         if (!list_empty(&squash->rsi_nosquash_nids))
2167                 cfs_free_nidlist(&squash->rsi_nosquash_nids);
2168         list_splice(&tmp, &squash->rsi_nosquash_nids);
2169         spin_unlock(&squash->rsi_lock);
2170
2171         RETURN(count);
2172
2173 failed:
2174         if (kernbuf) {
2175                 CWARN("%s: failed to set nosquash_nids to \"%s\", %s rc = %d\n",
2176                       name, kernbuf, errmsg, rc);
2177                 OBD_FREE(kernbuf, count + 1);
2178         } else {
2179                 CWARN("%s: failed to set nosquash_nids due to %s rc = %d\n",
2180                       name, errmsg, rc);
2181         }
2182         RETURN(rc);
2183 }
2184 EXPORT_SYMBOL(lprocfs_wr_nosquash_nids);
2185
2186 #endif /* CONFIG_PROC_FS*/