Whamcloud - gitweb
5517ed504126a2b018548c3e523d8883bd861ad9
[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         int                     blwi_mode;
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 */
814                 if (!req->rq_hp && !cfs_list_empty(&req->rq_list) &&
815                     req->rq_ops->hpreq_lock_match &&
816                     req->rq_ops->hpreq_lock_match(req, lock))
817                         ptlrpc_hpreq_reorder(req);
818         }
819         spin_unlock_bh(&lock->l_export->exp_rpc_lock);
820         EXIT;
821 }
822
823 /**
824  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
825  * enqueued server lock conflicts with given one.
826  *
827  * Sends blocking AST RPC to the client owning that lock; arms timeout timer
828  * to wait for client response.
829  */
830 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
831                              struct ldlm_lock_desc *desc,
832                              void *data, int flag)
833 {
834         struct ldlm_cb_async_args *ca;
835         struct ldlm_cb_set_arg *arg = data;
836         struct ldlm_request    *body;
837         struct ptlrpc_request  *req;
838         int                     instant_cancel = 0;
839         int                     rc = 0;
840         ENTRY;
841
842         if (flag == LDLM_CB_CANCELING)
843                 /* Don't need to do anything here. */
844                 RETURN(0);
845
846         LASSERT(lock);
847         LASSERT(data != NULL);
848         if (lock->l_export->exp_obd->obd_recovering != 0)
849                 LDLM_ERROR(lock, "BUG 6063: lock collide during recovery");
850
851         ldlm_lock_reorder_req(lock);
852
853         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
854                                         &RQF_LDLM_BL_CALLBACK,
855                                         LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK);
856         if (req == NULL)
857                 RETURN(-ENOMEM);
858
859         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
860         ca = ptlrpc_req_async_args(req);
861         ca->ca_set_arg = arg;
862         ca->ca_lock = lock;
863
864         req->rq_interpret_reply = ldlm_cb_interpret;
865         req->rq_no_resend = 1;
866
867         lock_res_and_lock(lock);
868         if (lock->l_granted_mode != lock->l_req_mode) {
869                 /* this blocking AST will be communicated as part of the
870                  * completion AST instead */
871                 unlock_res_and_lock(lock);
872
873                 ptlrpc_req_finished(req);
874                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
875                 RETURN(0);
876         }
877
878         if (lock->l_destroyed) {
879                 /* What's the point? */
880                 unlock_res_and_lock(lock);
881                 ptlrpc_req_finished(req);
882                 RETURN(0);
883         }
884
885         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
886                 instant_cancel = 1;
887
888         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
889         body->lock_handle[0] = lock->l_remote_handle;
890         body->lock_desc = *desc;
891         body->lock_flags |= ldlm_flags_to_wire(lock->l_flags & LDLM_AST_FLAGS);
892
893         LDLM_DEBUG(lock, "server preparing blocking AST");
894
895         ptlrpc_request_set_replen(req);
896         if (instant_cancel) {
897                 unlock_res_and_lock(lock);
898                 ldlm_lock_cancel(lock);
899         } else {
900                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
901                 ldlm_add_waiting_lock(lock);
902                 unlock_res_and_lock(lock);
903         }
904
905         req->rq_send_state = LUSTRE_IMP_FULL;
906         /* ptlrpc_request_alloc_pack already set timeout */
907         if (AT_OFF)
908                 req->rq_timeout = ldlm_get_rq_timeout();
909
910         if (lock->l_export && lock->l_export->exp_nid_stats &&
911             lock->l_export->exp_nid_stats->nid_ldlm_stats)
912                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
913                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
914
915         rc = ldlm_ast_fini(req, arg, lock, instant_cancel);
916
917         RETURN(rc);
918 }
919 EXPORT_SYMBOL(ldlm_server_blocking_ast);
920
921 /**
922  * ->l_completion_ast callback for a remote lock in server namespace.
923  *
924  *  Sends AST to the client notifying it of lock granting.  If initial
925  *  lock response was not sent yet, instead of sending another RPC, just
926  *  mark the lock as granted and client will understand
927  */
928 int ldlm_server_completion_ast(struct ldlm_lock *lock, __u64 flags, void *data)
929 {
930         struct ldlm_cb_set_arg *arg = data;
931         struct ldlm_request    *body;
932         struct ptlrpc_request  *req;
933         struct ldlm_cb_async_args *ca;
934         long                    total_enqueue_wait;
935         int                     instant_cancel = 0;
936         int                     rc = 0;
937         int                     lvb_len;
938         ENTRY;
939
940         LASSERT(lock != NULL);
941         LASSERT(data != NULL);
942
943         total_enqueue_wait = cfs_time_sub(cfs_time_current_sec(),
944                                           lock->l_last_activity);
945
946         req = ptlrpc_request_alloc(lock->l_export->exp_imp_reverse,
947                                     &RQF_LDLM_CP_CALLBACK);
948         if (req == NULL)
949                 RETURN(-ENOMEM);
950
951         /* server namespace, doesn't need lock */
952         lvb_len = ldlm_lvbo_size(lock);
953         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT, lvb_len);
954         rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK);
955         if (rc) {
956                 ptlrpc_request_free(req);
957                 RETURN(rc);
958         }
959
960         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
961         ca = ptlrpc_req_async_args(req);
962         ca->ca_set_arg = arg;
963         ca->ca_lock = lock;
964
965         req->rq_interpret_reply = ldlm_cb_interpret;
966         req->rq_no_resend = 1;
967         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
968
969         body->lock_handle[0] = lock->l_remote_handle;
970         body->lock_flags = ldlm_flags_to_wire(flags);
971         ldlm_lock2desc(lock, &body->lock_desc);
972         if (lvb_len > 0) {
973                 void *lvb = req_capsule_client_get(&req->rq_pill, &RMF_DLM_LVB);
974
975                 lvb_len = ldlm_lvbo_fill(lock, lvb, lvb_len);
976                 req_capsule_shrink(&req->rq_pill, &RMF_DLM_LVB,
977                                    lvb_len, RCL_CLIENT);
978         }
979
980         LDLM_DEBUG(lock, "server preparing completion AST (after %lds wait)",
981                    total_enqueue_wait);
982
983         /* Server-side enqueue wait time estimate, used in
984             __ldlm_add_waiting_lock to set future enqueue timers */
985         if (total_enqueue_wait < ldlm_get_enq_timeout(lock))
986                 at_measured(ldlm_lock_to_ns_at(lock),
987                             total_enqueue_wait);
988         else
989                 /* bz18618. Don't add lock enqueue time we spend waiting for a
990                    previous callback to fail. Locks waiting legitimately will
991                    get extended by ldlm_refresh_waiting_lock regardless of the
992                    estimate, so it's okay to underestimate here. */
993                 LDLM_DEBUG(lock, "lock completed after %lus; estimate was %ds. "
994                        "It is likely that a previous callback timed out.",
995                        total_enqueue_wait,
996                        at_get(ldlm_lock_to_ns_at(lock)));
997
998         ptlrpc_request_set_replen(req);
999
1000         req->rq_send_state = LUSTRE_IMP_FULL;
1001         /* ptlrpc_request_pack already set timeout */
1002         if (AT_OFF)
1003                 req->rq_timeout = ldlm_get_rq_timeout();
1004
1005         /* We only send real blocking ASTs after the lock is granted */
1006         lock_res_and_lock(lock);
1007         if (lock->l_flags & LDLM_FL_AST_SENT) {
1008                 body->lock_flags |= ldlm_flags_to_wire(LDLM_FL_AST_SENT);
1009                 /* Copy AST flags like LDLM_FL_DISCARD_DATA. */
1010                 body->lock_flags |= ldlm_flags_to_wire(lock->l_flags &
1011                                                        LDLM_AST_FLAGS);
1012
1013                 /* We might get here prior to ldlm_handle_enqueue setting
1014                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
1015                  * into waiting list, but this is safe and similar code in
1016                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
1017                  * that would not only cancel the lock, but will also remove
1018                  * it from waiting list */
1019                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1020                         unlock_res_and_lock(lock);
1021                         ldlm_lock_cancel(lock);
1022                         instant_cancel = 1;
1023                         lock_res_and_lock(lock);
1024                 } else {
1025                         /* start the lock-timeout clock */
1026                         ldlm_add_waiting_lock(lock);
1027                 }
1028         }
1029         unlock_res_and_lock(lock);
1030
1031         if (lock->l_export && lock->l_export->exp_nid_stats &&
1032             lock->l_export->exp_nid_stats->nid_ldlm_stats)
1033                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
1034                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
1035
1036         rc = ldlm_ast_fini(req, arg, lock, instant_cancel);
1037
1038         RETURN(rc);
1039 }
1040 EXPORT_SYMBOL(ldlm_server_completion_ast);
1041
1042 /**
1043  * Server side ->l_glimpse_ast handler for client locks.
1044  *
1045  * Sends glimpse AST to the client and waits for reply. Then updates
1046  * lvbo with the result.
1047  */
1048 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
1049 {
1050         struct ldlm_cb_set_arg          *arg = data;
1051         struct ldlm_request             *body;
1052         struct ptlrpc_request           *req;
1053         struct ldlm_cb_async_args       *ca;
1054         int                              rc;
1055         struct req_format               *req_fmt;
1056         ENTRY;
1057
1058         LASSERT(lock != NULL);
1059
1060         if (arg->gl_desc != NULL)
1061                 /* There is a glimpse descriptor to pack */
1062                 req_fmt = &RQF_LDLM_GL_DESC_CALLBACK;
1063         else
1064                 req_fmt = &RQF_LDLM_GL_CALLBACK;
1065
1066         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
1067                                         req_fmt, LUSTRE_DLM_VERSION,
1068                                         LDLM_GL_CALLBACK);
1069
1070         if (req == NULL)
1071                 RETURN(-ENOMEM);
1072
1073         if (arg->gl_desc != NULL) {
1074                 /* copy the GL descriptor */
1075                 union ldlm_gl_desc      *desc;
1076                 desc = req_capsule_client_get(&req->rq_pill, &RMF_DLM_GL_DESC);
1077                 *desc = *arg->gl_desc;
1078         }
1079
1080         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1081         body->lock_handle[0] = lock->l_remote_handle;
1082         ldlm_lock2desc(lock, &body->lock_desc);
1083
1084         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
1085         ca = ptlrpc_req_async_args(req);
1086         ca->ca_set_arg = arg;
1087         ca->ca_lock = lock;
1088
1089         /* server namespace, doesn't need lock */
1090         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
1091                              ldlm_lvbo_size(lock));
1092         ptlrpc_request_set_replen(req);
1093
1094         req->rq_send_state = LUSTRE_IMP_FULL;
1095         /* ptlrpc_request_alloc_pack already set timeout */
1096         if (AT_OFF)
1097                 req->rq_timeout = ldlm_get_rq_timeout();
1098
1099         req->rq_interpret_reply = ldlm_cb_interpret;
1100
1101         if (lock->l_export && lock->l_export->exp_nid_stats &&
1102             lock->l_export->exp_nid_stats->nid_ldlm_stats)
1103                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
1104                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
1105
1106         rc = ldlm_ast_fini(req, arg, lock, 0);
1107
1108         RETURN(rc);
1109 }
1110 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
1111
1112 int ldlm_glimpse_locks(struct ldlm_resource *res, cfs_list_t *gl_work_list)
1113 {
1114         int     rc;
1115         ENTRY;
1116
1117         rc = ldlm_run_ast_work(ldlm_res_to_ns(res), gl_work_list,
1118                                LDLM_WORK_GL_AST);
1119         if (rc == -ERESTART)
1120                 ldlm_reprocess_all(res);
1121
1122         RETURN(rc);
1123 }
1124 EXPORT_SYMBOL(ldlm_glimpse_locks);
1125
1126 /* return LDLM lock associated with a lock callback request */
1127 struct ldlm_lock *ldlm_request_lock(struct ptlrpc_request *req)
1128 {
1129         struct ldlm_cb_async_args       *ca;
1130         struct ldlm_lock                *lock;
1131         ENTRY;
1132
1133         ca = ptlrpc_req_async_args(req);
1134         lock = ca->ca_lock;
1135         if (lock == NULL)
1136                 RETURN(ERR_PTR(-EFAULT));
1137
1138         RETURN(lock);
1139 }
1140 EXPORT_SYMBOL(ldlm_request_lock);
1141
1142 static void ldlm_svc_get_eopc(const struct ldlm_request *dlm_req,
1143                        struct lprocfs_stats *srv_stats)
1144 {
1145         int lock_type = 0, op = 0;
1146
1147         lock_type = dlm_req->lock_desc.l_resource.lr_type;
1148
1149         switch (lock_type) {
1150         case LDLM_PLAIN:
1151                 op = PTLRPC_LAST_CNTR + LDLM_PLAIN_ENQUEUE;
1152                 break;
1153         case LDLM_EXTENT:
1154                 if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT)
1155                         op = PTLRPC_LAST_CNTR + LDLM_GLIMPSE_ENQUEUE;
1156                 else
1157                         op = PTLRPC_LAST_CNTR + LDLM_EXTENT_ENQUEUE;
1158                 break;
1159         case LDLM_FLOCK:
1160                 op = PTLRPC_LAST_CNTR + LDLM_FLOCK_ENQUEUE;
1161                 break;
1162         case LDLM_IBITS:
1163                 op = PTLRPC_LAST_CNTR + LDLM_IBITS_ENQUEUE;
1164                 break;
1165         default:
1166                 op = 0;
1167                 break;
1168         }
1169
1170         if (op)
1171                 lprocfs_counter_incr(srv_stats, op);
1172
1173         return;
1174 }
1175
1176 /**
1177  * Main server-side entry point into LDLM for enqueue. This is called by ptlrpc
1178  * service threads to carry out client lock enqueueing requests.
1179  */
1180 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
1181                          struct ptlrpc_request *req,
1182                          const struct ldlm_request *dlm_req,
1183                          const struct ldlm_callback_suite *cbs)
1184 {
1185         struct ldlm_reply *dlm_rep;
1186         __u64 flags;
1187         ldlm_error_t err = ELDLM_OK;
1188         struct ldlm_lock *lock = NULL;
1189         void *cookie = NULL;
1190         int rc = 0;
1191         ENTRY;
1192
1193         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
1194
1195         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
1196         flags = ldlm_flags_from_wire(dlm_req->lock_flags);
1197
1198         LASSERT(req->rq_export);
1199
1200         if (ptlrpc_req2svc(req)->srv_stats != NULL)
1201                 ldlm_svc_get_eopc(dlm_req, ptlrpc_req2svc(req)->srv_stats);
1202
1203         if (req->rq_export && req->rq_export->exp_nid_stats &&
1204             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1205                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1206                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
1207
1208         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
1209                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
1210                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
1211                           dlm_req->lock_desc.l_resource.lr_type);
1212                 GOTO(out, rc = -EFAULT);
1213         }
1214
1215         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
1216                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
1217                      dlm_req->lock_desc.l_req_mode &
1218                      (dlm_req->lock_desc.l_req_mode-1))) {
1219                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
1220                           dlm_req->lock_desc.l_req_mode);
1221                 GOTO(out, rc = -EFAULT);
1222         }
1223
1224         if (req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) {
1225                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1226                              LDLM_PLAIN)) {
1227                         DEBUG_REQ(D_ERROR, req,
1228                                   "PLAIN lock request from IBITS client?");
1229                         GOTO(out, rc = -EPROTO);
1230                 }
1231         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1232                             LDLM_IBITS)) {
1233                 DEBUG_REQ(D_ERROR, req,
1234                           "IBITS lock request from unaware client?");
1235                 GOTO(out, rc = -EPROTO);
1236         }
1237
1238 #if 0
1239         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
1240            against server's _CONNECT_SUPPORTED flags? (I don't want to use
1241            ibits for mgc/mgs) */
1242
1243         /* INODEBITS_INTEROP: Perform conversion from plain lock to
1244          * inodebits lock if client does not support them. */
1245         if (!(req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) &&
1246             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
1247                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
1248                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
1249                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
1250                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
1251                         dlm_req->lock_desc.l_req_mode = LCK_CR;
1252         }
1253 #endif
1254
1255         if (unlikely(flags & LDLM_FL_REPLAY)) {
1256                 /* Find an existing lock in the per-export lock hash */
1257                 /* In the function below, .hs_keycmp resolves to
1258                  * ldlm_export_lock_keycmp() */
1259                 /* coverity[overrun-buffer-val] */
1260                 lock = cfs_hash_lookup(req->rq_export->exp_lock_hash,
1261                                        (void *)&dlm_req->lock_handle[0]);
1262                 if (lock != NULL) {
1263                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
1264                                   LPX64, lock->l_handle.h_cookie);
1265                         GOTO(existing_lock, rc = 0);
1266                 }
1267         }
1268
1269         /* The lock's callback data might be set in the policy function */
1270         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
1271                                 dlm_req->lock_desc.l_resource.lr_type,
1272                                 dlm_req->lock_desc.l_req_mode,
1273                                 cbs, NULL, 0, LVB_T_NONE);
1274         if (!lock)
1275                 GOTO(out, rc = -ENOMEM);
1276
1277         lock->l_last_activity = cfs_time_current_sec();
1278         lock->l_remote_handle = dlm_req->lock_handle[0];
1279         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
1280
1281         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
1282         /* Don't enqueue a lock onto the export if it is been disonnected
1283          * due to eviction (bug 3822) or server umount (bug 24324).
1284          * Cancel it now instead. */
1285         if (req->rq_export->exp_disconnected) {
1286                 LDLM_ERROR(lock, "lock on disconnected export %p",
1287                            req->rq_export);
1288                 GOTO(out, rc = -ENOTCONN);
1289         }
1290
1291         lock->l_export = class_export_lock_get(req->rq_export, lock);
1292         if (lock->l_export->exp_lock_hash)
1293                 cfs_hash_add(lock->l_export->exp_lock_hash,
1294                              &lock->l_remote_handle,
1295                              &lock->l_exp_hash);
1296
1297 existing_lock:
1298
1299         if (flags & LDLM_FL_HAS_INTENT) {
1300                 /* In this case, the reply buffer is allocated deep in
1301                  * local_lock_enqueue by the policy function. */
1302                 cookie = req;
1303         } else {
1304                 /* based on the assumption that lvb size never changes during
1305                  * resource life time otherwise it need resource->lr_lock's
1306                  * protection */
1307                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
1308                                      RCL_SERVER, ldlm_lvbo_size(lock));
1309
1310                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
1311                         GOTO(out, rc = -ENOMEM);
1312
1313                 rc = req_capsule_server_pack(&req->rq_pill);
1314                 if (rc)
1315                         GOTO(out, rc);
1316         }
1317
1318         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
1319                 ldlm_convert_policy_to_local(req->rq_export,
1320                                           dlm_req->lock_desc.l_resource.lr_type,
1321                                           &dlm_req->lock_desc.l_policy_data,
1322                                           &lock->l_policy_data);
1323         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
1324                 lock->l_req_extent = lock->l_policy_data.l_extent;
1325
1326         err = ldlm_lock_enqueue(ns, &lock, cookie, &flags);
1327         if (err)
1328                 GOTO(out, err);
1329
1330         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1331         dlm_rep->lock_flags = ldlm_flags_to_wire(flags);
1332
1333         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
1334         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
1335
1336         /* We never send a blocking AST until the lock is granted, but
1337          * we can tell it right now */
1338         lock_res_and_lock(lock);
1339
1340         /* Now take into account flags to be inherited from original lock
1341            request both in reply to client and in our own lock flags. */
1342         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1343         lock->l_flags |= ldlm_flags_from_wire(dlm_req->lock_flags &
1344                                               LDLM_INHERIT_FLAGS);
1345
1346         /* Don't move a pending lock onto the export if it has already been
1347          * disconnected due to eviction (bug 5683) or server umount (bug 24324).
1348          * Cancel it now instead. */
1349         if (unlikely(req->rq_export->exp_disconnected ||
1350                      OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
1351                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1352                 rc = -ENOTCONN;
1353         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
1354                 dlm_rep->lock_flags |= ldlm_flags_to_wire(LDLM_FL_AST_SENT);
1355                 if (lock->l_granted_mode == lock->l_req_mode) {
1356                         /*
1357                          * Only cancel lock if it was granted, because it would
1358                          * be destroyed immediately and would never be granted
1359                          * in the future, causing timeouts on client.  Not
1360                          * granted lock will be cancelled immediately after
1361                          * sending completion AST.
1362                          */
1363                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1364                                 unlock_res_and_lock(lock);
1365                                 ldlm_lock_cancel(lock);
1366                                 lock_res_and_lock(lock);
1367                         } else
1368                                 ldlm_add_waiting_lock(lock);
1369                 }
1370         }
1371         /* Make sure we never ever grant usual metadata locks to liblustre
1372            clients */
1373         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1374             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1375              req->rq_export->exp_libclient) {
1376                 if (unlikely(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
1377                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
1378                         CERROR("Granting sync lock to libclient. "
1379                                "req fl %d, rep fl %d, lock fl "LPX64"\n",
1380                                dlm_req->lock_flags, dlm_rep->lock_flags,
1381                                lock->l_flags);
1382                         LDLM_ERROR(lock, "sync lock");
1383                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1384                                 struct ldlm_intent *it;
1385
1386                                 it = req_capsule_client_get(&req->rq_pill,
1387                                                             &RMF_LDLM_INTENT);
1388                                 if (it != NULL) {
1389                                         CERROR("This is intent %s ("LPU64")\n",
1390                                                ldlm_it2str(it->opc), it->opc);
1391                                 }
1392                         }
1393                 }
1394         }
1395
1396         unlock_res_and_lock(lock);
1397
1398         EXIT;
1399  out:
1400         req->rq_status = rc ?: err; /* return either error - bug 11190 */
1401         if (!req->rq_packed_final) {
1402                 err = lustre_pack_reply(req, 1, NULL, NULL);
1403                 if (rc == 0)
1404                         rc = err;
1405         }
1406
1407         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1408          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1409         if (lock) {
1410                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1411                            "(err=%d, rc=%d)", err, rc);
1412
1413                 if (rc == 0) {
1414                         int lvb_len = ldlm_lvbo_size(lock);
1415
1416                         if (lvb_len > 0) {
1417                                 void *buf;
1418                                 int buflen;
1419
1420                                 buf = req_capsule_server_get(&req->rq_pill,
1421                                                              &RMF_DLM_LVB);
1422                                 LASSERTF(buf != NULL, "req %p, lock %p\n",
1423                                          req, lock);
1424                                 buflen = req_capsule_get_size(&req->rq_pill,
1425                                                 &RMF_DLM_LVB, RCL_SERVER);
1426                                 buflen = ldlm_lvbo_fill(lock, buf, buflen);
1427                                 req_capsule_shrink(&req->rq_pill, &RMF_DLM_LVB,
1428                                                    buflen, RCL_SERVER);
1429                         }
1430                 } else {
1431                         lock_res_and_lock(lock);
1432                         ldlm_resource_unlink_lock(lock);
1433                         ldlm_lock_destroy_nolock(lock);
1434                         unlock_res_and_lock(lock);
1435                 }
1436
1437                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1438                         ldlm_reprocess_all(lock->l_resource);
1439
1440                 LDLM_LOCK_RELEASE(lock);
1441         }
1442
1443         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1444                           lock, rc);
1445
1446         return rc;
1447 }
1448 EXPORT_SYMBOL(ldlm_handle_enqueue0);
1449
1450 /**
1451  * Old-style LDLM main entry point for server code enqueue.
1452  */
1453 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1454                         ldlm_completion_callback completion_callback,
1455                         ldlm_blocking_callback blocking_callback,
1456                         ldlm_glimpse_callback glimpse_callback)
1457 {
1458         struct ldlm_request *dlm_req;
1459         struct ldlm_callback_suite cbs = {
1460                 .lcs_completion = completion_callback,
1461                 .lcs_blocking   = blocking_callback,
1462                 .lcs_glimpse    = glimpse_callback
1463         };
1464         int rc;
1465
1466         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1467         if (dlm_req != NULL) {
1468                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1469                                           req, dlm_req, &cbs);
1470         } else {
1471                 rc = -EFAULT;
1472         }
1473         return rc;
1474 }
1475 EXPORT_SYMBOL(ldlm_handle_enqueue);
1476
1477 /**
1478  * Main LDLM entry point for server code to process lock conversion requests.
1479  */
1480 int ldlm_handle_convert0(struct ptlrpc_request *req,
1481                          const struct ldlm_request *dlm_req)
1482 {
1483         struct ldlm_reply *dlm_rep;
1484         struct ldlm_lock *lock;
1485         int rc;
1486         ENTRY;
1487
1488         if (req->rq_export && req->rq_export->exp_nid_stats &&
1489             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1490                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1491                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1492
1493         rc = req_capsule_server_pack(&req->rq_pill);
1494         if (rc)
1495                 RETURN(rc);
1496
1497         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1498         dlm_rep->lock_flags = dlm_req->lock_flags;
1499
1500         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1501         if (!lock) {
1502                 req->rq_status = EINVAL;
1503         } else {
1504                 void *res = NULL;
1505
1506                 LDLM_DEBUG(lock, "server-side convert handler START");
1507
1508                 lock->l_last_activity = cfs_time_current_sec();
1509                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1510                                         &dlm_rep->lock_flags);
1511                 if (res) {
1512                         if (ldlm_del_waiting_lock(lock))
1513                                 LDLM_DEBUG(lock, "converted waiting lock");
1514                         req->rq_status = 0;
1515                 } else {
1516                         req->rq_status = EDEADLOCK;
1517                 }
1518         }
1519
1520         if (lock) {
1521                 if (!req->rq_status)
1522                         ldlm_reprocess_all(lock->l_resource);
1523                 LDLM_DEBUG(lock, "server-side convert handler END");
1524                 LDLM_LOCK_PUT(lock);
1525         } else
1526                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1527
1528         RETURN(0);
1529 }
1530 EXPORT_SYMBOL(ldlm_handle_convert0);
1531
1532 /**
1533  * Old-style main LDLM entry point for server code to process lock conversion
1534  * requests.
1535  */
1536 int ldlm_handle_convert(struct ptlrpc_request *req)
1537 {
1538         int rc;
1539         struct ldlm_request *dlm_req;
1540
1541         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1542         if (dlm_req != NULL) {
1543                 rc = ldlm_handle_convert0(req, dlm_req);
1544         } else {
1545                 CERROR ("Can't unpack dlm_req\n");
1546                 rc = -EFAULT;
1547         }
1548         return rc;
1549 }
1550 EXPORT_SYMBOL(ldlm_handle_convert);
1551
1552 /**
1553  * Cancel all the locks whose handles are packed into ldlm_request
1554  *
1555  * Called by server code expecting such combined cancel activity
1556  * requests.
1557  */
1558 int ldlm_request_cancel(struct ptlrpc_request *req,
1559                         const struct ldlm_request *dlm_req, int first)
1560 {
1561         struct ldlm_resource *res, *pres = NULL;
1562         struct ldlm_lock *lock;
1563         int i, count, done = 0;
1564         ENTRY;
1565
1566         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1567         if (first >= count)
1568                 RETURN(0);
1569
1570         if (count == 1 && dlm_req->lock_handle[0].cookie == 0)
1571                 RETURN(0);
1572
1573         /* There is no lock on the server at the replay time,
1574          * skip lock cancelling to make replay tests to pass. */
1575         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1576                 RETURN(0);
1577
1578         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1579                           "starting at %d", count, first);
1580
1581         for (i = first; i < count; i++) {
1582                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1583                 if (!lock) {
1584                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1585                                           "lock (cookie "LPU64")",
1586                                           dlm_req->lock_handle[i].cookie);
1587                         continue;
1588                 }
1589
1590                 res = lock->l_resource;
1591                 done++;
1592
1593                 /* This code is an optimization to only attempt lock
1594                  * granting on the resource (that could be CPU-expensive)
1595                  * after we are done cancelling lock in that resource. */
1596                 if (res != pres) {
1597                         if (pres != NULL) {
1598                                 ldlm_reprocess_all(pres);
1599                                 LDLM_RESOURCE_DELREF(pres);
1600                                 ldlm_resource_putref(pres);
1601                         }
1602                         if (res != NULL) {
1603                                 ldlm_resource_getref(res);
1604                                 LDLM_RESOURCE_ADDREF(res);
1605                                 ldlm_res_lvbo_update(res, NULL, 1);
1606                         }
1607                         pres = res;
1608                 }
1609                 ldlm_lock_cancel(lock);
1610                 LDLM_LOCK_PUT(lock);
1611         }
1612         if (pres != NULL) {
1613                 ldlm_reprocess_all(pres);
1614                 LDLM_RESOURCE_DELREF(pres);
1615                 ldlm_resource_putref(pres);
1616         }
1617         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1618         RETURN(done);
1619 }
1620 EXPORT_SYMBOL(ldlm_request_cancel);
1621
1622 /**
1623  * Main LDLM entry point for server code to cancel locks.
1624  *
1625  * Typically gets called from service handler on LDLM_CANCEL opc.
1626  */
1627 int ldlm_handle_cancel(struct ptlrpc_request *req)
1628 {
1629         struct ldlm_request *dlm_req;
1630         int rc;
1631         ENTRY;
1632
1633         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1634         if (dlm_req == NULL) {
1635                 CDEBUG(D_INFO, "bad request buffer for cancel\n");
1636                 RETURN(-EFAULT);
1637         }
1638
1639         if (req->rq_export && req->rq_export->exp_nid_stats &&
1640             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1641                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1642                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1643
1644         rc = req_capsule_server_pack(&req->rq_pill);
1645         if (rc)
1646                 RETURN(rc);
1647
1648         if (!ldlm_request_cancel(req, dlm_req, 0))
1649                 req->rq_status = ESTALE;
1650
1651         RETURN(ptlrpc_reply(req));
1652 }
1653 EXPORT_SYMBOL(ldlm_handle_cancel);
1654 #endif /* HAVE_SERVER_SUPPORT */
1655
1656 /**
1657  * Callback handler for receiving incoming blocking ASTs.
1658  *
1659  * This can only happen on client side.
1660  */
1661 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1662                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1663 {
1664         int do_ast;
1665         ENTRY;
1666
1667         LDLM_DEBUG(lock, "client blocking AST callback handler");
1668
1669         lock_res_and_lock(lock);
1670         lock->l_flags |= LDLM_FL_CBPENDING;
1671
1672         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1673                 lock->l_flags |= LDLM_FL_CANCEL;
1674
1675         do_ast = (!lock->l_readers && !lock->l_writers);
1676         unlock_res_and_lock(lock);
1677
1678         if (do_ast) {
1679                 CDEBUG(D_DLMTRACE, "Lock %p already unused, calling callback (%p)\n",
1680                        lock, lock->l_blocking_ast);
1681                 if (lock->l_blocking_ast != NULL)
1682                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1683                                              LDLM_CB_BLOCKING);
1684         } else {
1685                 CDEBUG(D_DLMTRACE, "Lock %p is referenced, will be cancelled later\n",
1686                        lock);
1687         }
1688
1689         LDLM_DEBUG(lock, "client blocking callback handler END");
1690         LDLM_LOCK_RELEASE(lock);
1691         EXIT;
1692 }
1693
1694 /**
1695  * Callback handler for receiving incoming completion ASTs.
1696  *
1697  * This only can happen on client side.
1698  */
1699 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1700                                     struct ldlm_namespace *ns,
1701                                     struct ldlm_request *dlm_req,
1702                                     struct ldlm_lock *lock)
1703 {
1704         int lvb_len;
1705         CFS_LIST_HEAD(ast_list);
1706         int rc = 0;
1707         ENTRY;
1708
1709         LDLM_DEBUG(lock, "client completion callback handler START");
1710
1711         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE)) {
1712                 int to = cfs_time_seconds(1);
1713                 while (to > 0) {
1714                         cfs_schedule_timeout_and_set_state(
1715                                 CFS_TASK_INTERRUPTIBLE, to);
1716                         if (lock->l_granted_mode == lock->l_req_mode ||
1717                             lock->l_destroyed)
1718                                 break;
1719                 }
1720         }
1721
1722         lvb_len = req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT);
1723         if (lvb_len < 0) {
1724                 LDLM_ERROR(lock, "Fail to get lvb_len, rc = %d", lvb_len);
1725                 GOTO(out, rc = lvb_len);
1726         } else if (lvb_len > 0) {
1727                 if (lock->l_lvb_len > 0) {
1728                         /* for extent lock, lvb contains ost_lvb{}. */
1729                         LASSERT(lock->l_lvb_data != NULL);
1730
1731                         if (unlikely(lock->l_lvb_len < lvb_len)) {
1732                                 LDLM_ERROR(lock, "Replied LVB is larger than "
1733                                            "expectation, expected = %d, "
1734                                            "replied = %d",
1735                                            lock->l_lvb_len, lvb_len);
1736                                 GOTO(out, rc = -EINVAL);
1737                         }
1738                 } else { /* for layout lock, lvb has variable length */
1739                         void *lvb_data;
1740
1741                         OBD_ALLOC(lvb_data, lvb_len);
1742                         if (lvb_data == NULL) {
1743                                 LDLM_ERROR(lock, "No memory.\n");
1744                                 GOTO(out, rc = -ENOMEM);
1745                         }
1746
1747                         lock_res_and_lock(lock);
1748                         LASSERT(lock->l_lvb_data == NULL);
1749                         lock->l_lvb_data = lvb_data;
1750                         lock->l_lvb_len = lvb_len;
1751                         unlock_res_and_lock(lock);
1752                 }
1753         }
1754
1755         lock_res_and_lock(lock);
1756         if (lock->l_destroyed ||
1757             lock->l_granted_mode == lock->l_req_mode) {
1758                 /* bug 11300: the lock has already been granted */
1759                 unlock_res_and_lock(lock);
1760                 LDLM_DEBUG(lock, "Double grant race happened");
1761                 GOTO(out, rc = 0);
1762         }
1763
1764         /* If we receive the completion AST before the actual enqueue returned,
1765          * then we might need to switch lock modes, resources, or extents. */
1766         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1767                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1768                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1769         }
1770
1771         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1772                 ldlm_convert_policy_to_local(req->rq_export,
1773                                           dlm_req->lock_desc.l_resource.lr_type,
1774                                           &dlm_req->lock_desc.l_policy_data,
1775                                           &lock->l_policy_data);
1776                 LDLM_DEBUG(lock, "completion AST, new policy data");
1777         }
1778
1779         ldlm_resource_unlink_lock(lock);
1780         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1781                    &lock->l_resource->lr_name,
1782                    sizeof(lock->l_resource->lr_name)) != 0) {
1783                 unlock_res_and_lock(lock);
1784                 rc = ldlm_lock_change_resource(ns, lock,
1785                                 &dlm_req->lock_desc.l_resource.lr_name);
1786                 if (rc < 0) {
1787                         LDLM_ERROR(lock, "Failed to allocate resource");
1788                         GOTO(out, rc);
1789                 }
1790                 LDLM_DEBUG(lock, "completion AST, new resource");
1791                 CERROR("change resource!\n");
1792                 lock_res_and_lock(lock);
1793         }
1794
1795         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1796                 /* BL_AST locks are not needed in LRU.
1797                  * Let ldlm_cancel_lru() be fast. */
1798                 ldlm_lock_remove_from_lru(lock);
1799                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
1800                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1801         }
1802
1803         if (lock->l_lvb_len > 0) {
1804                 rc = ldlm_fill_lvb(lock, &req->rq_pill, RCL_CLIENT,
1805                                    lock->l_lvb_data, lvb_len);
1806                 if (rc < 0) {
1807                         unlock_res_and_lock(lock);
1808                         GOTO(out, rc);
1809                 }
1810         }
1811
1812         ldlm_grant_lock(lock, &ast_list);
1813         unlock_res_and_lock(lock);
1814
1815         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1816
1817         /* Let Enqueue to call osc_lock_upcall() and initialize
1818          * l_ast_data */
1819         OBD_FAIL_TIMEOUT(OBD_FAIL_OSC_CP_ENQ_RACE, 2);
1820
1821         ldlm_run_ast_work(ns, &ast_list, LDLM_WORK_CP_AST);
1822
1823         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1824                           lock);
1825         GOTO(out, rc);
1826
1827 out:
1828         if (rc < 0) {
1829                 lock_res_and_lock(lock);
1830                 lock->l_flags |= LDLM_FL_FAILED;
1831                 unlock_res_and_lock(lock);
1832         }
1833         LDLM_LOCK_RELEASE(lock);
1834 }
1835
1836 /**
1837  * Callback handler for receiving incoming glimpse ASTs.
1838  *
1839  * This only can happen on client side.  After handling the glimpse AST
1840  * we also consider dropping the lock here if it is unused locally for a
1841  * long time.
1842  */
1843 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1844                                     struct ldlm_namespace *ns,
1845                                     struct ldlm_request *dlm_req,
1846                                     struct ldlm_lock *lock)
1847 {
1848         int rc = -ENOSYS;
1849         ENTRY;
1850
1851         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1852
1853         if (lock->l_glimpse_ast != NULL)
1854                 rc = lock->l_glimpse_ast(lock, req);
1855
1856         if (req->rq_repmsg != NULL) {
1857                 ptlrpc_reply(req);
1858         } else {
1859                 req->rq_status = rc;
1860                 ptlrpc_error(req);
1861         }
1862
1863         lock_res_and_lock(lock);
1864         if (lock->l_granted_mode == LCK_PW &&
1865             !lock->l_readers && !lock->l_writers &&
1866             cfs_time_after(cfs_time_current(),
1867                            cfs_time_add(lock->l_last_used,
1868                                         cfs_time_seconds(10)))) {
1869                 unlock_res_and_lock(lock);
1870                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1871                         ldlm_handle_bl_callback(ns, NULL, lock);
1872
1873                 EXIT;
1874                 return;
1875         }
1876         unlock_res_and_lock(lock);
1877         LDLM_LOCK_RELEASE(lock);
1878         EXIT;
1879 }
1880
1881 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1882 {
1883         if (req->rq_no_reply)
1884                 return 0;
1885
1886         req->rq_status = rc;
1887         if (!req->rq_packed_final) {
1888                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1889                 if (rc)
1890                         return rc;
1891         }
1892         return ptlrpc_reply(req);
1893 }
1894
1895 #ifdef __KERNEL__
1896 static int __ldlm_bl_to_thread(struct ldlm_bl_work_item *blwi, int mode)
1897 {
1898         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1899         ENTRY;
1900
1901         spin_lock(&blp->blp_lock);
1902         if (blwi->blwi_lock &&
1903             blwi->blwi_lock->l_flags & LDLM_FL_DISCARD_DATA) {
1904                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1905                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1906         } else {
1907                 /* other blocking callbacks are added to the regular list */
1908                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1909         }
1910         spin_unlock(&blp->blp_lock);
1911
1912         cfs_waitq_signal(&blp->blp_waitq);
1913
1914         /* can not use blwi->blwi_mode as blwi could be already freed in
1915            LDLM_ASYNC mode */
1916         if (mode == LDLM_SYNC)
1917                 wait_for_completion(&blwi->blwi_comp);
1918
1919         RETURN(0);
1920 }
1921
1922 static inline void init_blwi(struct ldlm_bl_work_item *blwi,
1923                              struct ldlm_namespace *ns,
1924                              struct ldlm_lock_desc *ld,
1925                              cfs_list_t *cancels, int count,
1926                              struct ldlm_lock *lock,
1927                              int mode)
1928 {
1929         init_completion(&blwi->blwi_comp);
1930         CFS_INIT_LIST_HEAD(&blwi->blwi_head);
1931
1932         if (cfs_memory_pressure_get())
1933                 blwi->blwi_mem_pressure = 1;
1934
1935         blwi->blwi_ns = ns;
1936         blwi->blwi_mode = mode;
1937         if (ld != NULL)
1938                 blwi->blwi_ld = *ld;
1939         if (count) {
1940                 cfs_list_add(&blwi->blwi_head, cancels);
1941                 cfs_list_del_init(cancels);
1942                 blwi->blwi_count = count;
1943         } else {
1944                 blwi->blwi_lock = lock;
1945         }
1946 }
1947
1948 /**
1949  * Queues a list of locks \a cancels containing \a count locks
1950  * for later processing by a blocking thread.  If \a count is zero,
1951  * then the lock referenced as \a lock is queued instead.
1952  *
1953  * The blocking thread would then call ->l_blocking_ast callback in the lock.
1954  * If list addition fails an error is returned and caller is supposed to
1955  * call ->l_blocking_ast itself.
1956  */
1957 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1958                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1959                              cfs_list_t *cancels, int count, int mode)
1960 {
1961         ENTRY;
1962
1963         if (cancels && count == 0)
1964                 RETURN(0);
1965
1966         if (mode == LDLM_SYNC) {
1967                 /* if it is synchronous call do minimum mem alloc, as it could
1968                  * be triggered from kernel shrinker
1969                  */
1970                 struct ldlm_bl_work_item blwi;
1971                 memset(&blwi, 0, sizeof(blwi));
1972                 init_blwi(&blwi, ns, ld, cancels, count, lock, LDLM_SYNC);
1973                 RETURN(__ldlm_bl_to_thread(&blwi, LDLM_SYNC));
1974         } else {
1975                 struct ldlm_bl_work_item *blwi;
1976                 OBD_ALLOC(blwi, sizeof(*blwi));
1977                 if (blwi == NULL)
1978                         RETURN(-ENOMEM);
1979                 init_blwi(blwi, ns, ld, cancels, count, lock, LDLM_ASYNC);
1980
1981                 RETURN(__ldlm_bl_to_thread(blwi, LDLM_ASYNC));
1982         }
1983 }
1984
1985 #endif
1986
1987 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1988                            struct ldlm_lock *lock)
1989 {
1990 #ifdef __KERNEL__
1991         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0, LDLM_ASYNC));
1992 #else
1993         RETURN(-ENOSYS);
1994 #endif
1995 }
1996
1997 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1998                            cfs_list_t *cancels, int count, int mode)
1999 {
2000 #ifdef __KERNEL__
2001         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count, mode));
2002 #else
2003         RETURN(-ENOSYS);
2004 #endif
2005 }
2006
2007 /* Setinfo coming from Server (eg MDT) to Client (eg MDC)! */
2008 static int ldlm_handle_setinfo(struct ptlrpc_request *req)
2009 {
2010         struct obd_device *obd = req->rq_export->exp_obd;
2011         char *key;
2012         void *val;
2013         int keylen, vallen;
2014         int rc = -ENOSYS;
2015         ENTRY;
2016
2017         DEBUG_REQ(D_HSM, req, "%s: handle setinfo\n", obd->obd_name);
2018
2019         req_capsule_set(&req->rq_pill, &RQF_OBD_SET_INFO);
2020
2021         key = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_KEY);
2022         if (key == NULL) {
2023                 DEBUG_REQ(D_IOCTL, req, "no set_info key");
2024                 RETURN(-EFAULT);
2025         }
2026         keylen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_KEY,
2027                                       RCL_CLIENT);
2028         val = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_VAL);
2029         if (val == NULL) {
2030                 DEBUG_REQ(D_IOCTL, req, "no set_info val");
2031                 RETURN(-EFAULT);
2032         }
2033         vallen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_VAL,
2034                                       RCL_CLIENT);
2035
2036         /* We are responsible for swabbing contents of val */
2037
2038         if (KEY_IS(KEY_HSM_COPYTOOL_SEND))
2039                 /* Pass it on to mdc (the "export" in this case) */
2040                 rc = obd_set_info_async(req->rq_svc_thread->t_env,
2041                                         req->rq_export,
2042                                         sizeof(KEY_HSM_COPYTOOL_SEND),
2043                                         KEY_HSM_COPYTOOL_SEND,
2044                                         vallen, val, NULL);
2045         else
2046                 DEBUG_REQ(D_WARNING, req, "ignoring unknown key %s", key);
2047
2048         return rc;
2049 }
2050
2051 static inline void ldlm_callback_errmsg(struct ptlrpc_request *req,
2052                                         const char *msg, int rc,
2053                                         struct lustre_handle *handle)
2054 {
2055         DEBUG_REQ((req->rq_no_reply || rc) ? D_WARNING : D_DLMTRACE, req,
2056                   "%s: [nid %s] [rc %d] [lock "LPX64"]",
2057                   msg, libcfs_id2str(req->rq_peer), rc,
2058                   handle ? handle->cookie : 0);
2059         if (req->rq_no_reply)
2060                 CWARN("No reply was sent, maybe cause bug 21636.\n");
2061         else if (rc)
2062                 CWARN("Send reply failed, maybe cause bug 21636.\n");
2063 }
2064
2065 static int ldlm_handle_qc_callback(struct ptlrpc_request *req)
2066 {
2067         struct obd_quotactl *oqctl;
2068         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
2069
2070         oqctl = req_capsule_client_get(&req->rq_pill, &RMF_OBD_QUOTACTL);
2071         if (oqctl == NULL) {
2072                 CERROR("Can't unpack obd_quotactl\n");
2073                 RETURN(-EPROTO);
2074         }
2075
2076         cli->cl_qchk_stat = oqctl->qc_stat;
2077         return 0;
2078 }
2079
2080 /* TODO: handle requests in a similar way as MDT: see mdt_handle_common() */
2081 static int ldlm_callback_handler(struct ptlrpc_request *req)
2082 {
2083         struct ldlm_namespace *ns;
2084         struct ldlm_request *dlm_req;
2085         struct ldlm_lock *lock;
2086         int rc;
2087         ENTRY;
2088
2089         /* Requests arrive in sender's byte order.  The ptlrpc service
2090          * handler has already checked and, if necessary, byte-swapped the
2091          * incoming request message body, but I am responsible for the
2092          * message buffers. */
2093
2094         /* do nothing for sec context finalize */
2095         if (lustre_msg_get_opc(req->rq_reqmsg) == SEC_CTX_FINI)
2096                 RETURN(0);
2097
2098         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2099
2100         if (req->rq_export == NULL) {
2101                 rc = ldlm_callback_reply(req, -ENOTCONN);
2102                 ldlm_callback_errmsg(req, "Operate on unconnected server",
2103                                      rc, NULL);
2104                 RETURN(0);
2105         }
2106
2107         LASSERT(req->rq_export != NULL);
2108         LASSERT(req->rq_export->exp_obd != NULL);
2109
2110         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2111         case LDLM_BL_CALLBACK:
2112                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_BL_CALLBACK_NET))
2113                         RETURN(0);
2114                 break;
2115         case LDLM_CP_CALLBACK:
2116                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CP_CALLBACK_NET))
2117                         RETURN(0);
2118                 break;
2119         case LDLM_GL_CALLBACK:
2120                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_GL_CALLBACK_NET))
2121                         RETURN(0);
2122                 break;
2123         case LDLM_SET_INFO:
2124                 rc = ldlm_handle_setinfo(req);
2125                 ldlm_callback_reply(req, rc);
2126                 RETURN(0);
2127         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
2128                 CERROR("shouldn't be handling OBD_LOG_CANCEL on DLM thread\n");
2129                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
2130                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
2131                         RETURN(0);
2132                 rc = llog_origin_handle_cancel(req);
2133                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
2134                         RETURN(0);
2135                 ldlm_callback_reply(req, rc);
2136                 RETURN(0);
2137         case LLOG_ORIGIN_HANDLE_CREATE:
2138                 req_capsule_set(&req->rq_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
2139                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2140                         RETURN(0);
2141                 rc = llog_origin_handle_open(req);
2142                 ldlm_callback_reply(req, rc);
2143                 RETURN(0);
2144         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
2145                 req_capsule_set(&req->rq_pill,
2146                                 &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
2147                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2148                         RETURN(0);
2149                 rc = llog_origin_handle_next_block(req);
2150                 ldlm_callback_reply(req, rc);
2151                 RETURN(0);
2152         case LLOG_ORIGIN_HANDLE_READ_HEADER:
2153                 req_capsule_set(&req->rq_pill,
2154                                 &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
2155                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2156                         RETURN(0);
2157                 rc = llog_origin_handle_read_header(req);
2158                 ldlm_callback_reply(req, rc);
2159                 RETURN(0);
2160         case LLOG_ORIGIN_HANDLE_CLOSE:
2161                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2162                         RETURN(0);
2163                 rc = llog_origin_handle_close(req);
2164                 ldlm_callback_reply(req, rc);
2165                 RETURN(0);
2166         case OBD_QC_CALLBACK:
2167                 req_capsule_set(&req->rq_pill, &RQF_QC_CALLBACK);
2168                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_QC_CALLBACK_NET))
2169                         RETURN(0);
2170                 rc = ldlm_handle_qc_callback(req);
2171                 ldlm_callback_reply(req, rc);
2172                 RETURN(0);
2173         default:
2174                 CERROR("unknown opcode %u\n",
2175                        lustre_msg_get_opc(req->rq_reqmsg));
2176                 ldlm_callback_reply(req, -EPROTO);
2177                 RETURN(0);
2178         }
2179
2180         ns = req->rq_export->exp_obd->obd_namespace;
2181         LASSERT(ns != NULL);
2182
2183         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2184
2185         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2186         if (dlm_req == NULL) {
2187                 rc = ldlm_callback_reply(req, -EPROTO);
2188                 ldlm_callback_errmsg(req, "Operate without parameter", rc,
2189                                      NULL);
2190                 RETURN(0);
2191         }
2192
2193         /* Force a known safe race, send a cancel to the server for a lock
2194          * which the server has already started a blocking callback on. */
2195         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
2196             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
2197                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0]);
2198                 if (rc < 0)
2199                         CERROR("ldlm_cli_cancel: %d\n", rc);
2200         }
2201
2202         lock = ldlm_handle2lock_long(&dlm_req->lock_handle[0], 0);
2203         if (!lock) {
2204                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
2205                        "disappeared\n", dlm_req->lock_handle[0].cookie);
2206                 rc = ldlm_callback_reply(req, -EINVAL);
2207                 ldlm_callback_errmsg(req, "Operate with invalid parameter", rc,
2208                                      &dlm_req->lock_handle[0]);
2209                 RETURN(0);
2210         }
2211
2212         if ((lock->l_flags & LDLM_FL_FAIL_LOC) &&
2213             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK)
2214                 OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
2215
2216         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
2217         lock_res_and_lock(lock);
2218         lock->l_flags |= ldlm_flags_from_wire(dlm_req->lock_flags &
2219                                               LDLM_AST_FLAGS);
2220         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
2221                 /* If somebody cancels lock and cache is already dropped,
2222                  * or lock is failed before cp_ast received on client,
2223                  * we can tell the server we have no lock. Otherwise, we
2224                  * should send cancel after dropping the cache. */
2225                 if (((lock->l_flags & LDLM_FL_CANCELING) &&
2226                     (lock->l_flags & LDLM_FL_BL_DONE)) ||
2227                     (lock->l_flags & LDLM_FL_FAILED)) {
2228                         LDLM_DEBUG(lock, "callback on lock "
2229                                    LPX64" - lock disappeared\n",
2230                                    dlm_req->lock_handle[0].cookie);
2231                         unlock_res_and_lock(lock);
2232                         LDLM_LOCK_RELEASE(lock);
2233                         rc = ldlm_callback_reply(req, -EINVAL);
2234                         ldlm_callback_errmsg(req, "Operate on stale lock", rc,
2235                                              &dlm_req->lock_handle[0]);
2236                         RETURN(0);
2237                 }
2238                 /* BL_AST locks are not needed in LRU.
2239                  * Let ldlm_cancel_lru() be fast. */
2240                 ldlm_lock_remove_from_lru(lock);
2241                 lock->l_flags |= LDLM_FL_BL_AST;
2242         }
2243         unlock_res_and_lock(lock);
2244
2245         /* We want the ost thread to get this reply so that it can respond
2246          * to ost requests (write cache writeback) that might be triggered
2247          * in the callback.
2248          *
2249          * But we'd also like to be able to indicate in the reply that we're
2250          * cancelling right now, because it's unused, or have an intent result
2251          * in the reply, so we might have to push the responsibility for sending
2252          * the reply down into the AST handlers, alas. */
2253
2254         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2255         case LDLM_BL_CALLBACK:
2256                 CDEBUG(D_INODE, "blocking ast\n");
2257                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_BL_CALLBACK);
2258                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)) {
2259                         rc = ldlm_callback_reply(req, 0);
2260                         if (req->rq_no_reply || rc)
2261                                 ldlm_callback_errmsg(req, "Normal process", rc,
2262                                                      &dlm_req->lock_handle[0]);
2263                 }
2264                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
2265                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
2266                 break;
2267         case LDLM_CP_CALLBACK:
2268                 CDEBUG(D_INODE, "completion ast\n");
2269                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_CP_CALLBACK);
2270                 ldlm_callback_reply(req, 0);
2271                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
2272                 break;
2273         case LDLM_GL_CALLBACK:
2274                 CDEBUG(D_INODE, "glimpse ast\n");
2275                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_GL_CALLBACK);
2276                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
2277                 break;
2278         default:
2279                 LBUG();                         /* checked above */
2280         }
2281
2282         RETURN(0);
2283 }
2284
2285 #ifdef HAVE_SERVER_SUPPORT
2286 /**
2287  * Main handler for canceld thread.
2288  *
2289  * Separated into its own thread to avoid deadlocks.
2290  */
2291 static int ldlm_cancel_handler(struct ptlrpc_request *req)
2292 {
2293         int rc;
2294         ENTRY;
2295
2296         /* Requests arrive in sender's byte order.  The ptlrpc service
2297          * handler has already checked and, if necessary, byte-swapped the
2298          * incoming request message body, but I am responsible for the
2299          * message buffers. */
2300
2301         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2302
2303         if (req->rq_export == NULL) {
2304                 struct ldlm_request *dlm_req;
2305
2306                 CERROR("%s from %s arrived at %lu with bad export cookie "
2307                        LPU64"\n",
2308                        ll_opcode2str(lustre_msg_get_opc(req->rq_reqmsg)),
2309                        libcfs_nid2str(req->rq_peer.nid),
2310                        req->rq_arrival_time.tv_sec,
2311                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
2312
2313                 if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_CANCEL) {
2314                         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2315                         dlm_req = req_capsule_client_get(&req->rq_pill,
2316                                                          &RMF_DLM_REQ);
2317                         if (dlm_req != NULL)
2318                                 ldlm_lock_dump_handle(D_ERROR,
2319                                                       &dlm_req->lock_handle[0]);
2320                 }
2321                 ldlm_callback_reply(req, -ENOTCONN);
2322                 RETURN(0);
2323         }
2324
2325         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2326
2327         /* XXX FIXME move this back to mds/handler.c, bug 249 */
2328         case LDLM_CANCEL:
2329                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2330                 CDEBUG(D_INODE, "cancel\n");
2331                 if (CFS_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_NET) ||
2332                     CFS_FAIL_CHECK(OBD_FAIL_PTLRPC_CANCEL_RESEND))
2333                         RETURN(0);
2334                 rc = ldlm_handle_cancel(req);
2335                 if (rc)
2336                         break;
2337                 RETURN(0);
2338         case OBD_LOG_CANCEL:
2339                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
2340                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
2341                         RETURN(0);
2342                 rc = llog_origin_handle_cancel(req);
2343                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
2344                         RETURN(0);
2345                 ldlm_callback_reply(req, rc);
2346                 RETURN(0);
2347         default:
2348                 CERROR("invalid opcode %d\n",
2349                        lustre_msg_get_opc(req->rq_reqmsg));
2350                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2351                 ldlm_callback_reply(req, -EINVAL);
2352         }
2353
2354         RETURN(0);
2355 }
2356
2357 static int ldlm_cancel_hpreq_lock_match(struct ptlrpc_request *req,
2358                                         struct ldlm_lock *lock)
2359 {
2360         struct ldlm_request *dlm_req;
2361         struct lustre_handle lockh;
2362         int rc = 0;
2363         int i;
2364         ENTRY;
2365
2366         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2367         if (dlm_req == NULL)
2368                 RETURN(0);
2369
2370         ldlm_lock2handle(lock, &lockh);
2371         for (i = 0; i < dlm_req->lock_count; i++) {
2372                 if (lustre_handle_equal(&dlm_req->lock_handle[i],
2373                                         &lockh)) {
2374                         DEBUG_REQ(D_RPCTRACE, req,
2375                                   "Prio raised by lock "LPX64".", lockh.cookie);
2376
2377                         rc = 1;
2378                         break;
2379                 }
2380         }
2381
2382         RETURN(rc);
2383
2384 }
2385
2386 static int ldlm_cancel_hpreq_check(struct ptlrpc_request *req)
2387 {
2388         struct ldlm_request *dlm_req;
2389         int rc = 0;
2390         int i;
2391         ENTRY;
2392
2393         /* no prolong in recovery */
2394         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
2395                 RETURN(0);
2396
2397         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2398         if (dlm_req == NULL)
2399                 RETURN(-EFAULT);
2400
2401         for (i = 0; i < dlm_req->lock_count; i++) {
2402                 struct ldlm_lock *lock;
2403
2404                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
2405                 if (lock == NULL)
2406                         continue;
2407
2408                 rc = !!(lock->l_flags & LDLM_FL_AST_SENT);
2409                 if (rc)
2410                         LDLM_DEBUG(lock, "hpreq cancel lock");
2411                 LDLM_LOCK_PUT(lock);
2412
2413                 if (rc)
2414                         break;
2415         }
2416
2417         RETURN(rc);
2418 }
2419
2420 static struct ptlrpc_hpreq_ops ldlm_cancel_hpreq_ops = {
2421         .hpreq_lock_match = ldlm_cancel_hpreq_lock_match,
2422         .hpreq_check      = ldlm_cancel_hpreq_check,
2423         .hpreq_fini       = NULL,
2424 };
2425
2426 static int ldlm_hpreq_handler(struct ptlrpc_request *req)
2427 {
2428         ENTRY;
2429
2430         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2431
2432         if (req->rq_export == NULL)
2433                 RETURN(0);
2434
2435         if (LDLM_CANCEL == lustre_msg_get_opc(req->rq_reqmsg)) {
2436                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2437                 req->rq_ops = &ldlm_cancel_hpreq_ops;
2438         }
2439         RETURN(0);
2440 }
2441
2442 int ldlm_revoke_lock_cb(cfs_hash_t *hs, cfs_hash_bd_t *bd,
2443                         cfs_hlist_node_t *hnode, void *data)
2444
2445 {
2446         cfs_list_t         *rpc_list = data;
2447         struct ldlm_lock   *lock = cfs_hash_object(hs, hnode);
2448
2449         lock_res_and_lock(lock);
2450
2451         if (lock->l_req_mode != lock->l_granted_mode) {
2452                 unlock_res_and_lock(lock);
2453                 return 0;
2454         }
2455
2456         LASSERT(lock->l_resource);
2457         if (lock->l_resource->lr_type != LDLM_IBITS &&
2458             lock->l_resource->lr_type != LDLM_PLAIN) {
2459                 unlock_res_and_lock(lock);
2460                 return 0;
2461         }
2462
2463         if (lock->l_flags & LDLM_FL_AST_SENT) {
2464                 unlock_res_and_lock(lock);
2465                 return 0;
2466         }
2467
2468         LASSERT(lock->l_blocking_ast);
2469         LASSERT(!lock->l_blocking_lock);
2470
2471         lock->l_flags |= LDLM_FL_AST_SENT;
2472         if (lock->l_export && lock->l_export->exp_lock_hash) {
2473                 /* NB: it's safe to call cfs_hash_del() even lock isn't
2474                  * in exp_lock_hash. */
2475                 /* In the function below, .hs_keycmp resolves to
2476                  * ldlm_export_lock_keycmp() */
2477                 /* coverity[overrun-buffer-val] */
2478                 cfs_hash_del(lock->l_export->exp_lock_hash,
2479                              &lock->l_remote_handle, &lock->l_exp_hash);
2480         }
2481
2482         cfs_list_add_tail(&lock->l_rk_ast, rpc_list);
2483         LDLM_LOCK_GET(lock);
2484
2485         unlock_res_and_lock(lock);
2486         return 0;
2487 }
2488
2489 void ldlm_revoke_export_locks(struct obd_export *exp)
2490 {
2491         cfs_list_t  rpc_list;
2492         ENTRY;
2493
2494         CFS_INIT_LIST_HEAD(&rpc_list);
2495         cfs_hash_for_each_empty(exp->exp_lock_hash,
2496                                 ldlm_revoke_lock_cb, &rpc_list);
2497         ldlm_run_ast_work(exp->exp_obd->obd_namespace, &rpc_list,
2498                           LDLM_WORK_REVOKE_AST);
2499
2500         EXIT;
2501 }
2502 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2503 #endif /* HAVE_SERVER_SUPPORT */
2504
2505 #ifdef __KERNEL__
2506 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
2507 {
2508         struct ldlm_bl_work_item *blwi = NULL;
2509         static unsigned int num_bl = 0;
2510
2511         spin_lock(&blp->blp_lock);
2512         /* process a request from the blp_list at least every blp_num_threads */
2513         if (!cfs_list_empty(&blp->blp_list) &&
2514             (cfs_list_empty(&blp->blp_prio_list) || num_bl == 0))
2515                 blwi = cfs_list_entry(blp->blp_list.next,
2516                                       struct ldlm_bl_work_item, blwi_entry);
2517         else
2518                 if (!cfs_list_empty(&blp->blp_prio_list))
2519                         blwi = cfs_list_entry(blp->blp_prio_list.next,
2520                                               struct ldlm_bl_work_item,
2521                                               blwi_entry);
2522
2523         if (blwi) {
2524                 if (++num_bl >= cfs_atomic_read(&blp->blp_num_threads))
2525                         num_bl = 0;
2526                 cfs_list_del(&blwi->blwi_entry);
2527         }
2528         spin_unlock(&blp->blp_lock);
2529
2530         return blwi;
2531 }
2532
2533 /* This only contains temporary data until the thread starts */
2534 struct ldlm_bl_thread_data {
2535         char                    bltd_name[CFS_CURPROC_COMM_MAX];
2536         struct ldlm_bl_pool     *bltd_blp;
2537         struct completion       bltd_comp;
2538         int                     bltd_num;
2539 };
2540
2541 static int ldlm_bl_thread_main(void *arg);
2542
2543 static int ldlm_bl_thread_start(struct ldlm_bl_pool *blp)
2544 {
2545         struct ldlm_bl_thread_data bltd = { .bltd_blp = blp };
2546         int rc;
2547
2548         init_completion(&bltd.bltd_comp);
2549         rc = cfs_create_thread(ldlm_bl_thread_main, &bltd, 0);
2550         if (rc < 0) {
2551                 CERROR("cannot start LDLM thread ldlm_bl_%02d: rc %d\n",
2552                        cfs_atomic_read(&blp->blp_num_threads), rc);
2553                 return rc;
2554         }
2555         wait_for_completion(&bltd.bltd_comp);
2556
2557         return 0;
2558 }
2559
2560 /**
2561  * Main blocking requests processing thread.
2562  *
2563  * Callers put locks into its queue by calling ldlm_bl_to_thread.
2564  * This thread in the end ends up doing actual call to ->l_blocking_ast
2565  * for queued locks.
2566  */
2567 static int ldlm_bl_thread_main(void *arg)
2568 {
2569         struct ldlm_bl_pool *blp;
2570         ENTRY;
2571
2572         {
2573                 struct ldlm_bl_thread_data *bltd = arg;
2574
2575                 blp = bltd->bltd_blp;
2576
2577                 bltd->bltd_num =
2578                         cfs_atomic_inc_return(&blp->blp_num_threads) - 1;
2579                 cfs_atomic_inc(&blp->blp_busy_threads);
2580
2581                 snprintf(bltd->bltd_name, sizeof(bltd->bltd_name) - 1,
2582                         "ldlm_bl_%02d", bltd->bltd_num);
2583                 cfs_daemonize(bltd->bltd_name);
2584
2585                 complete(&bltd->bltd_comp);
2586                 /* cannot use bltd after this, it is only on caller's stack */
2587         }
2588
2589         while (1) {
2590                 struct l_wait_info lwi = { 0 };
2591                 struct ldlm_bl_work_item *blwi = NULL;
2592                 int busy;
2593
2594                 blwi = ldlm_bl_get_work(blp);
2595
2596                 if (blwi == NULL) {
2597                         cfs_atomic_dec(&blp->blp_busy_threads);
2598                         l_wait_event_exclusive(blp->blp_waitq,
2599                                          (blwi = ldlm_bl_get_work(blp)) != NULL,
2600                                          &lwi);
2601                         busy = cfs_atomic_inc_return(&blp->blp_busy_threads);
2602                 } else {
2603                         busy = cfs_atomic_read(&blp->blp_busy_threads);
2604                 }
2605
2606                 if (blwi->blwi_ns == NULL)
2607                         /* added by ldlm_cleanup() */
2608                         break;
2609
2610                 /* Not fatal if racy and have a few too many threads */
2611                 if (unlikely(busy < blp->blp_max_threads &&
2612                              busy >= cfs_atomic_read(&blp->blp_num_threads) &&
2613                              !blwi->blwi_mem_pressure))
2614                         /* discard the return value, we tried */
2615                         ldlm_bl_thread_start(blp);
2616
2617                 if (blwi->blwi_mem_pressure)
2618                         cfs_memory_pressure_set();
2619
2620                 if (blwi->blwi_count) {
2621                         int count;
2622                         /* The special case when we cancel locks in LRU
2623                          * asynchronously, we pass the list of locks here.
2624                          * Thus locks are marked LDLM_FL_CANCELING, but NOT
2625                          * canceled locally yet. */
2626                         count = ldlm_cli_cancel_list_local(&blwi->blwi_head,
2627                                                            blwi->blwi_count,
2628                                                            LCF_BL_AST);
2629                         ldlm_cli_cancel_list(&blwi->blwi_head, count, NULL, 0);
2630                 } else {
2631                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
2632                                                 blwi->blwi_lock);
2633                 }
2634                 if (blwi->blwi_mem_pressure)
2635                         cfs_memory_pressure_clr();
2636
2637                 if (blwi->blwi_mode == LDLM_ASYNC)
2638                         OBD_FREE(blwi, sizeof(*blwi));
2639                 else
2640                         complete(&blwi->blwi_comp);
2641         }
2642
2643         cfs_atomic_dec(&blp->blp_busy_threads);
2644         cfs_atomic_dec(&blp->blp_num_threads);
2645         complete(&blp->blp_comp);
2646         RETURN(0);
2647 }
2648
2649 #endif
2650
2651 static int ldlm_setup(void);
2652 static int ldlm_cleanup(void);
2653
2654 int ldlm_get_ref(void)
2655 {
2656         int rc = 0;
2657         ENTRY;
2658         mutex_lock(&ldlm_ref_mutex);
2659         if (++ldlm_refcount == 1) {
2660                 rc = ldlm_setup();
2661                 if (rc)
2662                         ldlm_refcount--;
2663         }
2664         mutex_unlock(&ldlm_ref_mutex);
2665
2666         RETURN(rc);
2667 }
2668 EXPORT_SYMBOL(ldlm_get_ref);
2669
2670 void ldlm_put_ref(void)
2671 {
2672         ENTRY;
2673         mutex_lock(&ldlm_ref_mutex);
2674         if (ldlm_refcount == 1) {
2675                 int rc = ldlm_cleanup();
2676                 if (rc)
2677                         CERROR("ldlm_cleanup failed: %d\n", rc);
2678                 else
2679                         ldlm_refcount--;
2680         } else {
2681                 ldlm_refcount--;
2682         }
2683         mutex_unlock(&ldlm_ref_mutex);
2684
2685         EXIT;
2686 }
2687 EXPORT_SYMBOL(ldlm_put_ref);
2688
2689 /*
2690  * Export handle<->lock hash operations.
2691  */
2692 static unsigned
2693 ldlm_export_lock_hash(cfs_hash_t *hs, const void *key, unsigned mask)
2694 {
2695         return cfs_hash_u64_hash(((struct lustre_handle *)key)->cookie, mask);
2696 }
2697
2698 static void *
2699 ldlm_export_lock_key(cfs_hlist_node_t *hnode)
2700 {
2701         struct ldlm_lock *lock;
2702
2703         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2704         return &lock->l_remote_handle;
2705 }
2706
2707 static void
2708 ldlm_export_lock_keycpy(cfs_hlist_node_t *hnode, void *key)
2709 {
2710         struct ldlm_lock     *lock;
2711
2712         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2713         lock->l_remote_handle = *(struct lustre_handle *)key;
2714 }
2715
2716 static int
2717 ldlm_export_lock_keycmp(const void *key, cfs_hlist_node_t *hnode)
2718 {
2719         return lustre_handle_equal(ldlm_export_lock_key(hnode), key);
2720 }
2721
2722 static void *
2723 ldlm_export_lock_object(cfs_hlist_node_t *hnode)
2724 {
2725         return cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2726 }
2727
2728 static void
2729 ldlm_export_lock_get(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
2730 {
2731         struct ldlm_lock *lock;
2732
2733         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2734         LDLM_LOCK_GET(lock);
2735 }
2736
2737 static void
2738 ldlm_export_lock_put(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
2739 {
2740         struct ldlm_lock *lock;
2741
2742         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2743         LDLM_LOCK_RELEASE(lock);
2744 }
2745
2746 static cfs_hash_ops_t ldlm_export_lock_ops = {
2747         .hs_hash        = ldlm_export_lock_hash,
2748         .hs_key         = ldlm_export_lock_key,
2749         .hs_keycmp      = ldlm_export_lock_keycmp,
2750         .hs_keycpy      = ldlm_export_lock_keycpy,
2751         .hs_object      = ldlm_export_lock_object,
2752         .hs_get         = ldlm_export_lock_get,
2753         .hs_put         = ldlm_export_lock_put,
2754         .hs_put_locked  = ldlm_export_lock_put,
2755 };
2756
2757 int ldlm_init_export(struct obd_export *exp)
2758 {
2759         ENTRY;
2760
2761         exp->exp_lock_hash =
2762                 cfs_hash_create(obd_uuid2str(&exp->exp_client_uuid),
2763                                 HASH_EXP_LOCK_CUR_BITS,
2764                                 HASH_EXP_LOCK_MAX_BITS,
2765                                 HASH_EXP_LOCK_BKT_BITS, 0,
2766                                 CFS_HASH_MIN_THETA, CFS_HASH_MAX_THETA,
2767                                 &ldlm_export_lock_ops,
2768                                 CFS_HASH_DEFAULT | CFS_HASH_REHASH_KEY |
2769                                 CFS_HASH_NBLK_CHANGE);
2770
2771         if (!exp->exp_lock_hash)
2772                 RETURN(-ENOMEM);
2773
2774         RETURN(0);
2775 }
2776 EXPORT_SYMBOL(ldlm_init_export);
2777
2778 void ldlm_destroy_export(struct obd_export *exp)
2779 {
2780         ENTRY;
2781         cfs_hash_putref(exp->exp_lock_hash);
2782         exp->exp_lock_hash = NULL;
2783
2784         ldlm_destroy_flock_export(exp);
2785         EXIT;
2786 }
2787 EXPORT_SYMBOL(ldlm_destroy_export);
2788
2789 static int ldlm_setup(void)
2790 {
2791         static struct ptlrpc_service_conf       conf;
2792         struct ldlm_bl_pool                     *blp = NULL;
2793         int rc = 0;
2794 #ifdef __KERNEL__
2795         int i;
2796 #endif
2797         ENTRY;
2798
2799         if (ldlm_state != NULL)
2800                 RETURN(-EALREADY);
2801
2802         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
2803         if (ldlm_state == NULL)
2804                 RETURN(-ENOMEM);
2805
2806 #ifdef LPROCFS
2807         rc = ldlm_proc_setup();
2808         if (rc != 0)
2809                 GOTO(out, rc);
2810 #endif
2811
2812         memset(&conf, 0, sizeof(conf));
2813         conf = (typeof(conf)) {
2814                 .psc_name               = "ldlm_cbd",
2815                 .psc_watchdog_factor    = 2,
2816                 .psc_buf                = {
2817                         .bc_nbufs               = LDLM_NBUFS,
2818                         .bc_buf_size            = LDLM_BUFSIZE,
2819                         .bc_req_max_size        = LDLM_MAXREQSIZE,
2820                         .bc_rep_max_size        = LDLM_MAXREPSIZE,
2821                         .bc_req_portal          = LDLM_CB_REQUEST_PORTAL,
2822                         .bc_rep_portal          = LDLM_CB_REPLY_PORTAL,
2823                 },
2824                 .psc_thr                = {
2825                         .tc_thr_name            = "ldlm_cb",
2826                         .tc_thr_factor          = LDLM_THR_FACTOR,
2827                         .tc_nthrs_init          = LDLM_NTHRS_INIT,
2828                         .tc_nthrs_base          = LDLM_NTHRS_BASE,
2829                         .tc_nthrs_max           = LDLM_NTHRS_MAX,
2830                         .tc_nthrs_user          = ldlm_num_threads,
2831                         .tc_cpu_affinity        = 1,
2832                         .tc_ctx_tags            = LCT_MD_THREAD | LCT_DT_THREAD,
2833                 },
2834                 .psc_cpt                = {
2835                         .cc_pattern             = ldlm_cpts,
2836                 },
2837                 .psc_ops                = {
2838                         .so_req_handler         = ldlm_callback_handler,
2839                 },
2840         };
2841         ldlm_state->ldlm_cb_service = \
2842                         ptlrpc_register_service(&conf, ldlm_svc_proc_dir);
2843         if (IS_ERR(ldlm_state->ldlm_cb_service)) {
2844                 CERROR("failed to start service\n");
2845                 rc = PTR_ERR(ldlm_state->ldlm_cb_service);
2846                 ldlm_state->ldlm_cb_service = NULL;
2847                 GOTO(out, rc);
2848         }
2849
2850 #ifdef HAVE_SERVER_SUPPORT
2851         memset(&conf, 0, sizeof(conf));
2852         conf = (typeof(conf)) {
2853                 .psc_name               = "ldlm_canceld",
2854                 .psc_watchdog_factor    = 6,
2855                 .psc_buf                = {
2856                         .bc_nbufs               = LDLM_NBUFS,
2857                         .bc_buf_size            = LDLM_BUFSIZE,
2858                         .bc_req_max_size        = LDLM_MAXREQSIZE,
2859                         .bc_rep_max_size        = LDLM_MAXREPSIZE,
2860                         .bc_req_portal          = LDLM_CANCEL_REQUEST_PORTAL,
2861                         .bc_rep_portal          = LDLM_CANCEL_REPLY_PORTAL,
2862
2863                 },
2864                 .psc_thr                = {
2865                         .tc_thr_name            = "ldlm_cn",
2866                         .tc_thr_factor          = LDLM_THR_FACTOR,
2867                         .tc_nthrs_init          = LDLM_NTHRS_INIT,
2868                         .tc_nthrs_base          = LDLM_NTHRS_BASE,
2869                         .tc_nthrs_max           = LDLM_NTHRS_MAX,
2870                         .tc_nthrs_user          = ldlm_num_threads,
2871                         .tc_cpu_affinity        = 1,
2872                         .tc_ctx_tags            = LCT_MD_THREAD | \
2873                                                   LCT_DT_THREAD | \
2874                                                   LCT_CL_THREAD,
2875                 },
2876                 .psc_cpt                = {
2877                         .cc_pattern             = ldlm_cpts,
2878                 },
2879                 .psc_ops                = {
2880                         .so_req_handler         = ldlm_cancel_handler,
2881                         .so_hpreq_handler       = ldlm_hpreq_handler,
2882                 },
2883         };
2884         ldlm_state->ldlm_cancel_service = \
2885                         ptlrpc_register_service(&conf, ldlm_svc_proc_dir);
2886         if (IS_ERR(ldlm_state->ldlm_cancel_service)) {
2887                 CERROR("failed to start service\n");
2888                 rc = PTR_ERR(ldlm_state->ldlm_cancel_service);
2889                 ldlm_state->ldlm_cancel_service = NULL;
2890                 GOTO(out, rc);
2891         }
2892 #endif
2893
2894         OBD_ALLOC(blp, sizeof(*blp));
2895         if (blp == NULL)
2896                 GOTO(out, rc = -ENOMEM);
2897         ldlm_state->ldlm_bl_pool = blp;
2898
2899         spin_lock_init(&blp->blp_lock);
2900         CFS_INIT_LIST_HEAD(&blp->blp_list);
2901         CFS_INIT_LIST_HEAD(&blp->blp_prio_list);
2902         cfs_waitq_init(&blp->blp_waitq);
2903         cfs_atomic_set(&blp->blp_num_threads, 0);
2904         cfs_atomic_set(&blp->blp_busy_threads, 0);
2905
2906 #ifdef __KERNEL__
2907         if (ldlm_num_threads == 0) {
2908                 blp->blp_min_threads = LDLM_NTHRS_INIT;
2909                 blp->blp_max_threads = LDLM_NTHRS_MAX;
2910         } else {
2911                 blp->blp_min_threads = blp->blp_max_threads = \
2912                         min_t(int, LDLM_NTHRS_MAX, max_t(int, LDLM_NTHRS_INIT,
2913                                                          ldlm_num_threads));
2914         }
2915
2916         for (i = 0; i < blp->blp_min_threads; i++) {
2917                 rc = ldlm_bl_thread_start(blp);
2918                 if (rc < 0)
2919                         GOTO(out, rc);
2920         }
2921
2922 # ifdef HAVE_SERVER_SUPPORT
2923         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
2924         expired_lock_thread.elt_state = ELT_STOPPED;
2925         cfs_waitq_init(&expired_lock_thread.elt_waitq);
2926
2927         CFS_INIT_LIST_HEAD(&waiting_locks_list);
2928         spin_lock_init(&waiting_locks_spinlock);
2929         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
2930
2931         rc = cfs_create_thread(expired_lock_main, NULL, CFS_DAEMON_FLAGS);
2932         if (rc < 0) {
2933                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
2934                 GOTO(out, rc);
2935         }
2936
2937         cfs_wait_event(expired_lock_thread.elt_waitq,
2938                        expired_lock_thread.elt_state == ELT_READY);
2939 # endif /* HAVE_SERVER_SUPPORT */
2940
2941         rc = ldlm_pools_init();
2942         if (rc) {
2943                 CERROR("Failed to initialize LDLM pools: %d\n", rc);
2944                 GOTO(out, rc);
2945         }
2946 #endif
2947         RETURN(0);
2948
2949  out:
2950         ldlm_cleanup();
2951         RETURN(rc);
2952 }
2953
2954 static int ldlm_cleanup(void)
2955 {
2956         ENTRY;
2957
2958         if (!cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) ||
2959             !cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
2960                 CERROR("ldlm still has namespaces; clean these up first.\n");
2961                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
2962                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
2963                 RETURN(-EBUSY);
2964         }
2965
2966 #ifdef __KERNEL__
2967         ldlm_pools_fini();
2968
2969         if (ldlm_state->ldlm_bl_pool != NULL) {
2970                 struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
2971
2972                 while (cfs_atomic_read(&blp->blp_num_threads) > 0) {
2973                         struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
2974
2975                         init_completion(&blp->blp_comp);
2976
2977                         spin_lock(&blp->blp_lock);
2978                         cfs_list_add_tail(&blwi.blwi_entry, &blp->blp_list);
2979                         cfs_waitq_signal(&blp->blp_waitq);
2980                         spin_unlock(&blp->blp_lock);
2981
2982                         wait_for_completion(&blp->blp_comp);
2983                 }
2984
2985                 OBD_FREE(blp, sizeof(*blp));
2986         }
2987 #endif /* __KERNEL__ */
2988
2989         if (ldlm_state->ldlm_cb_service != NULL)
2990                 ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2991 # ifdef HAVE_SERVER_SUPPORT
2992         if (ldlm_state->ldlm_cancel_service != NULL)
2993                 ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2994 # endif
2995
2996 #ifdef __KERNEL__
2997         ldlm_proc_cleanup();
2998
2999 # ifdef HAVE_SERVER_SUPPORT
3000         if (expired_lock_thread.elt_state != ELT_STOPPED) {
3001                 expired_lock_thread.elt_state = ELT_TERMINATE;
3002                 cfs_waitq_signal(&expired_lock_thread.elt_waitq);
3003                 cfs_wait_event(expired_lock_thread.elt_waitq,
3004                                expired_lock_thread.elt_state == ELT_STOPPED);
3005         }
3006 # endif
3007 #endif /* __KERNEL__ */
3008
3009         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
3010         ldlm_state = NULL;
3011
3012         RETURN(0);
3013 }
3014
3015 int ldlm_init(void)
3016 {
3017         mutex_init(&ldlm_ref_mutex);
3018         mutex_init(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
3019         mutex_init(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
3020         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
3021                                                sizeof(struct ldlm_resource), 0,
3022                                                CFS_SLAB_HWCACHE_ALIGN);
3023         if (ldlm_resource_slab == NULL)
3024                 return -ENOMEM;
3025
3026         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
3027                               sizeof(struct ldlm_lock), 0,
3028                               CFS_SLAB_HWCACHE_ALIGN | SLAB_DESTROY_BY_RCU);
3029         if (ldlm_lock_slab == NULL) {
3030                 cfs_mem_cache_destroy(ldlm_resource_slab);
3031                 return -ENOMEM;
3032         }
3033
3034         ldlm_interval_slab = cfs_mem_cache_create("interval_node",
3035                                         sizeof(struct ldlm_interval),
3036                                         0, CFS_SLAB_HWCACHE_ALIGN);
3037         if (ldlm_interval_slab == NULL) {
3038                 cfs_mem_cache_destroy(ldlm_resource_slab);
3039                 cfs_mem_cache_destroy(ldlm_lock_slab);
3040                 return -ENOMEM;
3041         }
3042 #if LUSTRE_TRACKS_LOCK_EXP_REFS
3043         class_export_dump_hook = ldlm_dump_export_locks;
3044 #endif
3045         return 0;
3046 }
3047
3048 void ldlm_exit(void)
3049 {
3050         int rc;
3051         if (ldlm_refcount)
3052                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
3053         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
3054         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
3055 #ifdef __KERNEL__
3056         /* ldlm_lock_put() use RCU to call ldlm_lock_free, so need call
3057          * synchronize_rcu() to wait a grace period elapsed, so that
3058          * ldlm_lock_free() get a chance to be called. */
3059         synchronize_rcu();
3060 #endif
3061         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
3062         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
3063         rc = cfs_mem_cache_destroy(ldlm_interval_slab);
3064         LASSERTF(rc == 0, "couldn't free interval node slab\n");
3065 }