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