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