Whamcloud - gitweb
da54fcd136f6ddcf48162b1e9127e19ac61b2724
[fs/lustre-release.git] / lustre / ldlm / ldlm_lockd.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_lockd.c
37  *
38  * Author: Peter Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  */
41
42 #define DEBUG_SUBSYSTEM S_LDLM
43
44 #ifdef __KERNEL__
45 # include <libcfs/libcfs.h>
46 #else
47 # include <liblustre.h>
48 #endif
49
50 #include <lustre_dlm.h>
51 #include <obd_class.h>
52 #include <libcfs/list.h>
53 #include "ldlm_internal.h"
54
55 static int ldlm_num_threads;
56 CFS_MODULE_PARM(ldlm_num_threads, "i", int, 0444,
57                 "number of DLM service threads to start");
58
59 static char *ldlm_cpts;
60 CFS_MODULE_PARM(ldlm_cpts, "s", charp, 0444,
61                 "CPU partitions ldlm threads should run on");
62
63 extern cfs_mem_cache_t *ldlm_resource_slab;
64 extern cfs_mem_cache_t *ldlm_lock_slab;
65 static struct mutex     ldlm_ref_mutex;
66 static int ldlm_refcount;
67
68 struct ldlm_cb_async_args {
69         struct ldlm_cb_set_arg *ca_set_arg;
70         struct ldlm_lock       *ca_lock;
71 };
72
73 /* LDLM state */
74
75 static struct ldlm_state *ldlm_state;
76
77 inline cfs_time_t round_timeout(cfs_time_t timeout)
78 {
79         return cfs_time_seconds((int)cfs_duration_sec(cfs_time_sub(timeout, 0)) + 1);
80 }
81
82 /* timeout for initial callback (AST) reply (bz10399) */
83 static inline unsigned int ldlm_get_rq_timeout(void)
84 {
85         /* Non-AT value */
86         unsigned int timeout = min(ldlm_timeout, obd_timeout / 3);
87
88         return timeout < 1 ? 1 : timeout;
89 }
90
91 #define ELT_STOPPED   0
92 #define ELT_READY     1
93 #define ELT_TERMINATE 2
94
95 struct ldlm_bl_pool {
96         spinlock_t              blp_lock;
97
98         /*
99          * blp_prio_list is used for callbacks that should be handled
100          * as a priority. It is used for LDLM_FL_DISCARD_DATA requests.
101          * see bug 13843
102          */
103         cfs_list_t              blp_prio_list;
104
105         /*
106          * blp_list is used for all other callbacks which are likely
107          * to take longer to process.
108          */
109         cfs_list_t              blp_list;
110
111         cfs_waitq_t             blp_waitq;
112         struct completion        blp_comp;
113         cfs_atomic_t            blp_num_threads;
114         cfs_atomic_t            blp_busy_threads;
115         int                     blp_min_threads;
116         int                     blp_max_threads;
117 };
118
119 struct ldlm_bl_work_item {
120         cfs_list_t              blwi_entry;
121         struct ldlm_namespace  *blwi_ns;
122         struct ldlm_lock_desc   blwi_ld;
123         struct ldlm_lock       *blwi_lock;
124         cfs_list_t              blwi_head;
125         int                     blwi_count;
126         struct completion        blwi_comp;
127         ldlm_cancel_flags_t     blwi_flags;
128         int                     blwi_mem_pressure;
129 };
130
131 #if defined(HAVE_SERVER_SUPPORT) && defined(__KERNEL__)
132
133 /**
134  * Protects both waiting_locks_list and expired_lock_thread.
135  */
136 static spinlock_t waiting_locks_spinlock;   /* BH lock (timer) */
137
138 /**
139  * List for contended locks.
140  *
141  * As soon as a lock is contended, it gets placed on this list and
142  * expected time to get a response is filled in the lock. A special
143  * thread walks the list looking for locks that should be released and
144  * schedules client evictions for those that have not been released in
145  * time.
146  *
147  * All access to it should be under waiting_locks_spinlock.
148  */
149 static cfs_list_t waiting_locks_list;
150 static cfs_timer_t waiting_locks_timer;
151
152 static struct expired_lock_thread {
153         cfs_waitq_t             elt_waitq;
154         int                     elt_state;
155         int                     elt_dump;
156         cfs_list_t              elt_expired_locks;
157 } expired_lock_thread;
158
159 static inline int have_expired_locks(void)
160 {
161         int need_to_run;
162
163         ENTRY;
164         spin_lock_bh(&waiting_locks_spinlock);
165         need_to_run = !cfs_list_empty(&expired_lock_thread.elt_expired_locks);
166         spin_unlock_bh(&waiting_locks_spinlock);
167
168         RETURN(need_to_run);
169 }
170
171 /**
172  * Check expired lock list for expired locks and time them out.
173  */
174 static int expired_lock_main(void *arg)
175 {
176         cfs_list_t *expired = &expired_lock_thread.elt_expired_locks;
177         struct l_wait_info lwi = { 0 };
178         int do_dump;
179
180         ENTRY;
181         cfs_daemonize("ldlm_elt");
182
183         expired_lock_thread.elt_state = ELT_READY;
184         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
185
186         while (1) {
187                 l_wait_event(expired_lock_thread.elt_waitq,
188                              have_expired_locks() ||
189                              expired_lock_thread.elt_state == ELT_TERMINATE,
190                              &lwi);
191
192                 spin_lock_bh(&waiting_locks_spinlock);
193                 if (expired_lock_thread.elt_dump) {
194                         struct libcfs_debug_msg_data msgdata = {
195                                 .msg_file = __FILE__,
196                                 .msg_fn = "waiting_locks_callback",
197                                 .msg_line = expired_lock_thread.elt_dump };
198                         spin_unlock_bh(&waiting_locks_spinlock);
199
200                         /* from waiting_locks_callback, but not in timer */
201                         libcfs_debug_dumplog();
202                         libcfs_run_lbug_upcall(&msgdata);
203
204                         spin_lock_bh(&waiting_locks_spinlock);
205                         expired_lock_thread.elt_dump = 0;
206                 }
207
208                 do_dump = 0;
209
210                 while (!cfs_list_empty(expired)) {
211                         struct obd_export *export;
212                         struct ldlm_lock *lock;
213
214                         lock = cfs_list_entry(expired->next, struct ldlm_lock,
215                                           l_pending_chain);
216                         if ((void *)lock < LP_POISON + CFS_PAGE_SIZE &&
217                             (void *)lock >= LP_POISON) {
218                                 spin_unlock_bh(&waiting_locks_spinlock);
219                                 CERROR("free lock on elt list %p\n", lock);
220                                 LBUG();
221                         }
222                         cfs_list_del_init(&lock->l_pending_chain);
223                         if ((void *)lock->l_export < LP_POISON + CFS_PAGE_SIZE &&
224                             (void *)lock->l_export >= LP_POISON) {
225                                 CERROR("lock with free export on elt list %p\n",
226                                        lock->l_export);
227                                 lock->l_export = NULL;
228                                 LDLM_ERROR(lock, "free export");
229                                 /* release extra ref grabbed by
230                                  * ldlm_add_waiting_lock() or
231                                  * ldlm_failed_ast() */
232                                 LDLM_LOCK_RELEASE(lock);
233                                 continue;
234                         }
235
236                         if (lock->l_destroyed) {
237                                 /* release the lock refcount where
238                                  * waiting_locks_callback() founds */
239                                 LDLM_LOCK_RELEASE(lock);
240                                 continue;
241                         }
242                         export = class_export_lock_get(lock->l_export, lock);
243                         spin_unlock_bh(&waiting_locks_spinlock);
244
245                         do_dump++;
246                         class_fail_export(export);
247                         class_export_lock_put(export, lock);
248
249                         /* release extra ref grabbed by ldlm_add_waiting_lock()
250                          * or ldlm_failed_ast() */
251                         LDLM_LOCK_RELEASE(lock);
252
253                         spin_lock_bh(&waiting_locks_spinlock);
254                 }
255                 spin_unlock_bh(&waiting_locks_spinlock);
256
257                 if (do_dump && obd_dump_on_eviction) {
258                         CERROR("dump the log upon eviction\n");
259                         libcfs_debug_dumplog();
260                 }
261
262                 if (expired_lock_thread.elt_state == ELT_TERMINATE)
263                         break;
264         }
265
266         expired_lock_thread.elt_state = ELT_STOPPED;
267         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
268         RETURN(0);
269 }
270
271 static int ldlm_add_waiting_lock(struct ldlm_lock *lock);
272 static int __ldlm_add_waiting_lock(struct ldlm_lock *lock, int seconds);
273
274 /**
275  * Check if there is a request in the export request list
276  * which prevents the lock canceling.
277  */
278 static int ldlm_lock_busy(struct ldlm_lock *lock)
279 {
280         struct ptlrpc_request *req;
281         int match = 0;
282         ENTRY;
283
284         if (lock->l_export == NULL)
285                 return 0;
286
287         spin_lock_bh(&lock->l_export->exp_rpc_lock);
288         cfs_list_for_each_entry(req, &lock->l_export->exp_hp_rpcs,
289                                 rq_exp_list) {
290                 if (req->rq_ops->hpreq_lock_match) {
291                         match = req->rq_ops->hpreq_lock_match(req, lock);
292                         if (match)
293                                 break;
294                 }
295         }
296         spin_unlock_bh(&lock->l_export->exp_rpc_lock);
297         RETURN(match);
298 }
299
300 /* This is called from within a timer interrupt and cannot schedule */
301 static void waiting_locks_callback(unsigned long unused)
302 {
303         struct ldlm_lock        *lock;
304         int                     need_dump = 0;
305
306         spin_lock_bh(&waiting_locks_spinlock);
307         while (!cfs_list_empty(&waiting_locks_list)) {
308                 lock = cfs_list_entry(waiting_locks_list.next, struct ldlm_lock,
309                                       l_pending_chain);
310                 if (cfs_time_after(lock->l_callback_timeout,
311                                    cfs_time_current()) ||
312                     (lock->l_req_mode == LCK_GROUP))
313                         break;
314
315                 if (ptlrpc_check_suspend()) {
316                         /* there is a case when we talk to one mds, holding
317                          * lock from another mds. this way we easily can get
318                          * here, if second mds is being recovered. so, we
319                          * suspend timeouts. bug 6019 */
320
321                         LDLM_ERROR(lock, "recharge timeout: %s@%s nid %s ",
322                                    lock->l_export->exp_client_uuid.uuid,
323                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
324                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
325
326                         cfs_list_del_init(&lock->l_pending_chain);
327                         if (lock->l_destroyed) {
328                                 /* relay the lock refcount decrease to
329                                  * expired lock thread */
330                                 cfs_list_add(&lock->l_pending_chain,
331                                         &expired_lock_thread.elt_expired_locks);
332                         } else {
333                                 __ldlm_add_waiting_lock(lock,
334                                                 ldlm_get_enq_timeout(lock));
335                         }
336                         continue;
337                 }
338
339                 /* if timeout overlaps the activation time of suspended timeouts
340                  * then extend it to give a chance for client to reconnect */
341                 if (cfs_time_before(cfs_time_sub(lock->l_callback_timeout,
342                                                  cfs_time_seconds(obd_timeout)/2),
343                                     ptlrpc_suspend_wakeup_time())) {
344                         LDLM_ERROR(lock, "extend timeout due to recovery: %s@%s nid %s ",
345                                    lock->l_export->exp_client_uuid.uuid,
346                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
347                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
348
349                         cfs_list_del_init(&lock->l_pending_chain);
350                         if (lock->l_destroyed) {
351                                 /* relay the lock refcount decrease to
352                                  * expired lock thread */
353                                 cfs_list_add(&lock->l_pending_chain,
354                                         &expired_lock_thread.elt_expired_locks);
355                         } else {
356                                 __ldlm_add_waiting_lock(lock,
357                                                 ldlm_get_enq_timeout(lock));
358                         }
359                         continue;
360                 }
361
362                 /* Check if we need to prolong timeout */
363                 if (!OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT) &&
364                     ldlm_lock_busy(lock)) {
365                         int cont = 1;
366
367                         if (lock->l_pending_chain.next == &waiting_locks_list)
368                                 cont = 0;
369
370                         LDLM_LOCK_GET(lock);
371
372                         spin_unlock_bh(&waiting_locks_spinlock);
373                         LDLM_DEBUG(lock, "prolong the busy lock");
374                         ldlm_refresh_waiting_lock(lock,
375                                                   ldlm_get_enq_timeout(lock));
376                         spin_lock_bh(&waiting_locks_spinlock);
377
378                         if (!cont) {
379                                 LDLM_LOCK_RELEASE(lock);
380                                 break;
381                         }
382
383                         LDLM_LOCK_RELEASE(lock);
384                         continue;
385                 }
386                 ldlm_lock_to_ns(lock)->ns_timeouts++;
387                 LDLM_ERROR(lock, "lock callback timer expired after %lds: "
388                            "evicting client at %s ",
389                            cfs_time_current_sec()- lock->l_last_activity,
390                            libcfs_nid2str(
391                                    lock->l_export->exp_connection->c_peer.nid));
392
393                 /* no needs to take an extra ref on the lock since it was in
394                  * the waiting_locks_list and ldlm_add_waiting_lock()
395                  * already grabbed a ref */
396                 cfs_list_del(&lock->l_pending_chain);
397                 cfs_list_add(&lock->l_pending_chain,
398                              &expired_lock_thread.elt_expired_locks);
399                 need_dump = 1;
400         }
401
402         if (!cfs_list_empty(&expired_lock_thread.elt_expired_locks)) {
403                 if (obd_dump_on_timeout && need_dump)
404                         expired_lock_thread.elt_dump = __LINE__;
405
406                 cfs_waitq_signal(&expired_lock_thread.elt_waitq);
407         }
408
409         /*
410          * Make sure the timer will fire again if we have any locks
411          * left.
412          */
413         if (!cfs_list_empty(&waiting_locks_list)) {
414                 cfs_time_t timeout_rounded;
415                 lock = cfs_list_entry(waiting_locks_list.next, struct ldlm_lock,
416                                       l_pending_chain);
417                 timeout_rounded = (cfs_time_t)round_timeout(lock->l_callback_timeout);
418                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
419         }
420         spin_unlock_bh(&waiting_locks_spinlock);
421 }
422
423 /**
424  * Add lock to the list of contended locks.
425  *
426  * Indicate that we're waiting for a client to call us back cancelling a given
427  * lock.  We add it to the pending-callback chain, and schedule the lock-timeout
428  * timer to fire appropriately.  (We round up to the next second, to avoid
429  * floods of timer firings during periods of high lock contention and traffic).
430  * As done by ldlm_add_waiting_lock(), the caller must grab a lock reference
431  * if it has been added to the waiting list (1 is returned).
432  *
433  * Called with the namespace lock held.
434  */
435 static int __ldlm_add_waiting_lock(struct ldlm_lock *lock, int seconds)
436 {
437         cfs_time_t timeout;
438         cfs_time_t timeout_rounded;
439
440         if (!cfs_list_empty(&lock->l_pending_chain))
441                 return 0;
442
443         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT) ||
444             OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
445                 seconds = 1;
446
447         timeout = cfs_time_shift(seconds);
448         if (likely(cfs_time_after(timeout, lock->l_callback_timeout)))
449                 lock->l_callback_timeout = timeout;
450
451         timeout_rounded = round_timeout(lock->l_callback_timeout);
452
453         if (cfs_time_before(timeout_rounded,
454                             cfs_timer_deadline(&waiting_locks_timer)) ||
455             !cfs_timer_is_armed(&waiting_locks_timer)) {
456                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
457         }
458         /* if the new lock has a shorter timeout than something earlier on
459            the list, we'll wait the longer amount of time; no big deal. */
460         /* FIFO */
461         cfs_list_add_tail(&lock->l_pending_chain, &waiting_locks_list);
462         return 1;
463 }
464
465 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
466 {
467         int ret;
468         int timeout = ldlm_get_enq_timeout(lock);
469
470         /* NB: must be called with hold of lock_res_and_lock() */
471         LASSERT(lock->l_res_locked);
472         lock->l_waited = 1;
473
474         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
475
476         spin_lock_bh(&waiting_locks_spinlock);
477         if (lock->l_destroyed) {
478                 static cfs_time_t next;
479                 spin_unlock_bh(&waiting_locks_spinlock);
480                 LDLM_ERROR(lock, "not waiting on destroyed lock (bug 5653)");
481                 if (cfs_time_after(cfs_time_current(), next)) {
482                         next = cfs_time_shift(14400);
483                         libcfs_debug_dumpstack(NULL);
484                 }
485                 return 0;
486         }
487
488         ret = __ldlm_add_waiting_lock(lock, timeout);
489         if (ret) {
490                 /* grab ref on the lock if it has been added to the
491                  * waiting list */
492                 LDLM_LOCK_GET(lock);
493         }
494         spin_unlock_bh(&waiting_locks_spinlock);
495
496         if (ret) {
497                 spin_lock_bh(&lock->l_export->exp_bl_list_lock);
498                 if (cfs_list_empty(&lock->l_exp_list))
499                         cfs_list_add(&lock->l_exp_list,
500                                      &lock->l_export->exp_bl_list);
501                 spin_unlock_bh(&lock->l_export->exp_bl_list_lock);
502         }
503
504         LDLM_DEBUG(lock, "%sadding to wait list(timeout: %d, AT: %s)",
505                    ret == 0 ? "not re-" : "", timeout,
506                    AT_OFF ? "off" : "on");
507         return ret;
508 }
509
510 /**
511  * Remove a lock from the pending list, likely because it had its cancellation
512  * callback arrive without incident.  This adjusts the lock-timeout timer if
513  * needed.  Returns 0 if the lock wasn't pending after all, 1 if it was.
514  * As done by ldlm_del_waiting_lock(), the caller must release the lock
515  * reference when the lock is removed from any list (1 is returned).
516  *
517  * Called with namespace lock held.
518  */
519 static int __ldlm_del_waiting_lock(struct ldlm_lock *lock)
520 {
521         cfs_list_t *list_next;
522
523         if (cfs_list_empty(&lock->l_pending_chain))
524                 return 0;
525
526         list_next = lock->l_pending_chain.next;
527         if (lock->l_pending_chain.prev == &waiting_locks_list) {
528                 /* Removing the head of the list, adjust timer. */
529                 if (list_next == &waiting_locks_list) {
530                         /* No more, just cancel. */
531                         cfs_timer_disarm(&waiting_locks_timer);
532                 } else {
533                         struct ldlm_lock *next;
534                         next = cfs_list_entry(list_next, struct ldlm_lock,
535                                               l_pending_chain);
536                         cfs_timer_arm(&waiting_locks_timer,
537                                       round_timeout(next->l_callback_timeout));
538                 }
539         }
540         cfs_list_del_init(&lock->l_pending_chain);
541
542         return 1;
543 }
544
545 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
546 {
547         int ret;
548
549         if (lock->l_export == NULL) {
550                 /* We don't have a "waiting locks list" on clients. */
551                 CDEBUG(D_DLMTRACE, "Client lock %p : no-op\n", lock);
552                 return 0;
553         }
554
555         spin_lock_bh(&waiting_locks_spinlock);
556         ret = __ldlm_del_waiting_lock(lock);
557         spin_unlock_bh(&waiting_locks_spinlock);
558
559         /* remove the lock out of export blocking list */
560         spin_lock_bh(&lock->l_export->exp_bl_list_lock);
561         cfs_list_del_init(&lock->l_exp_list);
562         spin_unlock_bh(&lock->l_export->exp_bl_list_lock);
563
564         if (ret) {
565                 /* release lock ref if it has indeed been removed
566                  * from a list */
567                 LDLM_LOCK_RELEASE(lock);
568         }
569
570         LDLM_DEBUG(lock, "%s", ret == 0 ? "wasn't waiting" : "removed");
571         return ret;
572 }
573 EXPORT_SYMBOL(ldlm_del_waiting_lock);
574
575 /**
576  * Prolong the contended lock waiting time.
577  *
578  * Called with namespace lock held.
579  */
580 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
581 {
582         if (lock->l_export == NULL) {
583                 /* We don't have a "waiting locks list" on clients. */
584                 LDLM_DEBUG(lock, "client lock: no-op");
585                 return 0;
586         }
587
588         spin_lock_bh(&waiting_locks_spinlock);
589
590         if (cfs_list_empty(&lock->l_pending_chain)) {
591                 spin_unlock_bh(&waiting_locks_spinlock);
592                 LDLM_DEBUG(lock, "wasn't waiting");
593                 return 0;
594         }
595
596         /* we remove/add the lock to the waiting list, so no needs to
597          * release/take a lock reference */
598         __ldlm_del_waiting_lock(lock);
599         __ldlm_add_waiting_lock(lock, timeout);
600         spin_unlock_bh(&waiting_locks_spinlock);
601
602         LDLM_DEBUG(lock, "refreshed");
603         return 1;
604 }
605 EXPORT_SYMBOL(ldlm_refresh_waiting_lock);
606
607 #else /* !HAVE_SERVER_SUPPORT ||  !__KERNEL__ */
608
609 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
610 {
611         RETURN(0);
612 }
613
614 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
615 {
616         RETURN(0);
617 }
618
619 # ifdef HAVE_SERVER_SUPPORT
620 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
621 {
622         LASSERT(lock->l_res_locked);
623         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
624         RETURN(1);
625 }
626
627 # endif
628 #endif /* HAVE_SERVER_SUPPORT && __KERNEL__ */
629
630 #ifdef HAVE_SERVER_SUPPORT
631
632 /**
633  * Perform lock cleanup if AST sending failed.
634  */
635 static void ldlm_failed_ast(struct ldlm_lock *lock, int rc,
636                             const char *ast_type)
637 {
638         LCONSOLE_ERROR_MSG(0x138, "%s: A client on nid %s was evicted due "
639                            "to a lock %s callback time out: rc %d\n",
640                            lock->l_export->exp_obd->obd_name,
641                            obd_export_nid2str(lock->l_export), ast_type, rc);
642
643         if (obd_dump_on_timeout)
644                 libcfs_debug_dumplog();
645 #ifdef __KERNEL__
646         spin_lock_bh(&waiting_locks_spinlock);
647         if (__ldlm_del_waiting_lock(lock) == 0)
648                 /* the lock was not in any list, grab an extra ref before adding
649                  * the lock to the expired list */
650                 LDLM_LOCK_GET(lock);
651         cfs_list_add(&lock->l_pending_chain,
652                      &expired_lock_thread.elt_expired_locks);
653         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
654         spin_unlock_bh(&waiting_locks_spinlock);
655 #else
656         class_fail_export(lock->l_export);
657 #endif
658 }
659
660 /**
661  * Perform lock cleanup if AST reply came with error.
662  */
663 static int ldlm_handle_ast_error(struct ldlm_lock *lock,
664                                  struct ptlrpc_request *req, int rc,
665                                  const char *ast_type)
666 {
667         lnet_process_id_t peer = req->rq_import->imp_connection->c_peer;
668
669         if (rc == -ETIMEDOUT || rc == -EINTR || rc == -ENOTCONN) {
670                 LASSERT(lock->l_export);
671                 if (lock->l_export->exp_libclient) {
672                         LDLM_DEBUG(lock, "%s AST to liblustre client (nid %s)"
673                                    " timeout, just cancelling lock", ast_type,
674                                    libcfs_nid2str(peer.nid));
675                         ldlm_lock_cancel(lock);
676                         rc = -ERESTART;
677                 } else if (lock->l_flags & LDLM_FL_CANCEL) {
678                         LDLM_DEBUG(lock, "%s AST timeout from nid %s, but "
679                                    "cancel was received (AST reply lost?)",
680                                    ast_type, libcfs_nid2str(peer.nid));
681                         ldlm_lock_cancel(lock);
682                         rc = -ERESTART;
683                 } else {
684                         ldlm_del_waiting_lock(lock);
685                         ldlm_failed_ast(lock, rc, ast_type);
686                 }
687         } else if (rc) {
688                 if (rc == -EINVAL) {
689                         struct ldlm_resource *res = lock->l_resource;
690                         LDLM_DEBUG(lock, "client (nid %s) returned %d"
691                                " from %s AST - normal race",
692                                libcfs_nid2str(peer.nid),
693                                req->rq_repmsg ?
694                                lustre_msg_get_status(req->rq_repmsg) : -1,
695                                ast_type);
696                         if (res) {
697                                 /* update lvbo to return proper attributes.
698                                  * see bug 23174 */
699                                 ldlm_resource_getref(res);
700                                 ldlm_res_lvbo_update(res, NULL, 1);
701                                 ldlm_resource_putref(res);
702                         }
703
704                 } else {
705                         LDLM_ERROR(lock, "client (nid %s) returned %d "
706                                    "from %s AST", libcfs_nid2str(peer.nid),
707                                    (req->rq_repmsg != NULL) ?
708                                    lustre_msg_get_status(req->rq_repmsg) : 0,
709                                    ast_type);
710                 }
711                 ldlm_lock_cancel(lock);
712                 /* Server-side AST functions are called from ldlm_reprocess_all,
713                  * which needs to be told to please restart its reprocessing. */
714                 rc = -ERESTART;
715         }
716
717         return rc;
718 }
719
720 static int ldlm_cb_interpret(const struct lu_env *env,
721                              struct ptlrpc_request *req, void *data, int rc)
722 {
723         struct ldlm_cb_async_args *ca   = data;
724         struct ldlm_lock          *lock = ca->ca_lock;
725         struct ldlm_cb_set_arg    *arg  = ca->ca_set_arg;
726         ENTRY;
727
728         LASSERT(lock != NULL);
729
730         switch (arg->type) {
731         case LDLM_GL_CALLBACK:
732                 /* Update the LVB from disk if the AST failed
733                  * (this is a legal race)
734                  *
735                  * - Glimpse callback of local lock just returns
736                  *   -ELDLM_NO_LOCK_DATA.
737                  * - Glimpse callback of remote lock might return
738                  *   -ELDLM_NO_LOCK_DATA when inode is cleared. LU-274
739                  */
740                 if (rc == -ELDLM_NO_LOCK_DATA) {
741                         LDLM_DEBUG(lock, "lost race - client has a lock but no "
742                                    "inode");
743                         ldlm_res_lvbo_update(lock->l_resource, NULL, 1);
744                 } else if (rc != 0) {
745                         rc = ldlm_handle_ast_error(lock, req, rc, "glimpse");
746                 } else {
747                         rc = ldlm_res_lvbo_update(lock->l_resource, req, 1);
748                 }
749                 break;
750         case LDLM_BL_CALLBACK:
751                 if (rc != 0)
752                         rc = ldlm_handle_ast_error(lock, req, rc, "blocking");
753                 break;
754         case LDLM_CP_CALLBACK:
755                 if (rc != 0)
756                         rc = ldlm_handle_ast_error(lock, req, rc, "completion");
757                 break;
758         default:
759                 LDLM_ERROR(lock, "invalid opcode for lock callback %d",
760                            arg->type);
761                 LBUG();
762         }
763
764         /* release extra reference taken in ldlm_ast_fini() */
765         LDLM_LOCK_RELEASE(lock);
766
767         if (rc == -ERESTART)
768                 cfs_atomic_inc(&arg->restart);
769
770         RETURN(0);
771 }
772
773 static inline int ldlm_ast_fini(struct ptlrpc_request *req,
774                                 struct ldlm_cb_set_arg *arg,
775                                 struct ldlm_lock *lock,
776                                 int instant_cancel)
777 {
778         int rc = 0;
779         ENTRY;
780
781         if (unlikely(instant_cancel)) {
782                 rc = ptl_send_rpc(req, 1);
783                 ptlrpc_req_finished(req);
784                 if (rc == 0)
785                         cfs_atomic_inc(&arg->restart);
786         } else {
787                 LDLM_LOCK_GET(lock);
788                 ptlrpc_set_add_req(arg->set, req);
789         }
790
791         RETURN(rc);
792 }
793
794 /**
795  * Check if there are requests in the export request list which prevent
796  * the lock canceling and make these requests high priority ones.
797  */
798 static void ldlm_lock_reorder_req(struct ldlm_lock *lock)
799 {
800         struct ptlrpc_request *req;
801         ENTRY;
802
803         if (lock->l_export == NULL) {
804                 LDLM_DEBUG(lock, "client lock: no-op");
805                 RETURN_EXIT;
806         }
807
808         spin_lock_bh(&lock->l_export->exp_rpc_lock);
809         cfs_list_for_each_entry(req, &lock->l_export->exp_hp_rpcs,
810                                 rq_exp_list) {
811                 /* Do not process requests that were not yet added to there
812                  * incoming queue or were already removed from there for
813                  * processing. We evaluate ptlrpc_nrs_req_can_move() without
814                  * holding svcpt->scp_req_lock, and then redo the check with
815                  * the lock held once we need to obtain a reliable result.
816                  */
817                 if (ptlrpc_nrs_req_can_move(req) &&
818                     req->rq_ops->hpreq_lock_match &&
819                     req->rq_ops->hpreq_lock_match(req, lock))
820                         ptlrpc_nrs_req_hp_move(req);
821         }
822         spin_unlock_bh(&lock->l_export->exp_rpc_lock);
823         EXIT;
824 }
825
826 /**
827  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
828  * enqueued server lock conflicts with given one.
829  *
830  * Sends blocking AST RPC to the client owning that lock; arms timeout timer
831  * to wait for client response.
832  */
833 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
834                              struct ldlm_lock_desc *desc,
835                              void *data, int flag)
836 {
837         struct ldlm_cb_async_args *ca;
838         struct ldlm_cb_set_arg *arg = data;
839         struct ldlm_request    *body;
840         struct ptlrpc_request  *req;
841         int                     instant_cancel = 0;
842         int                     rc = 0;
843         ENTRY;
844
845         if (flag == LDLM_CB_CANCELING)
846                 /* Don't need to do anything here. */
847                 RETURN(0);
848
849         LASSERT(lock);
850         LASSERT(data != NULL);
851         if (lock->l_export->exp_obd->obd_recovering != 0)
852                 LDLM_ERROR(lock, "BUG 6063: lock collide during recovery");
853
854         ldlm_lock_reorder_req(lock);
855
856         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
857                                         &RQF_LDLM_BL_CALLBACK,
858                                         LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK);
859         if (req == NULL)
860                 RETURN(-ENOMEM);
861
862         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
863         ca = ptlrpc_req_async_args(req);
864         ca->ca_set_arg = arg;
865         ca->ca_lock = lock;
866
867         req->rq_interpret_reply = ldlm_cb_interpret;
868         req->rq_no_resend = 1;
869
870         lock_res_and_lock(lock);
871         if (lock->l_granted_mode != lock->l_req_mode) {
872                 /* this blocking AST will be communicated as part of the
873                  * completion AST instead */
874                 unlock_res_and_lock(lock);
875
876                 ptlrpc_req_finished(req);
877                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
878                 RETURN(0);
879         }
880
881         if (lock->l_destroyed) {
882                 /* What's the point? */
883                 unlock_res_and_lock(lock);
884                 ptlrpc_req_finished(req);
885                 RETURN(0);
886         }
887
888         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
889                 instant_cancel = 1;
890
891         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
892         body->lock_handle[0] = lock->l_remote_handle;
893         body->lock_desc = *desc;
894         body->lock_flags |= ldlm_flags_to_wire(lock->l_flags & LDLM_AST_FLAGS);
895
896         LDLM_DEBUG(lock, "server preparing blocking AST");
897
898         ptlrpc_request_set_replen(req);
899         if (instant_cancel) {
900                 unlock_res_and_lock(lock);
901                 ldlm_lock_cancel(lock);
902         } else {
903                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
904                 ldlm_add_waiting_lock(lock);
905                 unlock_res_and_lock(lock);
906         }
907
908         req->rq_send_state = LUSTRE_IMP_FULL;
909         /* ptlrpc_request_alloc_pack already set timeout */
910         if (AT_OFF)
911                 req->rq_timeout = ldlm_get_rq_timeout();
912
913         if (lock->l_export && lock->l_export->exp_nid_stats &&
914             lock->l_export->exp_nid_stats->nid_ldlm_stats)
915                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
916                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
917
918         rc = ldlm_ast_fini(req, arg, lock, instant_cancel);
919
920         RETURN(rc);
921 }
922 EXPORT_SYMBOL(ldlm_server_blocking_ast);
923
924 /**
925  * ->l_completion_ast callback for a remote lock in server namespace.
926  *
927  *  Sends AST to the client notifying it of lock granting.  If initial
928  *  lock response was not sent yet, instead of sending another RPC, just
929  *  mark the lock as granted and client will understand
930  */
931 int ldlm_server_completion_ast(struct ldlm_lock *lock, __u64 flags, void *data)
932 {
933         struct ldlm_cb_set_arg *arg = data;
934         struct ldlm_request    *body;
935         struct ptlrpc_request  *req;
936         struct ldlm_cb_async_args *ca;
937         long                    total_enqueue_wait;
938         int                     instant_cancel = 0;
939         int                     rc = 0;
940         int                     lvb_len;
941         ENTRY;
942
943         LASSERT(lock != NULL);
944         LASSERT(data != NULL);
945
946         total_enqueue_wait = cfs_time_sub(cfs_time_current_sec(),
947                                           lock->l_last_activity);
948
949         req = ptlrpc_request_alloc(lock->l_export->exp_imp_reverse,
950                                     &RQF_LDLM_CP_CALLBACK);
951         if (req == NULL)
952                 RETURN(-ENOMEM);
953
954         /* server namespace, doesn't need lock */
955         lvb_len = ldlm_lvbo_size(lock);
956         /* LU-3124 & LU-2187: to not return layout in completion AST because
957          * it may deadlock for LU-2187, or client may not have enough space
958          * for large layout. The layout will be returned to client with an
959          * extra RPC to fetch xattr.lov */
960         if (ldlm_has_layout(lock))
961                 lvb_len = 0;
962
963         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT, lvb_len);
964         rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK);
965         if (rc) {
966                 ptlrpc_request_free(req);
967                 RETURN(rc);
968         }
969
970         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
971         ca = ptlrpc_req_async_args(req);
972         ca->ca_set_arg = arg;
973         ca->ca_lock = lock;
974
975         req->rq_interpret_reply = ldlm_cb_interpret;
976         req->rq_no_resend = 1;
977         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
978
979         body->lock_handle[0] = lock->l_remote_handle;
980         body->lock_flags = ldlm_flags_to_wire(flags);
981         ldlm_lock2desc(lock, &body->lock_desc);
982         if (lvb_len > 0) {
983                 void *lvb = req_capsule_client_get(&req->rq_pill, &RMF_DLM_LVB);
984
985                 lvb_len = ldlm_lvbo_fill(lock, lvb, lvb_len);
986                 if (lvb_len < 0) {
987                         /* We still need to send the RPC to wake up the blocked
988                          * enqueue thread on the client.
989                          *
990                          * Consider old client, there is no better way to notify
991                          * the failure, just zero-sized the LVB, then the client
992                          * will fail out as "-EPROTO". */
993                         req_capsule_shrink(&req->rq_pill, &RMF_DLM_LVB, 0,
994                                            RCL_CLIENT);
995                         instant_cancel = 1;
996                 } else {
997                         req_capsule_shrink(&req->rq_pill, &RMF_DLM_LVB, lvb_len,
998                                            RCL_CLIENT);
999                 }
1000         }
1001
1002         LDLM_DEBUG(lock, "server preparing completion AST (after %lds wait)",
1003                    total_enqueue_wait);
1004
1005         /* Server-side enqueue wait time estimate, used in
1006             __ldlm_add_waiting_lock to set future enqueue timers */
1007         if (total_enqueue_wait < ldlm_get_enq_timeout(lock))
1008                 at_measured(ldlm_lock_to_ns_at(lock),
1009                             total_enqueue_wait);
1010         else
1011                 /* bz18618. Don't add lock enqueue time we spend waiting for a
1012                    previous callback to fail. Locks waiting legitimately will
1013                    get extended by ldlm_refresh_waiting_lock regardless of the
1014                    estimate, so it's okay to underestimate here. */
1015                 LDLM_DEBUG(lock, "lock completed after %lus; estimate was %ds. "
1016                        "It is likely that a previous callback timed out.",
1017                        total_enqueue_wait,
1018                        at_get(ldlm_lock_to_ns_at(lock)));
1019
1020         ptlrpc_request_set_replen(req);
1021
1022         req->rq_send_state = LUSTRE_IMP_FULL;
1023         /* ptlrpc_request_pack already set timeout */
1024         if (AT_OFF)
1025                 req->rq_timeout = ldlm_get_rq_timeout();
1026
1027         /* We only send real blocking ASTs after the lock is granted */
1028         lock_res_and_lock(lock);
1029         if (lock->l_flags & LDLM_FL_AST_SENT) {
1030                 body->lock_flags |= ldlm_flags_to_wire(LDLM_FL_AST_SENT);
1031                 /* Copy AST flags like LDLM_FL_DISCARD_DATA. */
1032                 body->lock_flags |= ldlm_flags_to_wire(lock->l_flags &
1033                                                        LDLM_AST_FLAGS);
1034
1035                 /* We might get here prior to ldlm_handle_enqueue setting
1036                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
1037                  * into waiting list, but this is safe and similar code in
1038                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
1039                  * that would not only cancel the lock, but will also remove
1040                  * it from waiting list */
1041                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1042                         unlock_res_and_lock(lock);
1043                         ldlm_lock_cancel(lock);
1044                         instant_cancel = 1;
1045                         lock_res_and_lock(lock);
1046                 } else {
1047                         /* start the lock-timeout clock */
1048                         ldlm_add_waiting_lock(lock);
1049                 }
1050         }
1051         unlock_res_and_lock(lock);
1052
1053         if (lock->l_export && lock->l_export->exp_nid_stats &&
1054             lock->l_export->exp_nid_stats->nid_ldlm_stats)
1055                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
1056                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
1057
1058         rc = ldlm_ast_fini(req, arg, lock, instant_cancel);
1059
1060         RETURN(lvb_len < 0 ? lvb_len : rc);
1061 }
1062 EXPORT_SYMBOL(ldlm_server_completion_ast);
1063
1064 /**
1065  * Server side ->l_glimpse_ast handler for client locks.
1066  *
1067  * Sends glimpse AST to the client and waits for reply. Then updates
1068  * lvbo with the result.
1069  */
1070 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
1071 {
1072         struct ldlm_cb_set_arg          *arg = data;
1073         struct ldlm_request             *body;
1074         struct ptlrpc_request           *req;
1075         struct ldlm_cb_async_args       *ca;
1076         int                              rc;
1077         struct req_format               *req_fmt;
1078         ENTRY;
1079
1080         LASSERT(lock != NULL);
1081
1082         if (arg->gl_desc != NULL)
1083                 /* There is a glimpse descriptor to pack */
1084                 req_fmt = &RQF_LDLM_GL_DESC_CALLBACK;
1085         else
1086                 req_fmt = &RQF_LDLM_GL_CALLBACK;
1087
1088         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
1089                                         req_fmt, LUSTRE_DLM_VERSION,
1090                                         LDLM_GL_CALLBACK);
1091
1092         if (req == NULL)
1093                 RETURN(-ENOMEM);
1094
1095         if (arg->gl_desc != NULL) {
1096                 /* copy the GL descriptor */
1097                 union ldlm_gl_desc      *desc;
1098                 desc = req_capsule_client_get(&req->rq_pill, &RMF_DLM_GL_DESC);
1099                 *desc = *arg->gl_desc;
1100         }
1101
1102         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1103         body->lock_handle[0] = lock->l_remote_handle;
1104         ldlm_lock2desc(lock, &body->lock_desc);
1105
1106         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
1107         ca = ptlrpc_req_async_args(req);
1108         ca->ca_set_arg = arg;
1109         ca->ca_lock = lock;
1110
1111         /* server namespace, doesn't need lock */
1112         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
1113                              ldlm_lvbo_size(lock));
1114         ptlrpc_request_set_replen(req);
1115
1116         req->rq_send_state = LUSTRE_IMP_FULL;
1117         /* ptlrpc_request_alloc_pack already set timeout */
1118         if (AT_OFF)
1119                 req->rq_timeout = ldlm_get_rq_timeout();
1120
1121         req->rq_interpret_reply = ldlm_cb_interpret;
1122
1123         if (lock->l_export && lock->l_export->exp_nid_stats &&
1124             lock->l_export->exp_nid_stats->nid_ldlm_stats)
1125                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
1126                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
1127
1128         rc = ldlm_ast_fini(req, arg, lock, 0);
1129
1130         RETURN(rc);
1131 }
1132 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
1133
1134 int ldlm_glimpse_locks(struct ldlm_resource *res, cfs_list_t *gl_work_list)
1135 {
1136         int     rc;
1137         ENTRY;
1138
1139         rc = ldlm_run_ast_work(ldlm_res_to_ns(res), gl_work_list,
1140                                LDLM_WORK_GL_AST);
1141         if (rc == -ERESTART)
1142                 ldlm_reprocess_all(res);
1143
1144         RETURN(rc);
1145 }
1146 EXPORT_SYMBOL(ldlm_glimpse_locks);
1147
1148 /* return LDLM lock associated with a lock callback request */
1149 struct ldlm_lock *ldlm_request_lock(struct ptlrpc_request *req)
1150 {
1151         struct ldlm_cb_async_args       *ca;
1152         struct ldlm_lock                *lock;
1153         ENTRY;
1154
1155         ca = ptlrpc_req_async_args(req);
1156         lock = ca->ca_lock;
1157         if (lock == NULL)
1158                 RETURN(ERR_PTR(-EFAULT));
1159
1160         RETURN(lock);
1161 }
1162 EXPORT_SYMBOL(ldlm_request_lock);
1163
1164 static void ldlm_svc_get_eopc(const struct ldlm_request *dlm_req,
1165                        struct lprocfs_stats *srv_stats)
1166 {
1167         int lock_type = 0, op = 0;
1168
1169         lock_type = dlm_req->lock_desc.l_resource.lr_type;
1170
1171         switch (lock_type) {
1172         case LDLM_PLAIN:
1173                 op = PTLRPC_LAST_CNTR + LDLM_PLAIN_ENQUEUE;
1174                 break;
1175         case LDLM_EXTENT:
1176                 if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT)
1177                         op = PTLRPC_LAST_CNTR + LDLM_GLIMPSE_ENQUEUE;
1178                 else
1179                         op = PTLRPC_LAST_CNTR + LDLM_EXTENT_ENQUEUE;
1180                 break;
1181         case LDLM_FLOCK:
1182                 op = PTLRPC_LAST_CNTR + LDLM_FLOCK_ENQUEUE;
1183                 break;
1184         case LDLM_IBITS:
1185                 op = PTLRPC_LAST_CNTR + LDLM_IBITS_ENQUEUE;
1186                 break;
1187         default:
1188                 op = 0;
1189                 break;
1190         }
1191
1192         if (op)
1193                 lprocfs_counter_incr(srv_stats, op);
1194
1195         return;
1196 }
1197
1198 /**
1199  * Main server-side entry point into LDLM for enqueue. This is called by ptlrpc
1200  * service threads to carry out client lock enqueueing requests.
1201  */
1202 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
1203                          struct ptlrpc_request *req,
1204                          const struct ldlm_request *dlm_req,
1205                          const struct ldlm_callback_suite *cbs)
1206 {
1207         struct ldlm_reply *dlm_rep;
1208         __u64 flags;
1209         ldlm_error_t err = ELDLM_OK;
1210         struct ldlm_lock *lock = NULL;
1211         void *cookie = NULL;
1212         int rc = 0;
1213         ENTRY;
1214
1215         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
1216
1217         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
1218         flags = ldlm_flags_from_wire(dlm_req->lock_flags);
1219
1220         LASSERT(req->rq_export);
1221
1222         if (ptlrpc_req2svc(req)->srv_stats != NULL)
1223                 ldlm_svc_get_eopc(dlm_req, ptlrpc_req2svc(req)->srv_stats);
1224
1225         if (req->rq_export && req->rq_export->exp_nid_stats &&
1226             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1227                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1228                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
1229
1230         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
1231                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
1232                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
1233                           dlm_req->lock_desc.l_resource.lr_type);
1234                 GOTO(out, rc = -EFAULT);
1235         }
1236
1237         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
1238                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
1239                      dlm_req->lock_desc.l_req_mode &
1240                      (dlm_req->lock_desc.l_req_mode-1))) {
1241                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
1242                           dlm_req->lock_desc.l_req_mode);
1243                 GOTO(out, rc = -EFAULT);
1244         }
1245
1246         if (exp_connect_flags(req->rq_export) & OBD_CONNECT_IBITS) {
1247                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1248                              LDLM_PLAIN)) {
1249                         DEBUG_REQ(D_ERROR, req,
1250                                   "PLAIN lock request from IBITS client?");
1251                         GOTO(out, rc = -EPROTO);
1252                 }
1253         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1254                             LDLM_IBITS)) {
1255                 DEBUG_REQ(D_ERROR, req,
1256                           "IBITS lock request from unaware client?");
1257                 GOTO(out, rc = -EPROTO);
1258         }
1259
1260 #if 0
1261         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
1262            against server's _CONNECT_SUPPORTED flags? (I don't want to use
1263            ibits for mgc/mgs) */
1264
1265         /* INODEBITS_INTEROP: Perform conversion from plain lock to
1266          * inodebits lock if client does not support them. */
1267         if (!(exp_connect_flags(req->rq_export) & OBD_CONNECT_IBITS) &&
1268             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
1269                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
1270                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
1271                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
1272                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
1273                         dlm_req->lock_desc.l_req_mode = LCK_CR;
1274         }
1275 #endif
1276
1277         if (unlikely(flags & LDLM_FL_REPLAY)) {
1278                 /* Find an existing lock in the per-export lock hash */
1279                 /* In the function below, .hs_keycmp resolves to
1280                  * ldlm_export_lock_keycmp() */
1281                 /* coverity[overrun-buffer-val] */
1282                 lock = cfs_hash_lookup(req->rq_export->exp_lock_hash,
1283                                        (void *)&dlm_req->lock_handle[0]);
1284                 if (lock != NULL) {
1285                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
1286                                   LPX64, lock->l_handle.h_cookie);
1287                         GOTO(existing_lock, rc = 0);
1288                 }
1289         }
1290
1291         /* The lock's callback data might be set in the policy function */
1292         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
1293                                 dlm_req->lock_desc.l_resource.lr_type,
1294                                 dlm_req->lock_desc.l_req_mode,
1295                                 cbs, NULL, 0, LVB_T_NONE);
1296         if (!lock)
1297                 GOTO(out, rc = -ENOMEM);
1298
1299         lock->l_last_activity = cfs_time_current_sec();
1300         lock->l_remote_handle = dlm_req->lock_handle[0];
1301         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
1302
1303         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
1304         /* Don't enqueue a lock onto the export if it is been disonnected
1305          * due to eviction (bug 3822) or server umount (bug 24324).
1306          * Cancel it now instead. */
1307         if (req->rq_export->exp_disconnected) {
1308                 LDLM_ERROR(lock, "lock on disconnected export %p",
1309                            req->rq_export);
1310                 GOTO(out, rc = -ENOTCONN);
1311         }
1312
1313         lock->l_export = class_export_lock_get(req->rq_export, lock);
1314         if (lock->l_export->exp_lock_hash)
1315                 cfs_hash_add(lock->l_export->exp_lock_hash,
1316                              &lock->l_remote_handle,
1317                              &lock->l_exp_hash);
1318
1319 existing_lock:
1320
1321         if (flags & LDLM_FL_HAS_INTENT) {
1322                 /* In this case, the reply buffer is allocated deep in
1323                  * local_lock_enqueue by the policy function. */
1324                 cookie = req;
1325         } else {
1326                 /* based on the assumption that lvb size never changes during
1327                  * resource life time otherwise it need resource->lr_lock's
1328                  * protection */
1329                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
1330                                      RCL_SERVER, ldlm_lvbo_size(lock));
1331
1332                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
1333                         GOTO(out, rc = -ENOMEM);
1334
1335                 rc = req_capsule_server_pack(&req->rq_pill);
1336                 if (rc)
1337                         GOTO(out, rc);
1338         }
1339
1340         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
1341                 ldlm_convert_policy_to_local(req->rq_export,
1342                                           dlm_req->lock_desc.l_resource.lr_type,
1343                                           &dlm_req->lock_desc.l_policy_data,
1344                                           &lock->l_policy_data);
1345         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
1346                 lock->l_req_extent = lock->l_policy_data.l_extent;
1347
1348         err = ldlm_lock_enqueue(ns, &lock, cookie, &flags);
1349         if (err)
1350                 GOTO(out, err);
1351
1352         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1353         dlm_rep->lock_flags = ldlm_flags_to_wire(flags);
1354
1355         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
1356         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
1357
1358         /* We never send a blocking AST until the lock is granted, but
1359          * we can tell it right now */
1360         lock_res_and_lock(lock);
1361
1362         /* Now take into account flags to be inherited from original lock
1363            request both in reply to client and in our own lock flags. */
1364         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1365         lock->l_flags |= ldlm_flags_from_wire(dlm_req->lock_flags &
1366                                               LDLM_INHERIT_FLAGS);
1367
1368         /* Don't move a pending lock onto the export if it has already been
1369          * disconnected due to eviction (bug 5683) or server umount (bug 24324).
1370          * Cancel it now instead. */
1371         if (unlikely(req->rq_export->exp_disconnected ||
1372                      OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
1373                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1374                 rc = -ENOTCONN;
1375         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
1376                 dlm_rep->lock_flags |= ldlm_flags_to_wire(LDLM_FL_AST_SENT);
1377                 if (lock->l_granted_mode == lock->l_req_mode) {
1378                         /*
1379                          * Only cancel lock if it was granted, because it would
1380                          * be destroyed immediately and would never be granted
1381                          * in the future, causing timeouts on client.  Not
1382                          * granted lock will be cancelled immediately after
1383                          * sending completion AST.
1384                          */
1385                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1386                                 unlock_res_and_lock(lock);
1387                                 ldlm_lock_cancel(lock);
1388                                 lock_res_and_lock(lock);
1389                         } else
1390                                 ldlm_add_waiting_lock(lock);
1391                 }
1392         }
1393         /* Make sure we never ever grant usual metadata locks to liblustre
1394            clients */
1395         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1396             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1397              req->rq_export->exp_libclient) {
1398                 if (unlikely(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
1399                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
1400                         CERROR("Granting sync lock to libclient. "
1401                                "req fl %d, rep fl %d, lock fl "LPX64"\n",
1402                                dlm_req->lock_flags, dlm_rep->lock_flags,
1403                                lock->l_flags);
1404                         LDLM_ERROR(lock, "sync lock");
1405                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1406                                 struct ldlm_intent *it;
1407
1408                                 it = req_capsule_client_get(&req->rq_pill,
1409                                                             &RMF_LDLM_INTENT);
1410                                 if (it != NULL) {
1411                                         CERROR("This is intent %s ("LPU64")\n",
1412                                                ldlm_it2str(it->opc), it->opc);
1413                                 }
1414                         }
1415                 }
1416         }
1417
1418         unlock_res_and_lock(lock);
1419
1420         EXIT;
1421  out:
1422         req->rq_status = rc ?: err; /* return either error - bug 11190 */
1423         if (!req->rq_packed_final) {
1424                 err = lustre_pack_reply(req, 1, NULL, NULL);
1425                 if (rc == 0)
1426                         rc = err;
1427         }
1428
1429         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1430          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1431         if (lock) {
1432                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1433                            "(err=%d, rc=%d)", err, rc);
1434
1435                 if (rc == 0) {
1436                         if (req_capsule_has_field(&req->rq_pill, &RMF_DLM_LVB,
1437                                                   RCL_SERVER) &&
1438                             ldlm_lvbo_size(lock) > 0) {
1439                                 void *buf;
1440                                 int buflen;
1441
1442                                 buf = req_capsule_server_get(&req->rq_pill,
1443                                                              &RMF_DLM_LVB);
1444                                 LASSERTF(buf != NULL, "req %p, lock %p\n",
1445                                          req, lock);
1446                                 buflen = req_capsule_get_size(&req->rq_pill,
1447                                                 &RMF_DLM_LVB, RCL_SERVER);
1448                                 buflen = ldlm_lvbo_fill(lock, buf, buflen);
1449                                 if (buflen >= 0)
1450                                         req_capsule_shrink(&req->rq_pill,
1451                                                            &RMF_DLM_LVB,
1452                                                            buflen, RCL_SERVER);
1453                                 else
1454                                         rc = buflen;
1455                         }
1456                 } else {
1457                         lock_res_and_lock(lock);
1458                         ldlm_resource_unlink_lock(lock);
1459                         ldlm_lock_destroy_nolock(lock);
1460                         unlock_res_and_lock(lock);
1461                 }
1462
1463                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1464                         ldlm_reprocess_all(lock->l_resource);
1465
1466                 LDLM_LOCK_RELEASE(lock);
1467         }
1468
1469         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1470                           lock, rc);
1471
1472         return rc;
1473 }
1474 EXPORT_SYMBOL(ldlm_handle_enqueue0);
1475
1476 /**
1477  * Old-style LDLM main entry point for server code enqueue.
1478  */
1479 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1480                         ldlm_completion_callback completion_callback,
1481                         ldlm_blocking_callback blocking_callback,
1482                         ldlm_glimpse_callback glimpse_callback)
1483 {
1484         struct ldlm_request *dlm_req;
1485         struct ldlm_callback_suite cbs = {
1486                 .lcs_completion = completion_callback,
1487                 .lcs_blocking   = blocking_callback,
1488                 .lcs_glimpse    = glimpse_callback
1489         };
1490         int rc;
1491
1492         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1493         if (dlm_req != NULL) {
1494                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1495                                           req, dlm_req, &cbs);
1496         } else {
1497                 rc = -EFAULT;
1498         }
1499         return rc;
1500 }
1501 EXPORT_SYMBOL(ldlm_handle_enqueue);
1502
1503 /**
1504  * Main LDLM entry point for server code to process lock conversion requests.
1505  */
1506 int ldlm_handle_convert0(struct ptlrpc_request *req,
1507                          const struct ldlm_request *dlm_req)
1508 {
1509         struct ldlm_reply *dlm_rep;
1510         struct ldlm_lock *lock;
1511         int rc;
1512         ENTRY;
1513
1514         if (req->rq_export && req->rq_export->exp_nid_stats &&
1515             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1516                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1517                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1518
1519         rc = req_capsule_server_pack(&req->rq_pill);
1520         if (rc)
1521                 RETURN(rc);
1522
1523         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1524         dlm_rep->lock_flags = dlm_req->lock_flags;
1525
1526         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1527         if (!lock) {
1528                 req->rq_status = EINVAL;
1529         } else {
1530                 void *res = NULL;
1531
1532                 LDLM_DEBUG(lock, "server-side convert handler START");
1533
1534                 lock->l_last_activity = cfs_time_current_sec();
1535                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1536                                         &dlm_rep->lock_flags);
1537                 if (res) {
1538                         if (ldlm_del_waiting_lock(lock))
1539                                 LDLM_DEBUG(lock, "converted waiting lock");
1540                         req->rq_status = 0;
1541                 } else {
1542                         req->rq_status = EDEADLOCK;
1543                 }
1544         }
1545
1546         if (lock) {
1547                 if (!req->rq_status)
1548                         ldlm_reprocess_all(lock->l_resource);
1549                 LDLM_DEBUG(lock, "server-side convert handler END");
1550                 LDLM_LOCK_PUT(lock);
1551         } else
1552                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1553
1554         RETURN(0);
1555 }
1556 EXPORT_SYMBOL(ldlm_handle_convert0);
1557
1558 /**
1559  * Old-style main LDLM entry point for server code to process lock conversion
1560  * requests.
1561  */
1562 int ldlm_handle_convert(struct ptlrpc_request *req)
1563 {
1564         int rc;
1565         struct ldlm_request *dlm_req;
1566
1567         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1568         if (dlm_req != NULL) {
1569                 rc = ldlm_handle_convert0(req, dlm_req);
1570         } else {
1571                 CERROR ("Can't unpack dlm_req\n");
1572                 rc = -EFAULT;
1573         }
1574         return rc;
1575 }
1576 EXPORT_SYMBOL(ldlm_handle_convert);
1577
1578 /**
1579  * Cancel all the locks whose handles are packed into ldlm_request
1580  *
1581  * Called by server code expecting such combined cancel activity
1582  * requests.
1583  */
1584 int ldlm_request_cancel(struct ptlrpc_request *req,
1585                         const struct ldlm_request *dlm_req, int first)
1586 {
1587         struct ldlm_resource *res, *pres = NULL;
1588         struct ldlm_lock *lock;
1589         int i, count, done = 0;
1590         ENTRY;
1591
1592         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1593         if (first >= count)
1594                 RETURN(0);
1595
1596         if (count == 1 && dlm_req->lock_handle[0].cookie == 0)
1597                 RETURN(0);
1598
1599         /* There is no lock on the server at the replay time,
1600          * skip lock cancelling to make replay tests to pass. */
1601         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1602                 RETURN(0);
1603
1604         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1605                           "starting at %d", count, first);
1606
1607         for (i = first; i < count; i++) {
1608                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1609                 if (!lock) {
1610                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1611                                           "lock (cookie "LPU64")",
1612                                           dlm_req->lock_handle[i].cookie);
1613                         continue;
1614                 }
1615
1616                 res = lock->l_resource;
1617                 done++;
1618
1619                 /* This code is an optimization to only attempt lock
1620                  * granting on the resource (that could be CPU-expensive)
1621                  * after we are done cancelling lock in that resource. */
1622                 if (res != pres) {
1623                         if (pres != NULL) {
1624                                 ldlm_reprocess_all(pres);
1625                                 LDLM_RESOURCE_DELREF(pres);
1626                                 ldlm_resource_putref(pres);
1627                         }
1628                         if (res != NULL) {
1629                                 ldlm_resource_getref(res);
1630                                 LDLM_RESOURCE_ADDREF(res);
1631                                 ldlm_res_lvbo_update(res, NULL, 1);
1632                         }
1633                         pres = res;
1634                 }
1635                 ldlm_lock_cancel(lock);
1636                 LDLM_LOCK_PUT(lock);
1637         }
1638         if (pres != NULL) {
1639                 ldlm_reprocess_all(pres);
1640                 LDLM_RESOURCE_DELREF(pres);
1641                 ldlm_resource_putref(pres);
1642         }
1643         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1644         RETURN(done);
1645 }
1646 EXPORT_SYMBOL(ldlm_request_cancel);
1647
1648 /**
1649  * Main LDLM entry point for server code to cancel locks.
1650  *
1651  * Typically gets called from service handler on LDLM_CANCEL opc.
1652  */
1653 int ldlm_handle_cancel(struct ptlrpc_request *req)
1654 {
1655         struct ldlm_request *dlm_req;
1656         int rc;
1657         ENTRY;
1658
1659         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1660         if (dlm_req == NULL) {
1661                 CDEBUG(D_INFO, "bad request buffer for cancel\n");
1662                 RETURN(-EFAULT);
1663         }
1664
1665         if (req->rq_export && req->rq_export->exp_nid_stats &&
1666             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1667                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1668                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1669
1670         rc = req_capsule_server_pack(&req->rq_pill);
1671         if (rc)
1672                 RETURN(rc);
1673
1674         if (!ldlm_request_cancel(req, dlm_req, 0))
1675                 req->rq_status = ESTALE;
1676
1677         RETURN(ptlrpc_reply(req));
1678 }
1679 EXPORT_SYMBOL(ldlm_handle_cancel);
1680 #endif /* HAVE_SERVER_SUPPORT */
1681
1682 /**
1683  * Callback handler for receiving incoming blocking ASTs.
1684  *
1685  * This can only happen on client side.
1686  */
1687 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1688                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1689 {
1690         int do_ast;
1691         ENTRY;
1692
1693         LDLM_DEBUG(lock, "client blocking AST callback handler");
1694
1695         lock_res_and_lock(lock);
1696         lock->l_flags |= LDLM_FL_CBPENDING;
1697
1698         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1699                 lock->l_flags |= LDLM_FL_CANCEL;
1700
1701         do_ast = (!lock->l_readers && !lock->l_writers);
1702         unlock_res_and_lock(lock);
1703
1704         if (do_ast) {
1705                 CDEBUG(D_DLMTRACE, "Lock %p already unused, calling callback (%p)\n",
1706                        lock, lock->l_blocking_ast);
1707                 if (lock->l_blocking_ast != NULL)
1708                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1709                                              LDLM_CB_BLOCKING);
1710         } else {
1711                 CDEBUG(D_DLMTRACE, "Lock %p is referenced, will be cancelled later\n",
1712                        lock);
1713         }
1714
1715         LDLM_DEBUG(lock, "client blocking callback handler END");
1716         LDLM_LOCK_RELEASE(lock);
1717         EXIT;
1718 }
1719
1720 /**
1721  * Callback handler for receiving incoming completion ASTs.
1722  *
1723  * This only can happen on client side.
1724  */
1725 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1726                                     struct ldlm_namespace *ns,
1727                                     struct ldlm_request *dlm_req,
1728                                     struct ldlm_lock *lock)
1729 {
1730         int lvb_len;
1731         CFS_LIST_HEAD(ast_list);
1732         int rc = 0;
1733         ENTRY;
1734
1735         LDLM_DEBUG(lock, "client completion callback handler START");
1736
1737         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE)) {
1738                 int to = cfs_time_seconds(1);
1739                 while (to > 0) {
1740                         cfs_schedule_timeout_and_set_state(
1741                                 CFS_TASK_INTERRUPTIBLE, to);
1742                         if (lock->l_granted_mode == lock->l_req_mode ||
1743                             lock->l_destroyed)
1744                                 break;
1745                 }
1746         }
1747
1748         lvb_len = req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT);
1749         if (lvb_len < 0) {
1750                 LDLM_ERROR(lock, "Fail to get lvb_len, rc = %d", lvb_len);
1751                 GOTO(out, rc = lvb_len);
1752         } else if (lvb_len > 0) {
1753                 if (lock->l_lvb_len > 0) {
1754                         /* for extent lock, lvb contains ost_lvb{}. */
1755                         LASSERT(lock->l_lvb_data != NULL);
1756
1757                         if (unlikely(lock->l_lvb_len < lvb_len)) {
1758                                 LDLM_ERROR(lock, "Replied LVB is larger than "
1759                                            "expectation, expected = %d, "
1760                                            "replied = %d",
1761                                            lock->l_lvb_len, lvb_len);
1762                                 GOTO(out, rc = -EINVAL);
1763                         }
1764                 } else if (ldlm_has_layout(lock)) { /* for layout lock, lvb has
1765                                                      * variable length */
1766                         void *lvb_data;
1767
1768                         OBD_ALLOC(lvb_data, lvb_len);
1769                         if (lvb_data == NULL) {
1770                                 LDLM_ERROR(lock, "No memory: %d.\n", lvb_len);
1771                                 GOTO(out, rc = -ENOMEM);
1772                         }
1773
1774                         lock_res_and_lock(lock);
1775                         LASSERT(lock->l_lvb_data == NULL);
1776                         lock->l_lvb_data = lvb_data;
1777                         lock->l_lvb_len = lvb_len;
1778                         unlock_res_and_lock(lock);
1779                 }
1780         }
1781
1782         lock_res_and_lock(lock);
1783         if (lock->l_destroyed ||
1784             lock->l_granted_mode == lock->l_req_mode) {
1785                 /* bug 11300: the lock has already been granted */
1786                 unlock_res_and_lock(lock);
1787                 LDLM_DEBUG(lock, "Double grant race happened");
1788                 GOTO(out, rc = 0);
1789         }
1790
1791         /* If we receive the completion AST before the actual enqueue returned,
1792          * then we might need to switch lock modes, resources, or extents. */
1793         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1794                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1795                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1796         }
1797
1798         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1799                 ldlm_convert_policy_to_local(req->rq_export,
1800                                           dlm_req->lock_desc.l_resource.lr_type,
1801                                           &dlm_req->lock_desc.l_policy_data,
1802                                           &lock->l_policy_data);
1803                 LDLM_DEBUG(lock, "completion AST, new policy data");
1804         }
1805
1806         ldlm_resource_unlink_lock(lock);
1807         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1808                    &lock->l_resource->lr_name,
1809                    sizeof(lock->l_resource->lr_name)) != 0) {
1810                 unlock_res_and_lock(lock);
1811                 rc = ldlm_lock_change_resource(ns, lock,
1812                                 &dlm_req->lock_desc.l_resource.lr_name);
1813                 if (rc < 0) {
1814                         LDLM_ERROR(lock, "Failed to allocate resource");
1815                         GOTO(out, rc);
1816                 }
1817                 LDLM_DEBUG(lock, "completion AST, new resource");
1818                 CERROR("change resource!\n");
1819                 lock_res_and_lock(lock);
1820         }
1821
1822         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1823                 /* BL_AST locks are not needed in LRU.
1824                  * Let ldlm_cancel_lru() be fast. */
1825                 ldlm_lock_remove_from_lru(lock);
1826                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
1827                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1828         }
1829
1830         if (lock->l_lvb_len > 0) {
1831                 rc = ldlm_fill_lvb(lock, &req->rq_pill, RCL_CLIENT,
1832                                    lock->l_lvb_data, lvb_len);
1833                 if (rc < 0) {
1834                         unlock_res_and_lock(lock);
1835                         GOTO(out, rc);
1836                 }
1837         }
1838
1839         ldlm_grant_lock(lock, &ast_list);
1840         unlock_res_and_lock(lock);
1841
1842         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1843
1844         /* Let Enqueue to call osc_lock_upcall() and initialize
1845          * l_ast_data */
1846         OBD_FAIL_TIMEOUT(OBD_FAIL_OSC_CP_ENQ_RACE, 2);
1847
1848         ldlm_run_ast_work(ns, &ast_list, LDLM_WORK_CP_AST);
1849
1850         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1851                           lock);
1852         GOTO(out, rc);
1853
1854 out:
1855         if (rc < 0) {
1856                 lock_res_and_lock(lock);
1857                 lock->l_flags |= LDLM_FL_FAILED;
1858                 unlock_res_and_lock(lock);
1859                 cfs_waitq_signal(&lock->l_waitq);
1860         }
1861         LDLM_LOCK_RELEASE(lock);
1862 }
1863
1864 /**
1865  * Callback handler for receiving incoming glimpse ASTs.
1866  *
1867  * This only can happen on client side.  After handling the glimpse AST
1868  * we also consider dropping the lock here if it is unused locally for a
1869  * long time.
1870  */
1871 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1872                                     struct ldlm_namespace *ns,
1873                                     struct ldlm_request *dlm_req,
1874                                     struct ldlm_lock *lock)
1875 {
1876         int rc = -ENOSYS;
1877         ENTRY;
1878
1879         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1880
1881         if (lock->l_glimpse_ast != NULL)
1882                 rc = lock->l_glimpse_ast(lock, req);
1883
1884         if (req->rq_repmsg != NULL) {
1885                 ptlrpc_reply(req);
1886         } else {
1887                 req->rq_status = rc;
1888                 ptlrpc_error(req);
1889         }
1890
1891         lock_res_and_lock(lock);
1892         if (lock->l_granted_mode == LCK_PW &&
1893             !lock->l_readers && !lock->l_writers &&
1894             cfs_time_after(cfs_time_current(),
1895                            cfs_time_add(lock->l_last_used,
1896                                         cfs_time_seconds(10)))) {
1897                 unlock_res_and_lock(lock);
1898                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1899                         ldlm_handle_bl_callback(ns, NULL, lock);
1900
1901                 EXIT;
1902                 return;
1903         }
1904         unlock_res_and_lock(lock);
1905         LDLM_LOCK_RELEASE(lock);
1906         EXIT;
1907 }
1908
1909 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1910 {
1911         if (req->rq_no_reply)
1912                 return 0;
1913
1914         req->rq_status = rc;
1915         if (!req->rq_packed_final) {
1916                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1917                 if (rc)
1918                         return rc;
1919         }
1920         return ptlrpc_reply(req);
1921 }
1922
1923 #ifdef __KERNEL__
1924 static int __ldlm_bl_to_thread(struct ldlm_bl_work_item *blwi,
1925                                ldlm_cancel_flags_t cancel_flags)
1926 {
1927         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1928         ENTRY;
1929
1930         spin_lock(&blp->blp_lock);
1931         if (blwi->blwi_lock &&
1932             blwi->blwi_lock->l_flags & LDLM_FL_DISCARD_DATA) {
1933                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1934                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1935         } else {
1936                 /* other blocking callbacks are added to the regular list */
1937                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1938         }
1939         spin_unlock(&blp->blp_lock);
1940
1941         cfs_waitq_signal(&blp->blp_waitq);
1942
1943         /* can not check blwi->blwi_flags as blwi could be already freed in
1944            LCF_ASYNC mode */
1945         if (!(cancel_flags & LCF_ASYNC))
1946                 wait_for_completion(&blwi->blwi_comp);
1947
1948         RETURN(0);
1949 }
1950
1951 static inline void init_blwi(struct ldlm_bl_work_item *blwi,
1952                              struct ldlm_namespace *ns,
1953                              struct ldlm_lock_desc *ld,
1954                              cfs_list_t *cancels, int count,
1955                              struct ldlm_lock *lock,
1956                              ldlm_cancel_flags_t cancel_flags)
1957 {
1958         init_completion(&blwi->blwi_comp);
1959         CFS_INIT_LIST_HEAD(&blwi->blwi_head);
1960
1961         if (cfs_memory_pressure_get())
1962                 blwi->blwi_mem_pressure = 1;
1963
1964         blwi->blwi_ns = ns;
1965         blwi->blwi_flags = cancel_flags;
1966         if (ld != NULL)
1967                 blwi->blwi_ld = *ld;
1968         if (count) {
1969                 cfs_list_add(&blwi->blwi_head, cancels);
1970                 cfs_list_del_init(cancels);
1971                 blwi->blwi_count = count;
1972         } else {
1973                 blwi->blwi_lock = lock;
1974         }
1975 }
1976
1977 /**
1978  * Queues a list of locks \a cancels containing \a count locks
1979  * for later processing by a blocking thread.  If \a count is zero,
1980  * then the lock referenced as \a lock is queued instead.
1981  *
1982  * The blocking thread would then call ->l_blocking_ast callback in the lock.
1983  * If list addition fails an error is returned and caller is supposed to
1984  * call ->l_blocking_ast itself.
1985  */
1986 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1987                              struct ldlm_lock_desc *ld,
1988                              struct ldlm_lock *lock,
1989                              cfs_list_t *cancels, int count,
1990                              ldlm_cancel_flags_t cancel_flags)
1991 {
1992         ENTRY;
1993
1994         if (cancels && count == 0)
1995                 RETURN(0);
1996
1997         if (cancel_flags & LCF_ASYNC) {
1998                 struct ldlm_bl_work_item *blwi;
1999
2000                 OBD_ALLOC(blwi, sizeof(*blwi));
2001                 if (blwi == NULL)
2002                         RETURN(-ENOMEM);
2003                 init_blwi(blwi, ns, ld, cancels, count, lock, cancel_flags);
2004
2005                 RETURN(__ldlm_bl_to_thread(blwi, cancel_flags));
2006         } else {
2007                 /* if it is synchronous call do minimum mem alloc, as it could
2008                  * be triggered from kernel shrinker
2009                  */
2010                 struct ldlm_bl_work_item blwi;
2011
2012                 memset(&blwi, 0, sizeof(blwi));
2013                 init_blwi(&blwi, ns, ld, cancels, count, lock, cancel_flags);
2014                 RETURN(__ldlm_bl_to_thread(&blwi, cancel_flags));
2015         }
2016 }
2017
2018 #endif
2019
2020 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
2021                            struct ldlm_lock *lock)
2022 {
2023 #ifdef __KERNEL__
2024         return ldlm_bl_to_thread(ns, ld, lock, NULL, 0, LCF_ASYNC);
2025 #else
2026         return -ENOSYS;
2027 #endif
2028 }
2029
2030 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
2031                            cfs_list_t *cancels, int count,
2032                            ldlm_cancel_flags_t cancel_flags)
2033 {
2034 #ifdef __KERNEL__
2035         return ldlm_bl_to_thread(ns, ld, NULL, cancels, count, cancel_flags);
2036 #else
2037         return -ENOSYS;
2038 #endif
2039 }
2040
2041 /* Setinfo coming from Server (eg MDT) to Client (eg MDC)! */
2042 static int ldlm_handle_setinfo(struct ptlrpc_request *req)
2043 {
2044         struct obd_device *obd = req->rq_export->exp_obd;
2045         char *key;
2046         void *val;
2047         int keylen, vallen;
2048         int rc = -ENOSYS;
2049         ENTRY;
2050
2051         DEBUG_REQ(D_HSM, req, "%s: handle setinfo\n", obd->obd_name);
2052
2053         req_capsule_set(&req->rq_pill, &RQF_OBD_SET_INFO);
2054
2055         key = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_KEY);
2056         if (key == NULL) {
2057                 DEBUG_REQ(D_IOCTL, req, "no set_info key");
2058                 RETURN(-EFAULT);
2059         }
2060         keylen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_KEY,
2061                                       RCL_CLIENT);
2062         val = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_VAL);
2063         if (val == NULL) {
2064                 DEBUG_REQ(D_IOCTL, req, "no set_info val");
2065                 RETURN(-EFAULT);
2066         }
2067         vallen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_VAL,
2068                                       RCL_CLIENT);
2069
2070         /* We are responsible for swabbing contents of val */
2071
2072         if (KEY_IS(KEY_HSM_COPYTOOL_SEND))
2073                 /* Pass it on to mdc (the "export" in this case) */
2074                 rc = obd_set_info_async(req->rq_svc_thread->t_env,
2075                                         req->rq_export,
2076                                         sizeof(KEY_HSM_COPYTOOL_SEND),
2077                                         KEY_HSM_COPYTOOL_SEND,
2078                                         vallen, val, NULL);
2079         else
2080                 DEBUG_REQ(D_WARNING, req, "ignoring unknown key %s", key);
2081
2082         return rc;
2083 }
2084
2085 static inline void ldlm_callback_errmsg(struct ptlrpc_request *req,
2086                                         const char *msg, int rc,
2087                                         struct lustre_handle *handle)
2088 {
2089         DEBUG_REQ((req->rq_no_reply || rc) ? D_WARNING : D_DLMTRACE, req,
2090                   "%s: [nid %s] [rc %d] [lock "LPX64"]",
2091                   msg, libcfs_id2str(req->rq_peer), rc,
2092                   handle ? handle->cookie : 0);
2093         if (req->rq_no_reply)
2094                 CWARN("No reply was sent, maybe cause bug 21636.\n");
2095         else if (rc)
2096                 CWARN("Send reply failed, maybe cause bug 21636.\n");
2097 }
2098
2099 static int ldlm_handle_qc_callback(struct ptlrpc_request *req)
2100 {
2101         struct obd_quotactl *oqctl;
2102         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
2103
2104         oqctl = req_capsule_client_get(&req->rq_pill, &RMF_OBD_QUOTACTL);
2105         if (oqctl == NULL) {
2106                 CERROR("Can't unpack obd_quotactl\n");
2107                 RETURN(-EPROTO);
2108         }
2109
2110         cli->cl_qchk_stat = oqctl->qc_stat;
2111         return 0;
2112 }
2113
2114 /* TODO: handle requests in a similar way as MDT: see mdt_handle_common() */
2115 static int ldlm_callback_handler(struct ptlrpc_request *req)
2116 {
2117         struct ldlm_namespace *ns;
2118         struct ldlm_request *dlm_req;
2119         struct ldlm_lock *lock;
2120         int rc;
2121         ENTRY;
2122
2123         /* Requests arrive in sender's byte order.  The ptlrpc service
2124          * handler has already checked and, if necessary, byte-swapped the
2125          * incoming request message body, but I am responsible for the
2126          * message buffers. */
2127
2128         /* do nothing for sec context finalize */
2129         if (lustre_msg_get_opc(req->rq_reqmsg) == SEC_CTX_FINI)
2130                 RETURN(0);
2131
2132         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2133
2134         if (req->rq_export == NULL) {
2135                 rc = ldlm_callback_reply(req, -ENOTCONN);
2136                 ldlm_callback_errmsg(req, "Operate on unconnected server",
2137                                      rc, NULL);
2138                 RETURN(0);
2139         }
2140
2141         LASSERT(req->rq_export != NULL);
2142         LASSERT(req->rq_export->exp_obd != NULL);
2143
2144         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2145         case LDLM_BL_CALLBACK:
2146                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_BL_CALLBACK_NET))
2147                         RETURN(0);
2148                 break;
2149         case LDLM_CP_CALLBACK:
2150                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CP_CALLBACK_NET))
2151                         RETURN(0);
2152                 break;
2153         case LDLM_GL_CALLBACK:
2154                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_GL_CALLBACK_NET))
2155                         RETURN(0);
2156                 break;
2157         case LDLM_SET_INFO:
2158                 rc = ldlm_handle_setinfo(req);
2159                 ldlm_callback_reply(req, rc);
2160                 RETURN(0);
2161         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
2162                 CERROR("shouldn't be handling OBD_LOG_CANCEL on DLM thread\n");
2163                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
2164                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
2165                         RETURN(0);
2166                 rc = llog_origin_handle_cancel(req);
2167                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
2168                         RETURN(0);
2169                 ldlm_callback_reply(req, rc);
2170                 RETURN(0);
2171         case LLOG_ORIGIN_HANDLE_CREATE:
2172                 req_capsule_set(&req->rq_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
2173                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2174                         RETURN(0);
2175                 rc = llog_origin_handle_open(req);
2176                 ldlm_callback_reply(req, rc);
2177                 RETURN(0);
2178         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
2179                 req_capsule_set(&req->rq_pill,
2180                                 &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
2181                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2182                         RETURN(0);
2183                 rc = llog_origin_handle_next_block(req);
2184                 ldlm_callback_reply(req, rc);
2185                 RETURN(0);
2186         case LLOG_ORIGIN_HANDLE_READ_HEADER:
2187                 req_capsule_set(&req->rq_pill,
2188                                 &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
2189                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2190                         RETURN(0);
2191                 rc = llog_origin_handle_read_header(req);
2192                 ldlm_callback_reply(req, rc);
2193                 RETURN(0);
2194         case LLOG_ORIGIN_HANDLE_CLOSE:
2195                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2196                         RETURN(0);
2197                 rc = llog_origin_handle_close(req);
2198                 ldlm_callback_reply(req, rc);
2199                 RETURN(0);
2200         case OBD_QC_CALLBACK:
2201                 req_capsule_set(&req->rq_pill, &RQF_QC_CALLBACK);
2202                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_QC_CALLBACK_NET))
2203                         RETURN(0);
2204                 rc = ldlm_handle_qc_callback(req);
2205                 ldlm_callback_reply(req, rc);
2206                 RETURN(0);
2207         default:
2208                 CERROR("unknown opcode %u\n",
2209                        lustre_msg_get_opc(req->rq_reqmsg));
2210                 ldlm_callback_reply(req, -EPROTO);
2211                 RETURN(0);
2212         }
2213
2214         ns = req->rq_export->exp_obd->obd_namespace;
2215         LASSERT(ns != NULL);
2216
2217         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2218
2219         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2220         if (dlm_req == NULL) {
2221                 rc = ldlm_callback_reply(req, -EPROTO);
2222                 ldlm_callback_errmsg(req, "Operate without parameter", rc,
2223                                      NULL);
2224                 RETURN(0);
2225         }
2226
2227         /* Force a known safe race, send a cancel to the server for a lock
2228          * which the server has already started a blocking callback on. */
2229         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
2230             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
2231                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0], 0);
2232                 if (rc < 0)
2233                         CERROR("ldlm_cli_cancel: %d\n", rc);
2234         }
2235
2236         lock = ldlm_handle2lock_long(&dlm_req->lock_handle[0], 0);
2237         if (!lock) {
2238                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
2239                        "disappeared\n", dlm_req->lock_handle[0].cookie);
2240                 rc = ldlm_callback_reply(req, -EINVAL);
2241                 ldlm_callback_errmsg(req, "Operate with invalid parameter", rc,
2242                                      &dlm_req->lock_handle[0]);
2243                 RETURN(0);
2244         }
2245
2246         if ((lock->l_flags & LDLM_FL_FAIL_LOC) &&
2247             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK)
2248                 OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
2249
2250         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
2251         lock_res_and_lock(lock);
2252         lock->l_flags |= ldlm_flags_from_wire(dlm_req->lock_flags &
2253                                               LDLM_AST_FLAGS);
2254         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
2255                 /* If somebody cancels lock and cache is already dropped,
2256                  * or lock is failed before cp_ast received on client,
2257                  * we can tell the server we have no lock. Otherwise, we
2258                  * should send cancel after dropping the cache. */
2259                 if (((lock->l_flags & LDLM_FL_CANCELING) &&
2260                     (lock->l_flags & LDLM_FL_BL_DONE)) ||
2261                     (lock->l_flags & LDLM_FL_FAILED)) {
2262                         LDLM_DEBUG(lock, "callback on lock "
2263                                    LPX64" - lock disappeared\n",
2264                                    dlm_req->lock_handle[0].cookie);
2265                         unlock_res_and_lock(lock);
2266                         LDLM_LOCK_RELEASE(lock);
2267                         rc = ldlm_callback_reply(req, -EINVAL);
2268                         ldlm_callback_errmsg(req, "Operate on stale lock", rc,
2269                                              &dlm_req->lock_handle[0]);
2270                         RETURN(0);
2271                 }
2272                 /* BL_AST locks are not needed in LRU.
2273                  * Let ldlm_cancel_lru() be fast. */
2274                 ldlm_lock_remove_from_lru(lock);
2275                 lock->l_flags |= LDLM_FL_BL_AST;
2276         }
2277         unlock_res_and_lock(lock);
2278
2279         /* We want the ost thread to get this reply so that it can respond
2280          * to ost requests (write cache writeback) that might be triggered
2281          * in the callback.
2282          *
2283          * But we'd also like to be able to indicate in the reply that we're
2284          * cancelling right now, because it's unused, or have an intent result
2285          * in the reply, so we might have to push the responsibility for sending
2286          * the reply down into the AST handlers, alas. */
2287
2288         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2289         case LDLM_BL_CALLBACK:
2290                 CDEBUG(D_INODE, "blocking ast\n");
2291                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_BL_CALLBACK);
2292                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)) {
2293                         rc = ldlm_callback_reply(req, 0);
2294                         if (req->rq_no_reply || rc)
2295                                 ldlm_callback_errmsg(req, "Normal process", rc,
2296                                                      &dlm_req->lock_handle[0]);
2297                 }
2298                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
2299                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
2300                 break;
2301         case LDLM_CP_CALLBACK:
2302                 CDEBUG(D_INODE, "completion ast\n");
2303                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_CP_CALLBACK);
2304                 ldlm_callback_reply(req, 0);
2305                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
2306                 break;
2307         case LDLM_GL_CALLBACK:
2308                 CDEBUG(D_INODE, "glimpse ast\n");
2309                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_GL_CALLBACK);
2310                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
2311                 break;
2312         default:
2313                 LBUG();                         /* checked above */
2314         }
2315
2316         RETURN(0);
2317 }
2318
2319 #ifdef HAVE_SERVER_SUPPORT
2320 /**
2321  * Main handler for canceld thread.
2322  *
2323  * Separated into its own thread to avoid deadlocks.
2324  */
2325 static int ldlm_cancel_handler(struct ptlrpc_request *req)
2326 {
2327         int rc;
2328         ENTRY;
2329
2330         /* Requests arrive in sender's byte order.  The ptlrpc service
2331          * handler has already checked and, if necessary, byte-swapped the
2332          * incoming request message body, but I am responsible for the
2333          * message buffers. */
2334
2335         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2336
2337         if (req->rq_export == NULL) {
2338                 struct ldlm_request *dlm_req;
2339
2340                 CERROR("%s from %s arrived at %lu with bad export cookie "
2341                        LPU64"\n",
2342                        ll_opcode2str(lustre_msg_get_opc(req->rq_reqmsg)),
2343                        libcfs_nid2str(req->rq_peer.nid),
2344                        req->rq_arrival_time.tv_sec,
2345                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
2346
2347                 if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_CANCEL) {
2348                         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2349                         dlm_req = req_capsule_client_get(&req->rq_pill,
2350                                                          &RMF_DLM_REQ);
2351                         if (dlm_req != NULL)
2352                                 ldlm_lock_dump_handle(D_ERROR,
2353                                                       &dlm_req->lock_handle[0]);
2354                 }
2355                 ldlm_callback_reply(req, -ENOTCONN);
2356                 RETURN(0);
2357         }
2358
2359         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2360
2361         /* XXX FIXME move this back to mds/handler.c, bug 249 */
2362         case LDLM_CANCEL:
2363                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2364                 CDEBUG(D_INODE, "cancel\n");
2365                 if (CFS_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_NET) ||
2366                     CFS_FAIL_CHECK(OBD_FAIL_PTLRPC_CANCEL_RESEND))
2367                         RETURN(0);
2368                 rc = ldlm_handle_cancel(req);
2369                 if (rc)
2370                         break;
2371                 RETURN(0);
2372         case OBD_LOG_CANCEL:
2373                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
2374                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
2375                         RETURN(0);
2376                 rc = llog_origin_handle_cancel(req);
2377                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
2378                         RETURN(0);
2379                 ldlm_callback_reply(req, rc);
2380                 RETURN(0);
2381         default:
2382                 CERROR("invalid opcode %d\n",
2383                        lustre_msg_get_opc(req->rq_reqmsg));
2384                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2385                 ldlm_callback_reply(req, -EINVAL);
2386         }
2387
2388         RETURN(0);
2389 }
2390
2391 static int ldlm_cancel_hpreq_lock_match(struct ptlrpc_request *req,
2392                                         struct ldlm_lock *lock)
2393 {
2394         struct ldlm_request *dlm_req;
2395         struct lustre_handle lockh;
2396         int rc = 0;
2397         int i;
2398         ENTRY;
2399
2400         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2401         if (dlm_req == NULL)
2402                 RETURN(0);
2403
2404         ldlm_lock2handle(lock, &lockh);
2405         for (i = 0; i < dlm_req->lock_count; i++) {
2406                 if (lustre_handle_equal(&dlm_req->lock_handle[i],
2407                                         &lockh)) {
2408                         DEBUG_REQ(D_RPCTRACE, req,
2409                                   "Prio raised by lock "LPX64".", lockh.cookie);
2410
2411                         rc = 1;
2412                         break;
2413                 }
2414         }
2415
2416         RETURN(rc);
2417
2418 }
2419
2420 static int ldlm_cancel_hpreq_check(struct ptlrpc_request *req)
2421 {
2422         struct ldlm_request *dlm_req;
2423         int rc = 0;
2424         int i;
2425         ENTRY;
2426
2427         /* no prolong in recovery */
2428         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
2429                 RETURN(0);
2430
2431         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2432         if (dlm_req == NULL)
2433                 RETURN(-EFAULT);
2434
2435         for (i = 0; i < dlm_req->lock_count; i++) {
2436                 struct ldlm_lock *lock;
2437
2438                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
2439                 if (lock == NULL)
2440                         continue;
2441
2442                 rc = !!(lock->l_flags & LDLM_FL_AST_SENT);
2443                 if (rc)
2444                         LDLM_DEBUG(lock, "hpreq cancel lock");
2445                 LDLM_LOCK_PUT(lock);
2446
2447                 if (rc)
2448                         break;
2449         }
2450
2451         RETURN(rc);
2452 }
2453
2454 static struct ptlrpc_hpreq_ops ldlm_cancel_hpreq_ops = {
2455         .hpreq_lock_match = ldlm_cancel_hpreq_lock_match,
2456         .hpreq_check      = ldlm_cancel_hpreq_check,
2457         .hpreq_fini       = NULL,
2458 };
2459
2460 static int ldlm_hpreq_handler(struct ptlrpc_request *req)
2461 {
2462         ENTRY;
2463
2464         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2465
2466         if (req->rq_export == NULL)
2467                 RETURN(0);
2468
2469         if (LDLM_CANCEL == lustre_msg_get_opc(req->rq_reqmsg)) {
2470                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2471                 req->rq_ops = &ldlm_cancel_hpreq_ops;
2472         }
2473         RETURN(0);
2474 }
2475
2476 int ldlm_revoke_lock_cb(cfs_hash_t *hs, cfs_hash_bd_t *bd,
2477                         cfs_hlist_node_t *hnode, void *data)
2478
2479 {
2480         cfs_list_t         *rpc_list = data;
2481         struct ldlm_lock   *lock = cfs_hash_object(hs, hnode);
2482
2483         lock_res_and_lock(lock);
2484
2485         if (lock->l_req_mode != lock->l_granted_mode) {
2486                 unlock_res_and_lock(lock);
2487                 return 0;
2488         }
2489
2490         LASSERT(lock->l_resource);
2491         if (lock->l_resource->lr_type != LDLM_IBITS &&
2492             lock->l_resource->lr_type != LDLM_PLAIN) {
2493                 unlock_res_and_lock(lock);
2494                 return 0;
2495         }
2496
2497         if (lock->l_flags & LDLM_FL_AST_SENT) {
2498                 unlock_res_and_lock(lock);
2499                 return 0;
2500         }
2501
2502         LASSERT(lock->l_blocking_ast);
2503         LASSERT(!lock->l_blocking_lock);
2504
2505         lock->l_flags |= LDLM_FL_AST_SENT;
2506         if (lock->l_export && lock->l_export->exp_lock_hash) {
2507                 /* NB: it's safe to call cfs_hash_del() even lock isn't
2508                  * in exp_lock_hash. */
2509                 /* In the function below, .hs_keycmp resolves to
2510                  * ldlm_export_lock_keycmp() */
2511                 /* coverity[overrun-buffer-val] */
2512                 cfs_hash_del(lock->l_export->exp_lock_hash,
2513                              &lock->l_remote_handle, &lock->l_exp_hash);
2514         }
2515
2516         cfs_list_add_tail(&lock->l_rk_ast, rpc_list);
2517         LDLM_LOCK_GET(lock);
2518
2519         unlock_res_and_lock(lock);
2520         return 0;
2521 }
2522
2523 void ldlm_revoke_export_locks(struct obd_export *exp)
2524 {
2525         cfs_list_t  rpc_list;
2526         ENTRY;
2527
2528         CFS_INIT_LIST_HEAD(&rpc_list);
2529         cfs_hash_for_each_empty(exp->exp_lock_hash,
2530                                 ldlm_revoke_lock_cb, &rpc_list);
2531         ldlm_run_ast_work(exp->exp_obd->obd_namespace, &rpc_list,
2532                           LDLM_WORK_REVOKE_AST);
2533
2534         EXIT;
2535 }
2536 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2537 #endif /* HAVE_SERVER_SUPPORT */
2538
2539 #ifdef __KERNEL__
2540 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
2541 {
2542         struct ldlm_bl_work_item *blwi = NULL;
2543         static unsigned int num_bl = 0;
2544
2545         spin_lock(&blp->blp_lock);
2546         /* process a request from the blp_list at least every blp_num_threads */
2547         if (!cfs_list_empty(&blp->blp_list) &&
2548             (cfs_list_empty(&blp->blp_prio_list) || num_bl == 0))
2549                 blwi = cfs_list_entry(blp->blp_list.next,
2550                                       struct ldlm_bl_work_item, blwi_entry);
2551         else
2552                 if (!cfs_list_empty(&blp->blp_prio_list))
2553                         blwi = cfs_list_entry(blp->blp_prio_list.next,
2554                                               struct ldlm_bl_work_item,
2555                                               blwi_entry);
2556
2557         if (blwi) {
2558                 if (++num_bl >= cfs_atomic_read(&blp->blp_num_threads))
2559                         num_bl = 0;
2560                 cfs_list_del(&blwi->blwi_entry);
2561         }
2562         spin_unlock(&blp->blp_lock);
2563
2564         return blwi;
2565 }
2566
2567 /* This only contains temporary data until the thread starts */
2568 struct ldlm_bl_thread_data {
2569         char                    bltd_name[CFS_CURPROC_COMM_MAX];
2570         struct ldlm_bl_pool     *bltd_blp;
2571         struct completion       bltd_comp;
2572         int                     bltd_num;
2573 };
2574
2575 static int ldlm_bl_thread_main(void *arg);
2576
2577 static int ldlm_bl_thread_start(struct ldlm_bl_pool *blp)
2578 {
2579         struct ldlm_bl_thread_data bltd = { .bltd_blp = blp };
2580         int rc;
2581
2582         init_completion(&bltd.bltd_comp);
2583         rc = cfs_create_thread(ldlm_bl_thread_main, &bltd, 0);
2584         if (rc < 0) {
2585                 CERROR("cannot start LDLM thread ldlm_bl_%02d: rc %d\n",
2586                        cfs_atomic_read(&blp->blp_num_threads), rc);
2587                 return rc;
2588         }
2589         wait_for_completion(&bltd.bltd_comp);
2590
2591         return 0;
2592 }
2593
2594 /**
2595  * Main blocking requests processing thread.
2596  *
2597  * Callers put locks into its queue by calling ldlm_bl_to_thread.
2598  * This thread in the end ends up doing actual call to ->l_blocking_ast
2599  * for queued locks.
2600  */
2601 static int ldlm_bl_thread_main(void *arg)
2602 {
2603         struct ldlm_bl_pool *blp;
2604         ENTRY;
2605
2606         {
2607                 struct ldlm_bl_thread_data *bltd = arg;
2608
2609                 blp = bltd->bltd_blp;
2610
2611                 bltd->bltd_num =
2612                         cfs_atomic_inc_return(&blp->blp_num_threads) - 1;
2613                 cfs_atomic_inc(&blp->blp_busy_threads);
2614
2615                 snprintf(bltd->bltd_name, sizeof(bltd->bltd_name) - 1,
2616                         "ldlm_bl_%02d", bltd->bltd_num);
2617                 cfs_daemonize(bltd->bltd_name);
2618
2619                 complete(&bltd->bltd_comp);
2620                 /* cannot use bltd after this, it is only on caller's stack */
2621         }
2622
2623         while (1) {
2624                 struct l_wait_info lwi = { 0 };
2625                 struct ldlm_bl_work_item *blwi = NULL;
2626                 int busy;
2627
2628                 blwi = ldlm_bl_get_work(blp);
2629
2630                 if (blwi == NULL) {
2631                         cfs_atomic_dec(&blp->blp_busy_threads);
2632                         l_wait_event_exclusive(blp->blp_waitq,
2633                                          (blwi = ldlm_bl_get_work(blp)) != NULL,
2634                                          &lwi);
2635                         busy = cfs_atomic_inc_return(&blp->blp_busy_threads);
2636                 } else {
2637                         busy = cfs_atomic_read(&blp->blp_busy_threads);
2638                 }
2639
2640                 if (blwi->blwi_ns == NULL)
2641                         /* added by ldlm_cleanup() */
2642                         break;
2643
2644                 /* Not fatal if racy and have a few too many threads */
2645                 if (unlikely(busy < blp->blp_max_threads &&
2646                              busy >= cfs_atomic_read(&blp->blp_num_threads) &&
2647                              !blwi->blwi_mem_pressure))
2648                         /* discard the return value, we tried */
2649                         ldlm_bl_thread_start(blp);
2650
2651                 if (blwi->blwi_mem_pressure)
2652                         cfs_memory_pressure_set();
2653
2654                 if (blwi->blwi_count) {
2655                         int count;
2656                         /* The special case when we cancel locks in LRU
2657                          * asynchronously, we pass the list of locks here.
2658                          * Thus locks are marked LDLM_FL_CANCELING, but NOT
2659                          * canceled locally yet. */
2660                         count = ldlm_cli_cancel_list_local(&blwi->blwi_head,
2661                                                            blwi->blwi_count,
2662                                                            LCF_BL_AST);
2663                         ldlm_cli_cancel_list(&blwi->blwi_head, count, NULL,
2664                                              blwi->blwi_flags);
2665                 } else {
2666                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
2667                                                 blwi->blwi_lock);
2668                 }
2669                 if (blwi->blwi_mem_pressure)
2670                         cfs_memory_pressure_clr();
2671
2672                 if (blwi->blwi_flags & LCF_ASYNC)
2673                         OBD_FREE(blwi, sizeof(*blwi));
2674                 else
2675                         complete(&blwi->blwi_comp);
2676         }
2677
2678         cfs_atomic_dec(&blp->blp_busy_threads);
2679         cfs_atomic_dec(&blp->blp_num_threads);
2680         complete(&blp->blp_comp);
2681         RETURN(0);
2682 }
2683
2684 #endif
2685
2686 static int ldlm_setup(void);
2687 static int ldlm_cleanup(void);
2688
2689 int ldlm_get_ref(void)
2690 {
2691         int rc = 0;
2692         ENTRY;
2693         mutex_lock(&ldlm_ref_mutex);
2694         if (++ldlm_refcount == 1) {
2695                 rc = ldlm_setup();
2696                 if (rc)
2697                         ldlm_refcount--;
2698         }
2699         mutex_unlock(&ldlm_ref_mutex);
2700
2701         RETURN(rc);
2702 }
2703 EXPORT_SYMBOL(ldlm_get_ref);
2704
2705 void ldlm_put_ref(void)
2706 {
2707         ENTRY;
2708         mutex_lock(&ldlm_ref_mutex);
2709         if (ldlm_refcount == 1) {
2710                 int rc = ldlm_cleanup();
2711                 if (rc)
2712                         CERROR("ldlm_cleanup failed: %d\n", rc);
2713                 else
2714                         ldlm_refcount--;
2715         } else {
2716                 ldlm_refcount--;
2717         }
2718         mutex_unlock(&ldlm_ref_mutex);
2719
2720         EXIT;
2721 }
2722 EXPORT_SYMBOL(ldlm_put_ref);
2723
2724 /*
2725  * Export handle<->lock hash operations.
2726  */
2727 static unsigned
2728 ldlm_export_lock_hash(cfs_hash_t *hs, const void *key, unsigned mask)
2729 {
2730         return cfs_hash_u64_hash(((struct lustre_handle *)key)->cookie, mask);
2731 }
2732
2733 static void *
2734 ldlm_export_lock_key(cfs_hlist_node_t *hnode)
2735 {
2736         struct ldlm_lock *lock;
2737
2738         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2739         return &lock->l_remote_handle;
2740 }
2741
2742 static void
2743 ldlm_export_lock_keycpy(cfs_hlist_node_t *hnode, void *key)
2744 {
2745         struct ldlm_lock     *lock;
2746
2747         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2748         lock->l_remote_handle = *(struct lustre_handle *)key;
2749 }
2750
2751 static int
2752 ldlm_export_lock_keycmp(const void *key, cfs_hlist_node_t *hnode)
2753 {
2754         return lustre_handle_equal(ldlm_export_lock_key(hnode), key);
2755 }
2756
2757 static void *
2758 ldlm_export_lock_object(cfs_hlist_node_t *hnode)
2759 {
2760         return cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2761 }
2762
2763 static void
2764 ldlm_export_lock_get(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
2765 {
2766         struct ldlm_lock *lock;
2767
2768         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2769         LDLM_LOCK_GET(lock);
2770 }
2771
2772 static void
2773 ldlm_export_lock_put(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
2774 {
2775         struct ldlm_lock *lock;
2776
2777         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2778         LDLM_LOCK_RELEASE(lock);
2779 }
2780
2781 static cfs_hash_ops_t ldlm_export_lock_ops = {
2782         .hs_hash        = ldlm_export_lock_hash,
2783         .hs_key         = ldlm_export_lock_key,
2784         .hs_keycmp      = ldlm_export_lock_keycmp,
2785         .hs_keycpy      = ldlm_export_lock_keycpy,
2786         .hs_object      = ldlm_export_lock_object,
2787         .hs_get         = ldlm_export_lock_get,
2788         .hs_put         = ldlm_export_lock_put,
2789         .hs_put_locked  = ldlm_export_lock_put,
2790 };
2791
2792 int ldlm_init_export(struct obd_export *exp)
2793 {
2794         ENTRY;
2795
2796         exp->exp_lock_hash =
2797                 cfs_hash_create(obd_uuid2str(&exp->exp_client_uuid),
2798                                 HASH_EXP_LOCK_CUR_BITS,
2799                                 HASH_EXP_LOCK_MAX_BITS,
2800                                 HASH_EXP_LOCK_BKT_BITS, 0,
2801                                 CFS_HASH_MIN_THETA, CFS_HASH_MAX_THETA,
2802                                 &ldlm_export_lock_ops,
2803                                 CFS_HASH_DEFAULT | CFS_HASH_REHASH_KEY |
2804                                 CFS_HASH_NBLK_CHANGE);
2805
2806         if (!exp->exp_lock_hash)
2807                 RETURN(-ENOMEM);
2808
2809         RETURN(0);
2810 }
2811 EXPORT_SYMBOL(ldlm_init_export);
2812
2813 void ldlm_destroy_export(struct obd_export *exp)
2814 {
2815         ENTRY;
2816         cfs_hash_putref(exp->exp_lock_hash);
2817         exp->exp_lock_hash = NULL;
2818
2819         ldlm_destroy_flock_export(exp);
2820         EXIT;
2821 }
2822 EXPORT_SYMBOL(ldlm_destroy_export);
2823
2824 static int ldlm_setup(void)
2825 {
2826         static struct ptlrpc_service_conf       conf;
2827         struct ldlm_bl_pool                     *blp = NULL;
2828         int rc = 0;
2829 #ifdef __KERNEL__
2830         int i;
2831 #endif
2832         ENTRY;
2833
2834         if (ldlm_state != NULL)
2835                 RETURN(-EALREADY);
2836
2837         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
2838         if (ldlm_state == NULL)
2839                 RETURN(-ENOMEM);
2840
2841 #ifdef LPROCFS
2842         rc = ldlm_proc_setup();
2843         if (rc != 0)
2844                 GOTO(out, rc);
2845 #endif
2846
2847         memset(&conf, 0, sizeof(conf));
2848         conf = (typeof(conf)) {
2849                 .psc_name               = "ldlm_cbd",
2850                 .psc_watchdog_factor    = 2,
2851                 .psc_buf                = {
2852                         .bc_nbufs               = LDLM_CLIENT_NBUFS,
2853                         .bc_buf_size            = LDLM_BUFSIZE,
2854                         .bc_req_max_size        = LDLM_MAXREQSIZE,
2855                         .bc_rep_max_size        = LDLM_MAXREPSIZE,
2856                         .bc_req_portal          = LDLM_CB_REQUEST_PORTAL,
2857                         .bc_rep_portal          = LDLM_CB_REPLY_PORTAL,
2858                 },
2859                 .psc_thr                = {
2860                         .tc_thr_name            = "ldlm_cb",
2861                         .tc_thr_factor          = LDLM_THR_FACTOR,
2862                         .tc_nthrs_init          = LDLM_NTHRS_INIT,
2863                         .tc_nthrs_base          = LDLM_NTHRS_BASE,
2864                         .tc_nthrs_max           = LDLM_NTHRS_MAX,
2865                         .tc_nthrs_user          = ldlm_num_threads,
2866                         .tc_cpu_affinity        = 1,
2867                         .tc_ctx_tags            = LCT_MD_THREAD | LCT_DT_THREAD,
2868                 },
2869                 .psc_cpt                = {
2870                         .cc_pattern             = ldlm_cpts,
2871                 },
2872                 .psc_ops                = {
2873                         .so_req_handler         = ldlm_callback_handler,
2874                 },
2875         };
2876         ldlm_state->ldlm_cb_service = \
2877                         ptlrpc_register_service(&conf, ldlm_svc_proc_dir);
2878         if (IS_ERR(ldlm_state->ldlm_cb_service)) {
2879                 CERROR("failed to start service\n");
2880                 rc = PTR_ERR(ldlm_state->ldlm_cb_service);
2881                 ldlm_state->ldlm_cb_service = NULL;
2882                 GOTO(out, rc);
2883         }
2884
2885 #ifdef HAVE_SERVER_SUPPORT
2886         memset(&conf, 0, sizeof(conf));
2887         conf = (typeof(conf)) {
2888                 .psc_name               = "ldlm_canceld",
2889                 .psc_watchdog_factor    = 6,
2890                 .psc_buf                = {
2891                         .bc_nbufs               = LDLM_SERVER_NBUFS,
2892                         .bc_buf_size            = LDLM_BUFSIZE,
2893                         .bc_req_max_size        = LDLM_MAXREQSIZE,
2894                         .bc_rep_max_size        = LDLM_MAXREPSIZE,
2895                         .bc_req_portal          = LDLM_CANCEL_REQUEST_PORTAL,
2896                         .bc_rep_portal          = LDLM_CANCEL_REPLY_PORTAL,
2897
2898                 },
2899                 .psc_thr                = {
2900                         .tc_thr_name            = "ldlm_cn",
2901                         .tc_thr_factor          = LDLM_THR_FACTOR,
2902                         .tc_nthrs_init          = LDLM_NTHRS_INIT,
2903                         .tc_nthrs_base          = LDLM_NTHRS_BASE,
2904                         .tc_nthrs_max           = LDLM_NTHRS_MAX,
2905                         .tc_nthrs_user          = ldlm_num_threads,
2906                         .tc_cpu_affinity        = 1,
2907                         .tc_ctx_tags            = LCT_MD_THREAD | \
2908                                                   LCT_DT_THREAD | \
2909                                                   LCT_CL_THREAD,
2910                 },
2911                 .psc_cpt                = {
2912                         .cc_pattern             = ldlm_cpts,
2913                 },
2914                 .psc_ops                = {
2915                         .so_req_handler         = ldlm_cancel_handler,
2916                         .so_hpreq_handler       = ldlm_hpreq_handler,
2917                 },
2918         };
2919         ldlm_state->ldlm_cancel_service = \
2920                         ptlrpc_register_service(&conf, ldlm_svc_proc_dir);
2921         if (IS_ERR(ldlm_state->ldlm_cancel_service)) {
2922                 CERROR("failed to start service\n");
2923                 rc = PTR_ERR(ldlm_state->ldlm_cancel_service);
2924                 ldlm_state->ldlm_cancel_service = NULL;
2925                 GOTO(out, rc);
2926         }
2927 #endif
2928
2929         OBD_ALLOC(blp, sizeof(*blp));
2930         if (blp == NULL)
2931                 GOTO(out, rc = -ENOMEM);
2932         ldlm_state->ldlm_bl_pool = blp;
2933
2934         spin_lock_init(&blp->blp_lock);
2935         CFS_INIT_LIST_HEAD(&blp->blp_list);
2936         CFS_INIT_LIST_HEAD(&blp->blp_prio_list);
2937         cfs_waitq_init(&blp->blp_waitq);
2938         cfs_atomic_set(&blp->blp_num_threads, 0);
2939         cfs_atomic_set(&blp->blp_busy_threads, 0);
2940
2941 #ifdef __KERNEL__
2942         if (ldlm_num_threads == 0) {
2943                 blp->blp_min_threads = LDLM_NTHRS_INIT;
2944                 blp->blp_max_threads = LDLM_NTHRS_MAX;
2945         } else {
2946                 blp->blp_min_threads = blp->blp_max_threads = \
2947                         min_t(int, LDLM_NTHRS_MAX, max_t(int, LDLM_NTHRS_INIT,
2948                                                          ldlm_num_threads));
2949         }
2950
2951         for (i = 0; i < blp->blp_min_threads; i++) {
2952                 rc = ldlm_bl_thread_start(blp);
2953                 if (rc < 0)
2954                         GOTO(out, rc);
2955         }
2956
2957 # ifdef HAVE_SERVER_SUPPORT
2958         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
2959         expired_lock_thread.elt_state = ELT_STOPPED;
2960         cfs_waitq_init(&expired_lock_thread.elt_waitq);
2961
2962         CFS_INIT_LIST_HEAD(&waiting_locks_list);
2963         spin_lock_init(&waiting_locks_spinlock);
2964         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
2965
2966         rc = cfs_create_thread(expired_lock_main, NULL, CFS_DAEMON_FLAGS);
2967         if (rc < 0) {
2968                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
2969                 GOTO(out, rc);
2970         }
2971
2972         cfs_wait_event(expired_lock_thread.elt_waitq,
2973                        expired_lock_thread.elt_state == ELT_READY);
2974 # endif /* HAVE_SERVER_SUPPORT */
2975
2976         rc = ldlm_pools_init();
2977         if (rc) {
2978                 CERROR("Failed to initialize LDLM pools: %d\n", rc);
2979                 GOTO(out, rc);
2980         }
2981 #endif
2982         RETURN(0);
2983
2984  out:
2985         ldlm_cleanup();
2986         RETURN(rc);
2987 }
2988
2989 static int ldlm_cleanup(void)
2990 {
2991         ENTRY;
2992
2993         if (!cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) ||
2994             !cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
2995                 CERROR("ldlm still has namespaces; clean these up first.\n");
2996                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
2997                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
2998                 RETURN(-EBUSY);
2999         }
3000
3001 #ifdef __KERNEL__
3002         ldlm_pools_fini();
3003
3004         if (ldlm_state->ldlm_bl_pool != NULL) {
3005                 struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
3006
3007                 while (cfs_atomic_read(&blp->blp_num_threads) > 0) {
3008                         struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
3009
3010                         init_completion(&blp->blp_comp);
3011
3012                         spin_lock(&blp->blp_lock);
3013                         cfs_list_add_tail(&blwi.blwi_entry, &blp->blp_list);
3014                         cfs_waitq_signal(&blp->blp_waitq);
3015                         spin_unlock(&blp->blp_lock);
3016
3017                         wait_for_completion(&blp->blp_comp);
3018                 }
3019
3020                 OBD_FREE(blp, sizeof(*blp));
3021         }
3022 #endif /* __KERNEL__ */
3023
3024         if (ldlm_state->ldlm_cb_service != NULL)
3025                 ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
3026 # ifdef HAVE_SERVER_SUPPORT
3027         if (ldlm_state->ldlm_cancel_service != NULL)
3028                 ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
3029 # endif
3030
3031 #ifdef __KERNEL__
3032         ldlm_proc_cleanup();
3033
3034 # ifdef HAVE_SERVER_SUPPORT
3035         if (expired_lock_thread.elt_state != ELT_STOPPED) {
3036                 expired_lock_thread.elt_state = ELT_TERMINATE;
3037                 cfs_waitq_signal(&expired_lock_thread.elt_waitq);
3038                 cfs_wait_event(expired_lock_thread.elt_waitq,
3039                                expired_lock_thread.elt_state == ELT_STOPPED);
3040         }
3041 # endif
3042 #endif /* __KERNEL__ */
3043
3044         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
3045         ldlm_state = NULL;
3046
3047         RETURN(0);
3048 }
3049
3050 int ldlm_init(void)
3051 {
3052         mutex_init(&ldlm_ref_mutex);
3053         mutex_init(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
3054         mutex_init(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
3055         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
3056                                                sizeof(struct ldlm_resource), 0,
3057                                                CFS_SLAB_HWCACHE_ALIGN);
3058         if (ldlm_resource_slab == NULL)
3059                 return -ENOMEM;
3060
3061         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
3062                               sizeof(struct ldlm_lock), 0,
3063                               CFS_SLAB_HWCACHE_ALIGN | SLAB_DESTROY_BY_RCU);
3064         if (ldlm_lock_slab == NULL) {
3065                 cfs_mem_cache_destroy(ldlm_resource_slab);
3066                 return -ENOMEM;
3067         }
3068
3069         ldlm_interval_slab = cfs_mem_cache_create("interval_node",
3070                                         sizeof(struct ldlm_interval),
3071                                         0, CFS_SLAB_HWCACHE_ALIGN);
3072         if (ldlm_interval_slab == NULL) {
3073                 cfs_mem_cache_destroy(ldlm_resource_slab);
3074                 cfs_mem_cache_destroy(ldlm_lock_slab);
3075                 return -ENOMEM;
3076         }
3077 #if LUSTRE_TRACKS_LOCK_EXP_REFS
3078         class_export_dump_hook = ldlm_dump_export_locks;
3079 #endif
3080         return 0;
3081 }
3082
3083 void ldlm_exit(void)
3084 {
3085         int rc;
3086         if (ldlm_refcount)
3087                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
3088         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
3089         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
3090 #ifdef __KERNEL__
3091         /* ldlm_lock_put() use RCU to call ldlm_lock_free, so need call
3092          * synchronize_rcu() to wait a grace period elapsed, so that
3093          * ldlm_lock_free() get a chance to be called. */
3094         synchronize_rcu();
3095 #endif
3096         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
3097         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
3098         rc = cfs_mem_cache_destroy(ldlm_interval_slab);
3099         LASSERTF(rc == 0, "couldn't free interval node slab\n");
3100 }