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