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