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