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