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