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