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