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