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