Whamcloud - gitweb
LU-9109 ldlm: restore missing newlines in ldlm sysfs files
[fs/lustre-release.git] / lustre / ldlm / ldlm_resource.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) 2010, 2016, 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/ldlm/ldlm_resource.c
33  *
34  * Author: Phil Schwan <phil@clusterfs.com>
35  * Author: Peter Braam <braam@clusterfs.com>
36  */
37
38 #define DEBUG_SUBSYSTEM S_LDLM
39 #include <lustre_dlm.h>
40 #include <lustre_fid.h>
41 #include <obd_class.h>
42 #include "ldlm_internal.h"
43
44 struct kmem_cache *ldlm_resource_slab, *ldlm_lock_slab;
45 struct kmem_cache *ldlm_interval_tree_slab;
46
47 int ldlm_srv_namespace_nr = 0;
48 int ldlm_cli_namespace_nr = 0;
49
50 struct mutex ldlm_srv_namespace_lock;
51 struct list_head ldlm_srv_namespace_list;
52
53 struct mutex ldlm_cli_namespace_lock;
54 /* Client Namespaces that have active resources in them.
55  * Once all resources go away, ldlm_poold moves such namespaces to the
56  * inactive list */
57 struct list_head ldlm_cli_active_namespace_list;
58 /* Client namespaces that don't have any locks in them */
59 struct list_head ldlm_cli_inactive_namespace_list;
60
61 static struct proc_dir_entry *ldlm_type_proc_dir;
62 static struct proc_dir_entry *ldlm_ns_proc_dir;
63 struct proc_dir_entry *ldlm_svc_proc_dir;
64
65 /* during debug dump certain amount of granted locks for one resource to avoid
66  * DDOS. */
67 static unsigned int ldlm_dump_granted_max = 256;
68
69 #ifdef CONFIG_PROC_FS
70 static ssize_t
71 lprocfs_dump_ns_seq_write(struct file *file, const char __user *buffer,
72                           size_t count, loff_t *off)
73 {
74         ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
75         ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
76         RETURN(count);
77 }
78 LPROC_SEQ_FOPS_WO_TYPE(ldlm, dump_ns);
79
80 LPROC_SEQ_FOPS_RW_TYPE(ldlm_rw, uint);
81 LPROC_SEQ_FOPS_RO_TYPE(ldlm, uint);
82
83 #ifdef HAVE_SERVER_SUPPORT
84
85 static int seq_watermark_show(struct seq_file *m, void *data)
86 {
87         seq_printf(m, "%llu\n", *(__u64 *)m->private);
88         return 0;
89 }
90
91 static ssize_t seq_watermark_write(struct file *file,
92                                    const char __user *buffer, size_t count,
93                                    loff_t *off)
94 {
95         __s64 value;
96         __u64 watermark;
97         __u64 *data = ((struct seq_file *)file->private_data)->private;
98         bool wm_low = (data == &ldlm_reclaim_threshold_mb) ? true : false;
99         int rc;
100
101         rc = lprocfs_str_with_units_to_s64(buffer, count, &value, 'M');
102         if (rc) {
103                 CERROR("Failed to set %s, rc = %d.\n",
104                        wm_low ? "lock_reclaim_threshold_mb" : "lock_limit_mb",
105                        rc);
106                 return rc;
107         } else if (value != 0 && value < (1 << 20)) {
108                 CERROR("%s should be greater than 1MB.\n",
109                        wm_low ? "lock_reclaim_threshold_mb" : "lock_limit_mb");
110                 return -EINVAL;
111         }
112         watermark = value >> 20;
113
114         if (wm_low) {
115                 if (ldlm_lock_limit_mb != 0 && watermark > ldlm_lock_limit_mb) {
116                         CERROR("lock_reclaim_threshold_mb must be smaller than "
117                                "lock_limit_mb.\n");
118                         return -EINVAL;
119                 }
120
121                 *data = watermark;
122                 if (watermark != 0) {
123                         watermark <<= 20;
124                         do_div(watermark, sizeof(struct ldlm_lock));
125                 }
126                 ldlm_reclaim_threshold = watermark;
127         } else {
128                 if (ldlm_reclaim_threshold_mb != 0 &&
129                     watermark < ldlm_reclaim_threshold_mb) {
130                         CERROR("lock_limit_mb must be greater than "
131                                "lock_reclaim_threshold_mb.\n");
132                         return -EINVAL;
133                 }
134
135                 *data = watermark;
136                 if (watermark != 0) {
137                         watermark <<= 20;
138                         do_div(watermark, sizeof(struct ldlm_lock));
139                 }
140                 ldlm_lock_limit = watermark;
141         }
142
143         return count;
144 }
145
146 static int seq_watermark_open(struct inode *inode, struct file *file)
147 {
148         return single_open(file, seq_watermark_show, PDE_DATA(inode));
149 }
150
151 static const struct file_operations ldlm_watermark_fops = {
152         .owner          = THIS_MODULE,
153         .open           = seq_watermark_open,
154         .read           = seq_read,
155         .write          = seq_watermark_write,
156         .llseek         = seq_lseek,
157         .release        = lprocfs_single_release,
158 };
159
160 static int seq_granted_show(struct seq_file *m, void *data)
161 {
162         seq_printf(m, "%llu\n", percpu_counter_sum_positive(
163                    (struct percpu_counter *)m->private));
164         return 0;
165 }
166
167 static int seq_granted_open(struct inode *inode, struct file *file)
168 {
169         return single_open(file, seq_granted_show, PDE_DATA(inode));
170 }
171
172 static const struct file_operations ldlm_granted_fops = {
173         .owner  = THIS_MODULE,
174         .open   = seq_granted_open,
175         .read   = seq_read,
176         .llseek = seq_lseek,
177         .release = seq_release,
178 };
179
180 #endif /* HAVE_SERVER_SUPPORT */
181
182 int ldlm_proc_setup(void)
183 {
184         int rc;
185         struct lprocfs_vars list[] = {
186                 { .name =       "dump_namespaces",
187                   .fops =       &ldlm_dump_ns_fops,
188                   .proc_mode =  0222 },
189                 { .name =       "dump_granted_max",
190                   .fops =       &ldlm_rw_uint_fops,
191                   .data =       &ldlm_dump_granted_max },
192 #ifdef HAVE_SERVER_SUPPORT
193                 { .name =       "lock_reclaim_threshold_mb",
194                   .fops =       &ldlm_watermark_fops,
195                   .data =       &ldlm_reclaim_threshold_mb },
196                 { .name =       "lock_limit_mb",
197                   .fops =       &ldlm_watermark_fops,
198                   .data =       &ldlm_lock_limit_mb },
199                 { .name =       "lock_granted_count",
200                   .fops =       &ldlm_granted_fops,
201                   .data =       &ldlm_granted_total },
202 #endif
203                 { NULL }};
204         ENTRY;
205         LASSERT(ldlm_ns_proc_dir == NULL);
206
207         ldlm_type_proc_dir = lprocfs_register(OBD_LDLM_DEVICENAME,
208                                               proc_lustre_root,
209                                               NULL, NULL);
210         if (IS_ERR(ldlm_type_proc_dir)) {
211                 CERROR("LProcFS failed in ldlm-init\n");
212                 rc = PTR_ERR(ldlm_type_proc_dir);
213                 GOTO(err, rc);
214         }
215
216         ldlm_ns_proc_dir = lprocfs_register("namespaces",
217                                             ldlm_type_proc_dir,
218                                             NULL, NULL);
219         if (IS_ERR(ldlm_ns_proc_dir)) {
220                 CERROR("LProcFS failed in ldlm-init\n");
221                 rc = PTR_ERR(ldlm_ns_proc_dir);
222                 GOTO(err_type, rc);
223         }
224
225         ldlm_svc_proc_dir = lprocfs_register("services",
226                                              ldlm_type_proc_dir,
227                                              NULL, NULL);
228         if (IS_ERR(ldlm_svc_proc_dir)) {
229                 CERROR("LProcFS failed in ldlm-init\n");
230                 rc = PTR_ERR(ldlm_svc_proc_dir);
231                 GOTO(err_ns, rc);
232         }
233
234         rc = lprocfs_add_vars(ldlm_type_proc_dir, list, NULL);
235         if (rc != 0) {
236                 CERROR("LProcFS failed in ldlm-init\n");
237                 GOTO(err_svc, rc);
238         }
239
240         RETURN(0);
241
242 err_svc:
243         lprocfs_remove(&ldlm_svc_proc_dir);
244 err_ns:
245         lprocfs_remove(&ldlm_ns_proc_dir);
246 err_type:
247         lprocfs_remove(&ldlm_type_proc_dir);
248 err:
249         ldlm_svc_proc_dir = NULL;
250         RETURN(rc);
251 }
252
253 void ldlm_proc_cleanup(void)
254 {
255         if (ldlm_svc_proc_dir)
256                 lprocfs_remove(&ldlm_svc_proc_dir);
257
258         if (ldlm_ns_proc_dir)
259                 lprocfs_remove(&ldlm_ns_proc_dir);
260
261         if (ldlm_type_proc_dir)
262                 lprocfs_remove(&ldlm_type_proc_dir);
263 }
264
265 static ssize_t resource_count_show(struct kobject *kobj, struct attribute *attr,
266                                    char *buf)
267 {
268         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
269                                                  ns_kobj);
270         __u64                   res = 0;
271         struct cfs_hash_bd              bd;
272         int                     i;
273
274         /* result is not strictly consistant */
275         cfs_hash_for_each_bucket(ns->ns_rs_hash, &bd, i)
276                 res += cfs_hash_bd_count_get(&bd);
277         return sprintf(buf, "%lld\n", res);
278 }
279 LUSTRE_RO_ATTR(resource_count);
280
281 static ssize_t lock_count_show(struct kobject *kobj, struct attribute *attr,
282                                char *buf)
283 {
284         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
285                                                  ns_kobj);
286         __u64                   locks;
287
288         locks = lprocfs_stats_collector(ns->ns_stats, LDLM_NSS_LOCKS,
289                                         LPROCFS_FIELDS_FLAGS_SUM);
290         return sprintf(buf, "%lld\n", locks);
291 }
292 LUSTRE_RO_ATTR(lock_count);
293
294 static ssize_t lock_unused_count_show(struct kobject *kobj,
295                                       struct attribute *attr,
296                                       char *buf)
297 {
298         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
299                                                  ns_kobj);
300
301         return sprintf(buf, "%d\n", ns->ns_nr_unused);
302 }
303 LUSTRE_RO_ATTR(lock_unused_count);
304
305 static ssize_t lru_size_show(struct kobject *kobj, struct attribute *attr,
306                              char *buf)
307 {
308         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
309                                                  ns_kobj);
310         __u32 *nr = &ns->ns_max_unused;
311
312         if (ns_connect_lru_resize(ns))
313                 nr = &ns->ns_nr_unused;
314         return sprintf(buf, "%u\n", *nr);
315 }
316
317 static ssize_t lru_size_store(struct kobject *kobj, struct attribute *attr,
318                               const char *buffer, size_t count)
319 {
320         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
321                                                  ns_kobj);
322         unsigned long tmp;
323         int lru_resize;
324         int err;
325
326         if (strncmp(buffer, "clear", 5) == 0) {
327                 CDEBUG(D_DLMTRACE,
328                        "dropping all unused locks from namespace %s\n",
329                        ldlm_ns_name(ns));
330                 if (ns_connect_lru_resize(ns)) {
331                         int canceled, unused  = ns->ns_nr_unused;
332
333                         /* Try to cancel all @ns_nr_unused locks. */
334                         canceled = ldlm_cancel_lru(ns, unused, 0,
335                                                    LDLM_LRU_FLAG_PASSED);
336                         if (canceled < unused) {
337                                 CDEBUG(D_DLMTRACE,
338                                        "not all requested locks are canceled, requested: %d, canceled: %d\n",
339                                        unused,
340                                        canceled);
341                                 return -EINVAL;
342                         }
343                 } else {
344                         tmp = ns->ns_max_unused;
345                         ns->ns_max_unused = 0;
346                         ldlm_cancel_lru(ns, 0, 0, LDLM_LRU_FLAG_PASSED);
347                         ns->ns_max_unused = tmp;
348                 }
349                 return count;
350         }
351
352         err = kstrtoul(buffer, 10, &tmp);
353         if (err != 0) {
354                 CERROR("lru_size: invalid value written\n");
355                 return -EINVAL;
356         }
357         lru_resize = (tmp == 0);
358
359         if (ns_connect_lru_resize(ns)) {
360                 if (!lru_resize)
361                         ns->ns_max_unused = (unsigned int)tmp;
362
363                 if (tmp > ns->ns_nr_unused)
364                         tmp = ns->ns_nr_unused;
365                 tmp = ns->ns_nr_unused - tmp;
366
367                 CDEBUG(D_DLMTRACE,
368                        "changing namespace %s unused locks from %u to %u\n",
369                        ldlm_ns_name(ns), ns->ns_nr_unused,
370                        (unsigned int)tmp);
371                 ldlm_cancel_lru(ns, tmp, LCF_ASYNC, LDLM_LRU_FLAG_PASSED);
372
373                 if (!lru_resize) {
374                         CDEBUG(D_DLMTRACE,
375                                "disable lru_resize for namespace %s\n",
376                                ldlm_ns_name(ns));
377                         ns->ns_connect_flags &= ~OBD_CONNECT_LRU_RESIZE;
378                 }
379         } else {
380                 CDEBUG(D_DLMTRACE,
381                        "changing namespace %s max_unused from %u to %u\n",
382                        ldlm_ns_name(ns), ns->ns_max_unused,
383                        (unsigned int)tmp);
384                 ns->ns_max_unused = (unsigned int)tmp;
385                 ldlm_cancel_lru(ns, 0, LCF_ASYNC, LDLM_LRU_FLAG_PASSED);
386
387                 /* Make sure that LRU resize was originally supported before
388                  * turning it on here.
389                  */
390                 if (lru_resize &&
391                     (ns->ns_orig_connect_flags & OBD_CONNECT_LRU_RESIZE)) {
392                         CDEBUG(D_DLMTRACE,
393                                "enable lru_resize for namespace %s\n",
394                                ldlm_ns_name(ns));
395                         ns->ns_connect_flags |= OBD_CONNECT_LRU_RESIZE;
396                 }
397         }
398
399         return count;
400 }
401 LUSTRE_RW_ATTR(lru_size);
402
403 static ssize_t lru_max_age_show(struct kobject *kobj, struct attribute *attr,
404                                 char *buf)
405 {
406         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
407                                                  ns_kobj);
408
409         return sprintf(buf, "%u\n", ns->ns_max_age);
410 }
411
412 static ssize_t lru_max_age_store(struct kobject *kobj, struct attribute *attr,
413                                  const char *buffer, size_t count)
414 {
415         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
416                                                  ns_kobj);
417         unsigned long tmp;
418         int err;
419
420         err = kstrtoul(buffer, 10, &tmp);
421         if (err != 0)
422                 return -EINVAL;
423
424         ns->ns_max_age = tmp;
425
426         return count;
427 }
428 LUSTRE_RW_ATTR(lru_max_age);
429
430 static ssize_t early_lock_cancel_show(struct kobject *kobj,
431                                       struct attribute *attr,
432                                       char *buf)
433 {
434         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
435                                                  ns_kobj);
436
437         return sprintf(buf, "%d\n", ns_connect_cancelset(ns));
438 }
439
440 static ssize_t early_lock_cancel_store(struct kobject *kobj,
441                                        struct attribute *attr,
442                                        const char *buffer,
443                                        size_t count)
444 {
445         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
446                                                  ns_kobj);
447         unsigned long supp = -1;
448         int rc;
449
450         rc = kstrtoul(buffer, 10, &supp);
451         if (rc < 0)
452                 return rc;
453
454         if (supp == 0)
455                 ns->ns_connect_flags &= ~OBD_CONNECT_CANCELSET;
456         else if (ns->ns_orig_connect_flags & OBD_CONNECT_CANCELSET)
457                 ns->ns_connect_flags |= OBD_CONNECT_CANCELSET;
458         return count;
459 }
460 LUSTRE_RW_ATTR(early_lock_cancel);
461
462 #ifdef HAVE_SERVER_SUPPORT
463 static ssize_t ctime_age_limit_show(struct kobject *kobj,
464                                     struct attribute *attr, char *buf)
465 {
466         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
467                                                  ns_kobj);
468
469         return sprintf(buf, "%u\n", ns->ns_ctime_age_limit);
470 }
471
472 static ssize_t ctime_age_limit_store(struct kobject *kobj,
473                                      struct attribute *attr,
474                                      const char *buffer, size_t count)
475 {
476         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
477                                                  ns_kobj);
478         unsigned long tmp;
479         int err;
480
481         err = kstrtoul(buffer, 10, &tmp);
482         if (err != 0)
483                 return -EINVAL;
484
485         ns->ns_ctime_age_limit = tmp;
486
487         return count;
488 }
489 LUSTRE_RW_ATTR(ctime_age_limit);
490
491 static ssize_t lock_timeouts_show(struct kobject *kobj, struct attribute *attr,
492                                   char *buf)
493 {
494         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
495                                                  ns_kobj);
496
497         return sprintf(buf, "%d\n", ns->ns_timeouts);
498 }
499 LUSTRE_RO_ATTR(lock_timeouts);
500
501 static ssize_t max_nolock_bytes_show(struct kobject *kobj,
502                                      struct attribute *attr, char *buf)
503 {
504         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
505                                                  ns_kobj);
506
507         return sprintf(buf, "%u\n", ns->ns_max_nolock_size);
508 }
509
510 static ssize_t max_nolock_bytes_store(struct kobject *kobj,
511                                       struct attribute *attr,
512                                       const char *buffer, size_t count)
513 {
514         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
515                                                  ns_kobj);
516         unsigned long tmp;
517         int err;
518
519         err = kstrtoul(buffer, 10, &tmp);
520         if (err != 0)
521                 return -EINVAL;
522
523         ns->ns_max_nolock_size = tmp;
524
525         return count;
526 }
527 LUSTRE_RW_ATTR(max_nolock_bytes);
528
529 static ssize_t contention_seconds_show(struct kobject *kobj,
530                                        struct attribute *attr, char *buf)
531 {
532         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
533                                                  ns_kobj);
534
535         return sprintf(buf, "%u\n", ns->ns_contention_time);
536 }
537
538 static ssize_t contention_seconds_store(struct kobject *kobj,
539                                         struct attribute *attr,
540                                         const char *buffer, size_t count)
541 {
542         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
543                                                  ns_kobj);
544         unsigned long tmp;
545         int err;
546
547         err = kstrtoul(buffer, 10, &tmp);
548         if (err != 0)
549                 return -EINVAL;
550
551         ns->ns_contention_time = tmp;
552
553         return count;
554 }
555 LUSTRE_RW_ATTR(contention_seconds);
556
557 static ssize_t contended_locks_show(struct kobject *kobj,
558                                     struct attribute *attr, char *buf)
559 {
560         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
561                                                  ns_kobj);
562
563         return sprintf(buf, "%u\n", ns->ns_contended_locks);
564 }
565
566 static ssize_t contended_locks_store(struct kobject *kobj,
567                                      struct attribute *attr,
568                                      const char *buffer, size_t count)
569 {
570         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
571                                                  ns_kobj);
572         unsigned long tmp;
573         int err;
574
575         err = kstrtoul(buffer, 10, &tmp);
576         if (err != 0)
577                 return -EINVAL;
578
579         ns->ns_contended_locks = tmp;
580
581         return count;
582 }
583 LUSTRE_RW_ATTR(contended_locks);
584
585 static ssize_t max_parallel_ast_show(struct kobject *kobj,
586                                      struct attribute *attr, char *buf)
587 {
588         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
589                                                  ns_kobj);
590
591         return sprintf(buf, "%u\n", ns->ns_max_parallel_ast);
592 }
593
594 static ssize_t max_parallel_ast_store(struct kobject *kobj,
595                                       struct attribute *attr,
596                                       const char *buffer, size_t count)
597 {
598         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
599                                                  ns_kobj);
600         unsigned long tmp;
601         int err;
602
603         err = kstrtoul(buffer, 10, &tmp);
604         if (err != 0)
605                 return -EINVAL;
606
607         ns->ns_max_parallel_ast = tmp;
608
609         return count;
610 }
611 LUSTRE_RW_ATTR(max_parallel_ast);
612
613 #endif /* HAVE_SERVER_SUPPORT */
614
615 /* These are for namespaces in /sys/fs/lustre/ldlm/namespaces/ */
616 static struct attribute *ldlm_ns_attrs[] = {
617         &lustre_attr_resource_count.attr,
618         &lustre_attr_lock_count.attr,
619         &lustre_attr_lock_unused_count.attr,
620         &lustre_attr_lru_size.attr,
621         &lustre_attr_lru_max_age.attr,
622         &lustre_attr_early_lock_cancel.attr,
623 #ifdef HAVE_SERVER_SUPPORT
624         &lustre_attr_ctime_age_limit.attr,
625         &lustre_attr_lock_timeouts.attr,
626         &lustre_attr_max_nolock_bytes.attr,
627         &lustre_attr_contention_seconds.attr,
628         &lustre_attr_contended_locks.attr,
629         &lustre_attr_max_parallel_ast.attr,
630 #endif
631         NULL,
632 };
633
634 static void ldlm_ns_release(struct kobject *kobj)
635 {
636         struct ldlm_namespace *ns = container_of(kobj, struct ldlm_namespace,
637                                                  ns_kobj);
638         complete(&ns->ns_kobj_unregister);
639 }
640
641 static struct kobj_type ldlm_ns_ktype = {
642         .default_attrs  = ldlm_ns_attrs,
643         .sysfs_ops      = &lustre_sysfs_ops,
644         .release        = ldlm_ns_release,
645 };
646
647 static void ldlm_namespace_proc_unregister(struct ldlm_namespace *ns)
648 {
649         if (ns->ns_proc_dir_entry == NULL)
650                 CERROR("dlm namespace %s has no procfs dir?\n",
651                        ldlm_ns_name(ns));
652         else
653                 lprocfs_remove(&ns->ns_proc_dir_entry);
654
655         if (ns->ns_stats != NULL)
656                 lprocfs_free_stats(&ns->ns_stats);
657 }
658
659 void ldlm_namespace_sysfs_unregister(struct ldlm_namespace *ns)
660 {
661         kobject_put(&ns->ns_kobj);
662         wait_for_completion(&ns->ns_kobj_unregister);
663 }
664
665 int ldlm_namespace_sysfs_register(struct ldlm_namespace *ns)
666 {
667         int err;
668
669         ns->ns_kobj.kset = ldlm_ns_kset;
670         init_completion(&ns->ns_kobj_unregister);
671         err = kobject_init_and_add(&ns->ns_kobj, &ldlm_ns_ktype, NULL,
672                                    "%s", ldlm_ns_name(ns));
673
674         ns->ns_stats = lprocfs_alloc_stats(LDLM_NSS_LAST, 0);
675         if (!ns->ns_stats) {
676                 kobject_put(&ns->ns_kobj);
677                 return -ENOMEM;
678         }
679
680         lprocfs_counter_init(ns->ns_stats, LDLM_NSS_LOCKS,
681                              LPROCFS_CNTR_AVGMINMAX, "locks", "locks");
682
683         return err;
684 }
685
686 static int ldlm_namespace_proc_register(struct ldlm_namespace *ns)
687 {
688         struct proc_dir_entry *ns_pde;
689
690         LASSERT(ns != NULL);
691         LASSERT(ns->ns_rs_hash != NULL);
692
693         if (ns->ns_proc_dir_entry != NULL) {
694                 ns_pde = ns->ns_proc_dir_entry;
695         } else {
696                 ns_pde = proc_mkdir(ldlm_ns_name(ns), ldlm_ns_proc_dir);
697                 if (ns_pde == NULL)
698                         return -ENOMEM;
699                 ns->ns_proc_dir_entry = ns_pde;
700         }
701
702         return 0;
703 }
704 #undef MAX_STRING_SIZE
705 #else /* CONFIG_PROC_FS */
706
707 #define ldlm_namespace_proc_unregister(ns)      ({;})
708 #define ldlm_namespace_proc_register(ns)        ({0;})
709
710 #endif /* CONFIG_PROC_FS */
711
712 static unsigned ldlm_res_hop_hash(struct cfs_hash *hs,
713                                   const void *key, unsigned mask)
714 {
715         const struct ldlm_res_id     *id  = key;
716         unsigned                val = 0;
717         unsigned                i;
718
719         for (i = 0; i < RES_NAME_SIZE; i++)
720                 val += id->name[i];
721         return val & mask;
722 }
723
724 static unsigned ldlm_res_hop_fid_hash(struct cfs_hash *hs,
725                                       const void *key, unsigned mask)
726 {
727         const struct ldlm_res_id *id = key;
728         struct lu_fid       fid;
729         __u32               hash;
730         __u32               val;
731
732         fid.f_seq = id->name[LUSTRE_RES_ID_SEQ_OFF];
733         fid.f_oid = (__u32)id->name[LUSTRE_RES_ID_VER_OID_OFF];
734         fid.f_ver = (__u32)(id->name[LUSTRE_RES_ID_VER_OID_OFF] >> 32);
735
736         hash = fid_flatten32(&fid);
737         hash += (hash >> 4) + (hash << 12); /* mixing oid and seq */
738         if (id->name[LUSTRE_RES_ID_HSH_OFF] != 0) {
739                 val = id->name[LUSTRE_RES_ID_HSH_OFF];
740                 hash += (val >> 5) + (val << 11);
741         } else {
742                 val = fid_oid(&fid);
743         }
744         hash = hash_long(hash, hs->hs_bkt_bits);
745         /* give me another random factor */
746         hash -= hash_long((unsigned long)hs, val % 11 + 3);
747
748         hash <<= hs->hs_cur_bits - hs->hs_bkt_bits;
749         hash |= ldlm_res_hop_hash(hs, key, CFS_HASH_NBKT(hs) - 1);
750
751         return hash & mask;
752 }
753
754 static void *ldlm_res_hop_key(struct hlist_node *hnode)
755 {
756         struct ldlm_resource   *res;
757
758         res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
759         return &res->lr_name;
760 }
761
762 static int ldlm_res_hop_keycmp(const void *key, struct hlist_node *hnode)
763 {
764         struct ldlm_resource   *res;
765
766         res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
767         return ldlm_res_eq((const struct ldlm_res_id *)key,
768                            (const struct ldlm_res_id *)&res->lr_name);
769 }
770
771 static void *ldlm_res_hop_object(struct hlist_node *hnode)
772 {
773         return hlist_entry(hnode, struct ldlm_resource, lr_hash);
774 }
775
776 static void
777 ldlm_res_hop_get_locked(struct cfs_hash *hs, struct hlist_node *hnode)
778 {
779         struct ldlm_resource *res;
780
781         res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
782         ldlm_resource_getref(res);
783 }
784
785 static void ldlm_res_hop_put(struct cfs_hash *hs, struct hlist_node *hnode)
786 {
787         struct ldlm_resource *res;
788
789         res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
790         ldlm_resource_putref(res);
791 }
792
793 static struct cfs_hash_ops ldlm_ns_hash_ops = {
794         .hs_hash        = ldlm_res_hop_hash,
795         .hs_key         = ldlm_res_hop_key,
796         .hs_keycmp      = ldlm_res_hop_keycmp,
797         .hs_keycpy      = NULL,
798         .hs_object      = ldlm_res_hop_object,
799         .hs_get         = ldlm_res_hop_get_locked,
800         .hs_put         = ldlm_res_hop_put
801 };
802
803 static struct cfs_hash_ops ldlm_ns_fid_hash_ops = {
804         .hs_hash        = ldlm_res_hop_fid_hash,
805         .hs_key         = ldlm_res_hop_key,
806         .hs_keycmp      = ldlm_res_hop_keycmp,
807         .hs_keycpy      = NULL,
808         .hs_object      = ldlm_res_hop_object,
809         .hs_get         = ldlm_res_hop_get_locked,
810         .hs_put         = ldlm_res_hop_put
811 };
812
813 typedef struct ldlm_ns_hash_def {
814         enum ldlm_ns_type       nsd_type;
815         /** hash bucket bits */
816         unsigned                nsd_bkt_bits;
817         /** hash bits */
818         unsigned                nsd_all_bits;
819         /** hash operations */
820         struct cfs_hash_ops *nsd_hops;
821 } ldlm_ns_hash_def_t;
822
823 static struct ldlm_ns_hash_def ldlm_ns_hash_defs[] =
824 {
825         {
826                 .nsd_type       = LDLM_NS_TYPE_MDC,
827                 .nsd_bkt_bits   = 11,
828                 .nsd_all_bits   = 16,
829                 .nsd_hops       = &ldlm_ns_fid_hash_ops,
830         },
831         {
832                 .nsd_type       = LDLM_NS_TYPE_MDT,
833                 .nsd_bkt_bits   = 14,
834                 .nsd_all_bits   = 21,
835                 .nsd_hops       = &ldlm_ns_fid_hash_ops,
836         },
837         {
838                 .nsd_type       = LDLM_NS_TYPE_OSC,
839                 .nsd_bkt_bits   = 8,
840                 .nsd_all_bits   = 12,
841                 .nsd_hops       = &ldlm_ns_hash_ops,
842         },
843         {
844                 .nsd_type       = LDLM_NS_TYPE_OST,
845                 .nsd_bkt_bits   = 11,
846                 .nsd_all_bits   = 17,
847                 .nsd_hops       = &ldlm_ns_hash_ops,
848         },
849         {
850                 .nsd_type       = LDLM_NS_TYPE_MGC,
851                 .nsd_bkt_bits   = 4,
852                 .nsd_all_bits   = 4,
853                 .nsd_hops       = &ldlm_ns_hash_ops,
854         },
855         {
856                 .nsd_type       = LDLM_NS_TYPE_MGT,
857                 .nsd_bkt_bits   = 4,
858                 .nsd_all_bits   = 4,
859                 .nsd_hops       = &ldlm_ns_hash_ops,
860         },
861         {
862                 .nsd_type       = LDLM_NS_TYPE_UNKNOWN,
863         },
864 };
865
866 /**
867  * Create and initialize new empty namespace.
868  */
869 struct ldlm_namespace *ldlm_namespace_new(struct obd_device *obd, char *name,
870                                           enum ldlm_side client,
871                                           enum ldlm_appetite apt,
872                                           enum ldlm_ns_type ns_type)
873 {
874         struct ldlm_namespace *ns = NULL;
875         struct ldlm_ns_bucket *nsb;
876         struct ldlm_ns_hash_def *nsd;
877         struct cfs_hash_bd bd;
878         int idx;
879         int rc;
880         ENTRY;
881
882         LASSERT(obd != NULL);
883
884         rc = ldlm_get_ref();
885         if (rc) {
886                 CERROR("ldlm_get_ref failed: %d\n", rc);
887                 RETURN(NULL);
888         }
889
890         for (idx = 0;;idx++) {
891                 nsd = &ldlm_ns_hash_defs[idx];
892                 if (nsd->nsd_type == LDLM_NS_TYPE_UNKNOWN) {
893                         CERROR("Unknown type %d for ns %s\n", ns_type, name);
894                         GOTO(out_ref, NULL);
895                 }
896
897                 if (nsd->nsd_type == ns_type)
898                         break;
899         }
900
901         OBD_ALLOC_PTR(ns);
902         if (!ns)
903                 GOTO(out_ref, NULL);
904
905         ns->ns_rs_hash = cfs_hash_create(name,
906                                          nsd->nsd_all_bits, nsd->nsd_all_bits,
907                                          nsd->nsd_bkt_bits, sizeof(*nsb),
908                                          CFS_HASH_MIN_THETA,
909                                          CFS_HASH_MAX_THETA,
910                                          nsd->nsd_hops,
911                                          CFS_HASH_DEPTH |
912                                          CFS_HASH_BIGNAME |
913                                          CFS_HASH_SPIN_BKTLOCK |
914                                          CFS_HASH_NO_ITEMREF);
915         if (ns->ns_rs_hash == NULL)
916                 GOTO(out_ns, NULL);
917
918         cfs_hash_for_each_bucket(ns->ns_rs_hash, &bd, idx) {
919                 nsb = cfs_hash_bd_extra_get(ns->ns_rs_hash, &bd);
920                 at_init(&nsb->nsb_at_estimate, ldlm_enqueue_min, 0);
921                 nsb->nsb_namespace = ns;
922                 nsb->nsb_reclaim_start = 0;
923         }
924
925         ns->ns_obd      = obd;
926         ns->ns_appetite = apt;
927         ns->ns_client   = client;
928
929         INIT_LIST_HEAD(&ns->ns_list_chain);
930         INIT_LIST_HEAD(&ns->ns_unused_list);
931         spin_lock_init(&ns->ns_lock);
932         atomic_set(&ns->ns_bref, 0);
933         init_waitqueue_head(&ns->ns_waitq);
934
935         ns->ns_max_nolock_size    = NS_DEFAULT_MAX_NOLOCK_BYTES;
936         ns->ns_contention_time    = NS_DEFAULT_CONTENTION_SECONDS;
937         ns->ns_contended_locks    = NS_DEFAULT_CONTENDED_LOCKS;
938
939         ns->ns_max_parallel_ast   = LDLM_DEFAULT_PARALLEL_AST_LIMIT;
940         ns->ns_nr_unused          = 0;
941         ns->ns_max_unused         = LDLM_DEFAULT_LRU_SIZE;
942         ns->ns_max_age            = LDLM_DEFAULT_MAX_ALIVE;
943         ns->ns_ctime_age_limit    = LDLM_CTIME_AGE_LIMIT;
944         ns->ns_timeouts           = 0;
945         ns->ns_orig_connect_flags = 0;
946         ns->ns_connect_flags      = 0;
947         ns->ns_stopping           = 0;
948         ns->ns_reclaim_start      = 0;
949
950         rc = ldlm_namespace_sysfs_register(ns);
951         if (rc) {
952                 CERROR("Can't initialize ns sysfs, rc %d\n", rc);
953                 GOTO(out_hash, rc);
954         }
955
956         rc = ldlm_namespace_proc_register(ns);
957         if (rc) {
958                 CERROR("Can't initialize ns proc, rc %d\n", rc);
959                 GOTO(out_sysfs, rc);
960         }
961
962         idx = ldlm_namespace_nr_read(client);
963         rc = ldlm_pool_init(&ns->ns_pool, ns, idx, client);
964         if (rc) {
965                 CERROR("Can't initialize lock pool, rc %d\n", rc);
966                 GOTO(out_proc, rc);
967         }
968
969         ldlm_namespace_register(ns, client);
970         RETURN(ns);
971 out_proc:
972         ldlm_namespace_proc_unregister(ns);
973 out_sysfs:
974         ldlm_namespace_sysfs_unregister(ns);
975         ldlm_namespace_cleanup(ns, 0);
976 out_hash:
977         cfs_hash_putref(ns->ns_rs_hash);
978 out_ns:
979         OBD_FREE_PTR(ns);
980 out_ref:
981         ldlm_put_ref();
982         RETURN(NULL);
983 }
984 EXPORT_SYMBOL(ldlm_namespace_new);
985
986 extern struct ldlm_lock *ldlm_lock_get(struct ldlm_lock *lock);
987
988 /**
989  * Cancel and destroy all locks on a resource.
990  *
991  * If flags contains FL_LOCAL_ONLY, don't try to tell the server, just
992  * clean up.  This is currently only used for recovery, and we make
993  * certain assumptions as a result--notably, that we shouldn't cancel
994  * locks with refs.
995  */
996 static void cleanup_resource(struct ldlm_resource *res, struct list_head *q,
997                              __u64 flags)
998 {
999         struct list_head *tmp;
1000         int rc = 0, client = ns_is_client(ldlm_res_to_ns(res));
1001         bool local_only = !!(flags & LDLM_FL_LOCAL_ONLY);
1002
1003         do {
1004                 struct ldlm_lock *lock = NULL;
1005
1006                 /* First, we look for non-cleaned-yet lock
1007                  * all cleaned locks are marked by CLEANED flag. */
1008                 lock_res(res);
1009                 list_for_each(tmp, q) {
1010                         lock = list_entry(tmp, struct ldlm_lock,
1011                                           l_res_link);
1012                         if (ldlm_is_cleaned(lock)) {
1013                                 lock = NULL;
1014                                 continue;
1015                         }
1016                         LDLM_LOCK_GET(lock);
1017                         ldlm_set_cleaned(lock);
1018                         break;
1019                 }
1020
1021                 if (lock == NULL) {
1022                         unlock_res(res);
1023                         break;
1024                 }
1025
1026                 /* Set CBPENDING so nothing in the cancellation path
1027                  * can match this lock. */
1028                 ldlm_set_cbpending(lock);
1029                 ldlm_set_failed(lock);
1030                 lock->l_flags |= flags;
1031
1032                 /* ... without sending a CANCEL message for local_only. */
1033                 if (local_only)
1034                         ldlm_set_local_only(lock);
1035
1036                 if (local_only && (lock->l_readers || lock->l_writers)) {
1037                         /* This is a little bit gross, but much better than the
1038                          * alternative: pretend that we got a blocking AST from
1039                          * the server, so that when the lock is decref'd, it
1040                          * will go away ... */
1041                         unlock_res(res);
1042                         LDLM_DEBUG(lock, "setting FL_LOCAL_ONLY");
1043                         if (lock->l_flags & LDLM_FL_FAIL_LOC) {
1044                                 set_current_state(TASK_UNINTERRUPTIBLE);
1045                                 schedule_timeout(cfs_time_seconds(4));
1046                                 set_current_state(TASK_RUNNING);
1047                         }
1048                         if (lock->l_completion_ast)
1049                                 lock->l_completion_ast(lock,
1050                                                        LDLM_FL_FAILED, NULL);
1051                         LDLM_LOCK_RELEASE(lock);
1052                         continue;
1053                 }
1054
1055                 if (client) {
1056                         struct lustre_handle lockh;
1057
1058                         unlock_res(res);
1059                         ldlm_lock2handle(lock, &lockh);
1060                         rc = ldlm_cli_cancel(&lockh, LCF_LOCAL);
1061                         if (rc)
1062                                 CERROR("ldlm_cli_cancel: %d\n", rc);
1063                 } else {
1064                         unlock_res(res);
1065                         LDLM_DEBUG(lock, "Freeing a lock still held by a "
1066                                    "client node");
1067                         ldlm_lock_cancel(lock);
1068                 }
1069                 LDLM_LOCK_RELEASE(lock);
1070         } while (1);
1071 }
1072
1073 static int ldlm_resource_clean(struct cfs_hash *hs, struct cfs_hash_bd *bd,
1074                                struct hlist_node *hnode, void *arg)
1075 {
1076         struct ldlm_resource *res = cfs_hash_object(hs, hnode);
1077         __u64 flags = *(__u64 *)arg;
1078
1079         cleanup_resource(res, &res->lr_granted, flags);
1080         cleanup_resource(res, &res->lr_converting, flags);
1081         cleanup_resource(res, &res->lr_waiting, flags);
1082
1083         return 0;
1084 }
1085
1086 static int ldlm_resource_complain(struct cfs_hash *hs, struct cfs_hash_bd *bd,
1087                                   struct hlist_node *hnode, void *arg)
1088 {
1089         struct ldlm_resource  *res = cfs_hash_object(hs, hnode);
1090
1091         lock_res(res);
1092         CERROR("%s: namespace resource "DLDLMRES" (%p) refcount nonzero "
1093                "(%d) after lock cleanup; forcing cleanup.\n",
1094                ldlm_ns_name(ldlm_res_to_ns(res)), PLDLMRES(res), res,
1095                atomic_read(&res->lr_refcount) - 1);
1096
1097         ldlm_resource_dump(D_ERROR, res);
1098         unlock_res(res);
1099         return 0;
1100 }
1101
1102 /**
1103  * Cancel and destroy all locks in the namespace.
1104  *
1105  * Typically used during evictions when server notified client that it was
1106  * evicted and all of its state needs to be destroyed.
1107  * Also used during shutdown.
1108  */
1109 int ldlm_namespace_cleanup(struct ldlm_namespace *ns, __u64 flags)
1110 {
1111         if (ns == NULL) {
1112                 CDEBUG(D_INFO, "NULL ns, skipping cleanup\n");
1113                 return ELDLM_OK;
1114         }
1115
1116         cfs_hash_for_each_nolock(ns->ns_rs_hash, ldlm_resource_clean,
1117                                  &flags, 0);
1118         cfs_hash_for_each_nolock(ns->ns_rs_hash, ldlm_resource_complain,
1119                                  NULL, 0);
1120         return ELDLM_OK;
1121 }
1122 EXPORT_SYMBOL(ldlm_namespace_cleanup);
1123
1124 /**
1125  * Attempts to free namespace.
1126  *
1127  * Only used when namespace goes away, like during an unmount.
1128  */
1129 static int __ldlm_namespace_free(struct ldlm_namespace *ns, int force)
1130 {
1131         ENTRY;
1132
1133         /* At shutdown time, don't call the cancellation callback */
1134         ldlm_namespace_cleanup(ns, force ? LDLM_FL_LOCAL_ONLY : 0);
1135
1136         if (atomic_read(&ns->ns_bref) > 0) {
1137                 struct l_wait_info lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL);
1138                 int rc;
1139                 CDEBUG(D_DLMTRACE,
1140                        "dlm namespace %s free waiting on refcount %d\n",
1141                        ldlm_ns_name(ns), atomic_read(&ns->ns_bref));
1142 force_wait:
1143                 if (force)
1144                         lwi = LWI_TIMEOUT(msecs_to_jiffies(obd_timeout *
1145                                           MSEC_PER_SEC) / 4, NULL, NULL);
1146
1147                 rc = l_wait_event(ns->ns_waitq,
1148                                   atomic_read(&ns->ns_bref) == 0, &lwi);
1149
1150                 /* Forced cleanups should be able to reclaim all references,
1151                  * so it's safe to wait forever... we can't leak locks... */
1152                 if (force && rc == -ETIMEDOUT) {
1153                         LCONSOLE_ERROR("Forced cleanup waiting for %s "
1154                                        "namespace with %d resources in use, "
1155                                        "(rc=%d)\n", ldlm_ns_name(ns),
1156                                        atomic_read(&ns->ns_bref), rc);
1157                         GOTO(force_wait, rc);
1158                 }
1159
1160                 if (atomic_read(&ns->ns_bref)) {
1161                         LCONSOLE_ERROR("Cleanup waiting for %s namespace "
1162                                        "with %d resources in use, (rc=%d)\n",
1163                                        ldlm_ns_name(ns),
1164                                        atomic_read(&ns->ns_bref), rc);
1165                         RETURN(ELDLM_NAMESPACE_EXISTS);
1166                 }
1167                 CDEBUG(D_DLMTRACE, "dlm namespace %s free done waiting\n",
1168                        ldlm_ns_name(ns));
1169         }
1170
1171         RETURN(ELDLM_OK);
1172 }
1173
1174 /**
1175  * Performs various cleanups for passed \a ns to make it drop refc and be
1176  * ready for freeing. Waits for refc == 0.
1177  *
1178  * The following is done:
1179  * (0) Unregister \a ns from its list to make inaccessible for potential
1180  * users like pools thread and others;
1181  * (1) Clear all locks in \a ns.
1182  */
1183 void ldlm_namespace_free_prior(struct ldlm_namespace *ns,
1184                                struct obd_import *imp,
1185                                int force)
1186 {
1187         int rc;
1188         ENTRY;
1189         if (!ns) {
1190                 EXIT;
1191                 return;
1192         }
1193
1194         spin_lock(&ns->ns_lock);
1195         ns->ns_stopping = 1;
1196         spin_unlock(&ns->ns_lock);
1197
1198         /*
1199          * Can fail with -EINTR when force == 0 in which case try harder.
1200          */
1201         rc = __ldlm_namespace_free(ns, force);
1202         if (rc != ELDLM_OK) {
1203                 if (imp) {
1204                         ptlrpc_disconnect_import(imp, 0);
1205                         ptlrpc_invalidate_import(imp);
1206                 }
1207
1208                 /*
1209                  * With all requests dropped and the import inactive
1210                  * we are gaurenteed all reference will be dropped.
1211                  */
1212                 rc = __ldlm_namespace_free(ns, 1);
1213                 LASSERT(rc == 0);
1214         }
1215         EXIT;
1216 }
1217 EXPORT_SYMBOL(ldlm_namespace_free_prior);
1218
1219 /**
1220  * Performs freeing memory structures related to \a ns. This is only done
1221  * when ldlm_namespce_free_prior() successfully removed all resources
1222  * referencing \a ns and its refc == 0.
1223  */
1224 void ldlm_namespace_free_post(struct ldlm_namespace *ns)
1225 {
1226         ENTRY;
1227         if (!ns) {
1228                 EXIT;
1229                 return;
1230         }
1231
1232         /* Make sure that nobody can find this ns in its list. */
1233         ldlm_namespace_unregister(ns, ns->ns_client);
1234         /* Fini pool _before_ parent proc dir is removed. This is important as
1235          * ldlm_pool_fini() removes own proc dir which is child to @dir.
1236          * Removing it after @dir may cause oops. */
1237         ldlm_pool_fini(&ns->ns_pool);
1238
1239         ldlm_namespace_proc_unregister(ns);
1240         ldlm_namespace_sysfs_unregister(ns);
1241         cfs_hash_putref(ns->ns_rs_hash);
1242         /* Namespace \a ns should be not on list at this time, otherwise
1243          * this will cause issues related to using freed \a ns in poold
1244          * thread. */
1245         LASSERT(list_empty(&ns->ns_list_chain));
1246         OBD_FREE_PTR(ns);
1247         ldlm_put_ref();
1248         EXIT;
1249 }
1250 EXPORT_SYMBOL(ldlm_namespace_free_post);
1251
1252 /**
1253  * Cleanup the resource, and free namespace.
1254  * bug 12864:
1255  * Deadlock issue:
1256  * proc1: destroy import
1257  *        class_disconnect_export(grab cl_sem) ->
1258  *              -> ldlm_namespace_free ->
1259  *              -> lprocfs_remove(grab _lprocfs_lock).
1260  * proc2: read proc info
1261  *        lprocfs_fops_read(grab _lprocfs_lock) ->
1262  *              -> osc_rd_active, etc(grab cl_sem).
1263  *
1264  * So that I have to split the ldlm_namespace_free into two parts - the first
1265  * part ldlm_namespace_free_prior is used to cleanup the resource which is
1266  * being used; the 2nd part ldlm_namespace_free_post is used to unregister the
1267  * lprocfs entries, and then free memory. It will be called w/o cli->cl_sem
1268  * held.
1269  */
1270 void ldlm_namespace_free(struct ldlm_namespace *ns,
1271                          struct obd_import *imp,
1272                          int force)
1273 {
1274         ldlm_namespace_free_prior(ns, imp, force);
1275         ldlm_namespace_free_post(ns);
1276 }
1277 EXPORT_SYMBOL(ldlm_namespace_free);
1278
1279 void ldlm_namespace_get(struct ldlm_namespace *ns)
1280 {
1281         atomic_inc(&ns->ns_bref);
1282 }
1283
1284 /* This is only for callers that care about refcount */
1285 static int ldlm_namespace_get_return(struct ldlm_namespace *ns)
1286 {
1287         return atomic_inc_return(&ns->ns_bref);
1288 }
1289
1290 void ldlm_namespace_put(struct ldlm_namespace *ns)
1291 {
1292         if (atomic_dec_and_lock(&ns->ns_bref, &ns->ns_lock)) {
1293                 wake_up(&ns->ns_waitq);
1294                 spin_unlock(&ns->ns_lock);
1295         }
1296 }
1297
1298 /** Register \a ns in the list of namespaces */
1299 void ldlm_namespace_register(struct ldlm_namespace *ns, enum ldlm_side client)
1300 {
1301         mutex_lock(ldlm_namespace_lock(client));
1302         LASSERT(list_empty(&ns->ns_list_chain));
1303         list_add(&ns->ns_list_chain, ldlm_namespace_inactive_list(client));
1304         ldlm_namespace_nr_inc(client);
1305         mutex_unlock(ldlm_namespace_lock(client));
1306 }
1307
1308 /** Unregister \a ns from the list of namespaces. */
1309 void ldlm_namespace_unregister(struct ldlm_namespace *ns, enum ldlm_side client)
1310 {
1311         mutex_lock(ldlm_namespace_lock(client));
1312         LASSERT(!list_empty(&ns->ns_list_chain));
1313         /* Some asserts and possibly other parts of the code are still
1314          * using list_empty(&ns->ns_list_chain). This is why it is
1315          * important to use list_del_init() here. */
1316         list_del_init(&ns->ns_list_chain);
1317         ldlm_namespace_nr_dec(client);
1318         mutex_unlock(ldlm_namespace_lock(client));
1319 }
1320
1321 /** Should be called with ldlm_namespace_lock(client) taken. */
1322 void ldlm_namespace_move_to_active_locked(struct ldlm_namespace *ns,
1323                                           enum ldlm_side client)
1324 {
1325         LASSERT(!list_empty(&ns->ns_list_chain));
1326         LASSERT(mutex_is_locked(ldlm_namespace_lock(client)));
1327         list_move_tail(&ns->ns_list_chain, ldlm_namespace_list(client));
1328 }
1329
1330 /** Should be called with ldlm_namespace_lock(client) taken. */
1331 void ldlm_namespace_move_to_inactive_locked(struct ldlm_namespace *ns,
1332                                             enum ldlm_side client)
1333 {
1334         LASSERT(!list_empty(&ns->ns_list_chain));
1335         LASSERT(mutex_is_locked(ldlm_namespace_lock(client)));
1336         list_move_tail(&ns->ns_list_chain,
1337                        ldlm_namespace_inactive_list(client));
1338 }
1339
1340 /** Should be called with ldlm_namespace_lock(client) taken. */
1341 struct ldlm_namespace *ldlm_namespace_first_locked(enum ldlm_side client)
1342 {
1343         LASSERT(mutex_is_locked(ldlm_namespace_lock(client)));
1344         LASSERT(!list_empty(ldlm_namespace_list(client)));
1345         return container_of(ldlm_namespace_list(client)->next,
1346                             struct ldlm_namespace, ns_list_chain);
1347 }
1348
1349 /** Create and initialize new resource. */
1350 static struct ldlm_resource *ldlm_resource_new(enum ldlm_type ldlm_type)
1351 {
1352         struct ldlm_resource *res;
1353         int idx;
1354
1355         OBD_SLAB_ALLOC_PTR_GFP(res, ldlm_resource_slab, GFP_NOFS);
1356         if (res == NULL)
1357                 return NULL;
1358
1359         if (ldlm_type == LDLM_EXTENT) {
1360                 OBD_SLAB_ALLOC(res->lr_itree, ldlm_interval_tree_slab,
1361                                sizeof(*res->lr_itree) * LCK_MODE_NUM);
1362                 if (res->lr_itree == NULL) {
1363                         OBD_SLAB_FREE_PTR(res, ldlm_resource_slab);
1364                         return NULL;
1365                 }
1366                 /* Initialize interval trees for each lock mode. */
1367                 for (idx = 0; idx < LCK_MODE_NUM; idx++) {
1368                         res->lr_itree[idx].lit_size = 0;
1369                         res->lr_itree[idx].lit_mode = 1 << idx;
1370                         res->lr_itree[idx].lit_root = NULL;
1371                 }
1372         }
1373
1374         INIT_LIST_HEAD(&res->lr_granted);
1375         INIT_LIST_HEAD(&res->lr_converting);
1376         INIT_LIST_HEAD(&res->lr_waiting);
1377
1378         atomic_set(&res->lr_refcount, 1);
1379         spin_lock_init(&res->lr_lock);
1380         lu_ref_init(&res->lr_reference);
1381
1382         /* Since LVB init can be delayed now, there is no longer need to
1383          * immediatelly acquire mutex here. */
1384         mutex_init(&res->lr_lvb_mutex);
1385         res->lr_lvb_initialized = false;
1386
1387         return res;
1388 }
1389
1390 /**
1391  * Return a reference to resource with given name, creating it if necessary.
1392  * Args: namespace with ns_lock unlocked
1393  * Locks: takes and releases NS hash-lock and res->lr_lock
1394  * Returns: referenced, unlocked ldlm_resource or NULL
1395  */
1396 struct ldlm_resource *
1397 ldlm_resource_get(struct ldlm_namespace *ns, struct ldlm_resource *parent,
1398                   const struct ldlm_res_id *name, enum ldlm_type type,
1399                   int create)
1400 {
1401         struct hlist_node       *hnode;
1402         struct ldlm_resource    *res = NULL;
1403         struct cfs_hash_bd              bd;
1404         __u64                   version;
1405         int                     ns_refcount = 0;
1406
1407         LASSERT(ns != NULL);
1408         LASSERT(parent == NULL);
1409         LASSERT(ns->ns_rs_hash != NULL);
1410         LASSERT(name->name[0] != 0);
1411
1412         cfs_hash_bd_get_and_lock(ns->ns_rs_hash, (void *)name, &bd, 0);
1413         hnode = cfs_hash_bd_lookup_locked(ns->ns_rs_hash, &bd, (void *)name);
1414         if (hnode != NULL) {
1415                 cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 0);
1416                 GOTO(found, res);
1417         }
1418
1419         version = cfs_hash_bd_version_get(&bd);
1420         cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 0);
1421
1422         if (create == 0)
1423                 return ERR_PTR(-ENOENT);
1424
1425         LASSERTF(type >= LDLM_MIN_TYPE && type < LDLM_MAX_TYPE,
1426                  "type: %d\n", type);
1427         res = ldlm_resource_new(type);
1428         if (res == NULL)
1429                 return ERR_PTR(-ENOMEM);
1430
1431         res->lr_ns_bucket = cfs_hash_bd_extra_get(ns->ns_rs_hash, &bd);
1432         res->lr_name = *name;
1433         res->lr_type = type;
1434
1435         cfs_hash_bd_lock(ns->ns_rs_hash, &bd, 1);
1436         hnode = (version == cfs_hash_bd_version_get(&bd)) ? NULL :
1437                 cfs_hash_bd_lookup_locked(ns->ns_rs_hash, &bd, (void *)name);
1438
1439         if (hnode != NULL) {
1440                 /* Someone won the race and already added the resource. */
1441                 cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
1442                 /* Clean lu_ref for failed resource. */
1443                 lu_ref_fini(&res->lr_reference);
1444                 if (res->lr_itree != NULL)
1445                         OBD_SLAB_FREE(res->lr_itree, ldlm_interval_tree_slab,
1446                                       sizeof(*res->lr_itree) * LCK_MODE_NUM);
1447                 OBD_SLAB_FREE(res, ldlm_resource_slab, sizeof *res);
1448 found:
1449                 res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
1450                 return res;
1451         }
1452         /* We won! Let's add the resource. */
1453         cfs_hash_bd_add_locked(ns->ns_rs_hash, &bd, &res->lr_hash);
1454         if (cfs_hash_bd_count_get(&bd) == 1)
1455                 ns_refcount = ldlm_namespace_get_return(ns);
1456
1457         cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
1458
1459         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_CREATE_RESOURCE, 2);
1460
1461         /* Let's see if we happened to be the very first resource in this
1462          * namespace. If so, and this is a client namespace, we need to move
1463          * the namespace into the active namespaces list to be patrolled by
1464          * the ldlm_poold. */
1465         if (ns_is_client(ns) && ns_refcount == 1) {
1466                 mutex_lock(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
1467                 ldlm_namespace_move_to_active_locked(ns, LDLM_NAMESPACE_CLIENT);
1468                 mutex_unlock(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
1469         }
1470
1471         return res;
1472 }
1473 EXPORT_SYMBOL(ldlm_resource_get);
1474
1475 struct ldlm_resource *ldlm_resource_getref(struct ldlm_resource *res)
1476 {
1477         LASSERT(res != NULL);
1478         LASSERT(res != LP_POISON);
1479         atomic_inc(&res->lr_refcount);
1480         CDEBUG(D_INFO, "getref res: %p count: %d\n", res,
1481                atomic_read(&res->lr_refcount));
1482         return res;
1483 }
1484
1485 static void __ldlm_resource_putref_final(struct cfs_hash_bd *bd,
1486                                          struct ldlm_resource *res)
1487 {
1488         struct ldlm_ns_bucket *nsb = res->lr_ns_bucket;
1489
1490         if (!list_empty(&res->lr_granted)) {
1491                 ldlm_resource_dump(D_ERROR, res);
1492                 LBUG();
1493         }
1494
1495         if (!list_empty(&res->lr_converting)) {
1496                 ldlm_resource_dump(D_ERROR, res);
1497                 LBUG();
1498         }
1499
1500         if (!list_empty(&res->lr_waiting)) {
1501                 ldlm_resource_dump(D_ERROR, res);
1502                 LBUG();
1503         }
1504
1505         cfs_hash_bd_del_locked(nsb->nsb_namespace->ns_rs_hash,
1506                                bd, &res->lr_hash);
1507         lu_ref_fini(&res->lr_reference);
1508         if (cfs_hash_bd_count_get(bd) == 0)
1509                 ldlm_namespace_put(nsb->nsb_namespace);
1510 }
1511
1512 /* Returns 1 if the resource was freed, 0 if it remains. */
1513 int ldlm_resource_putref(struct ldlm_resource *res)
1514 {
1515         struct ldlm_namespace *ns = ldlm_res_to_ns(res);
1516         struct cfs_hash_bd   bd;
1517
1518         LASSERT_ATOMIC_GT_LT(&res->lr_refcount, 0, LI_POISON);
1519         CDEBUG(D_INFO, "putref res: %p count: %d\n",
1520                res, atomic_read(&res->lr_refcount) - 1);
1521
1522         cfs_hash_bd_get(ns->ns_rs_hash, &res->lr_name, &bd);
1523         if (cfs_hash_bd_dec_and_lock(ns->ns_rs_hash, &bd, &res->lr_refcount)) {
1524                 __ldlm_resource_putref_final(&bd, res);
1525                 cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
1526                 if (ns->ns_lvbo && ns->ns_lvbo->lvbo_free)
1527                         ns->ns_lvbo->lvbo_free(res);
1528                 if (res->lr_itree != NULL)
1529                         OBD_SLAB_FREE(res->lr_itree, ldlm_interval_tree_slab,
1530                                       sizeof(*res->lr_itree) * LCK_MODE_NUM);
1531                 OBD_SLAB_FREE(res, ldlm_resource_slab, sizeof *res);
1532                 return 1;
1533         }
1534         return 0;
1535 }
1536 EXPORT_SYMBOL(ldlm_resource_putref);
1537
1538 /**
1539  * Add a lock into a given resource into specified lock list.
1540  */
1541 void ldlm_resource_add_lock(struct ldlm_resource *res, struct list_head *head,
1542                             struct ldlm_lock *lock)
1543 {
1544         check_res_locked(res);
1545
1546         LDLM_DEBUG(lock, "About to add this lock");
1547
1548         if (ldlm_is_destroyed(lock)) {
1549                 CDEBUG(D_OTHER, "Lock destroyed, not adding to resource\n");
1550                 return;
1551         }
1552
1553         LASSERT(list_empty(&lock->l_res_link));
1554
1555         list_add_tail(&lock->l_res_link, head);
1556 }
1557
1558 /**
1559  * Insert a lock into resource after specified lock.
1560  *
1561  * Obtain resource description from the lock we are inserting after.
1562  */
1563 void ldlm_resource_insert_lock_after(struct ldlm_lock *original,
1564                                      struct ldlm_lock *new)
1565 {
1566         struct ldlm_resource *res = original->l_resource;
1567
1568         check_res_locked(res);
1569
1570         ldlm_resource_dump(D_INFO, res);
1571         LDLM_DEBUG(new, "About to insert this lock after %p: ", original);
1572
1573         if (ldlm_is_destroyed(new)) {
1574                 CDEBUG(D_OTHER, "Lock destroyed, not adding to resource\n");
1575                 goto out;
1576         }
1577
1578         LASSERT(list_empty(&new->l_res_link));
1579
1580         list_add(&new->l_res_link, &original->l_res_link);
1581  out:;
1582 }
1583
1584 void ldlm_resource_unlink_lock(struct ldlm_lock *lock)
1585 {
1586         int type = lock->l_resource->lr_type;
1587
1588         check_res_locked(lock->l_resource);
1589         if (type == LDLM_IBITS || type == LDLM_PLAIN)
1590                 ldlm_unlink_lock_skiplist(lock);
1591         else if (type == LDLM_EXTENT)
1592                 ldlm_extent_unlink_lock(lock);
1593         list_del_init(&lock->l_res_link);
1594 }
1595 EXPORT_SYMBOL(ldlm_resource_unlink_lock);
1596
1597 void ldlm_res2desc(struct ldlm_resource *res, struct ldlm_resource_desc *desc)
1598 {
1599         desc->lr_type = res->lr_type;
1600         desc->lr_name = res->lr_name;
1601 }
1602
1603 /**
1604  * Print information about all locks in all namespaces on this node to debug
1605  * log.
1606  */
1607 void ldlm_dump_all_namespaces(enum ldlm_side client, int level)
1608 {
1609         struct list_head *tmp;
1610
1611         if (!((libcfs_debug | D_ERROR) & level))
1612                 return;
1613
1614         mutex_lock(ldlm_namespace_lock(client));
1615
1616         list_for_each(tmp, ldlm_namespace_list(client)) {
1617                 struct ldlm_namespace *ns;
1618
1619                 ns = list_entry(tmp, struct ldlm_namespace, ns_list_chain);
1620                 ldlm_namespace_dump(level, ns);
1621         }
1622
1623         mutex_unlock(ldlm_namespace_lock(client));
1624 }
1625
1626 static int ldlm_res_hash_dump(struct cfs_hash *hs, struct cfs_hash_bd *bd,
1627                               struct hlist_node *hnode, void *arg)
1628 {
1629         struct ldlm_resource *res = cfs_hash_object(hs, hnode);
1630         int    level = (int)(unsigned long)arg;
1631
1632         lock_res(res);
1633         ldlm_resource_dump(level, res);
1634         unlock_res(res);
1635
1636         return 0;
1637 }
1638
1639 /**
1640  * Print information about all locks in this namespace on this node to debug
1641  * log.
1642  */
1643 void ldlm_namespace_dump(int level, struct ldlm_namespace *ns)
1644 {
1645         if (!((libcfs_debug | D_ERROR) & level))
1646                 return;
1647
1648         CDEBUG(level, "--- Namespace: %s (rc: %d, side: %s)\n",
1649                ldlm_ns_name(ns), atomic_read(&ns->ns_bref),
1650                ns_is_client(ns) ? "client" : "server");
1651
1652         if (cfs_time_before(cfs_time_current(), ns->ns_next_dump))
1653                 return;
1654
1655         cfs_hash_for_each_nolock(ns->ns_rs_hash,
1656                                  ldlm_res_hash_dump,
1657                                  (void *)(unsigned long)level, 0);
1658         spin_lock(&ns->ns_lock);
1659         ns->ns_next_dump = cfs_time_shift(10);
1660         spin_unlock(&ns->ns_lock);
1661 }
1662
1663 /**
1664  * Print information about all locks in this resource to debug log.
1665  */
1666 void ldlm_resource_dump(int level, struct ldlm_resource *res)
1667 {
1668         struct ldlm_lock *lock;
1669         unsigned int granted = 0;
1670
1671         CLASSERT(RES_NAME_SIZE == 4);
1672
1673         if (!((libcfs_debug | D_ERROR) & level))
1674                 return;
1675
1676         CDEBUG(level, "--- Resource: "DLDLMRES" (%p) refcount = %d\n",
1677                PLDLMRES(res), res, atomic_read(&res->lr_refcount));
1678
1679         if (!list_empty(&res->lr_granted)) {
1680                 CDEBUG(level, "Granted locks (in reverse order):\n");
1681                 list_for_each_entry_reverse(lock, &res->lr_granted,
1682                                                 l_res_link) {
1683                         LDLM_DEBUG_LIMIT(level, lock, "###");
1684                         if (!(level & D_CANTMASK) &&
1685                             ++granted > ldlm_dump_granted_max) {
1686                                 CDEBUG(level, "only dump %d granted locks to "
1687                                        "avoid DDOS.\n", granted);
1688                                 break;
1689                         }
1690                 }
1691         }
1692         if (!list_empty(&res->lr_converting)) {
1693                 CDEBUG(level, "Converting locks:\n");
1694                 list_for_each_entry(lock, &res->lr_converting, l_res_link)
1695                         LDLM_DEBUG_LIMIT(level, lock, "###");
1696         }
1697         if (!list_empty(&res->lr_waiting)) {
1698                 CDEBUG(level, "Waiting locks:\n");
1699                 list_for_each_entry(lock, &res->lr_waiting, l_res_link)
1700                         LDLM_DEBUG_LIMIT(level, lock, "###");
1701         }
1702 }
1703 EXPORT_SYMBOL(ldlm_resource_dump);