Whamcloud - gitweb
Revert "b=22244 delegate lock cancel to blocking thread"
[fs/lustre-release.git] / lustre / ldlm / ldlm_lockd.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
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 #ifndef EXPORT_SYMTAB
43 # define EXPORT_SYMTAB
44 #endif
45 #define DEBUG_SUBSYSTEM S_LDLM
46
47 #ifdef __KERNEL__
48 # include <libcfs/libcfs.h>
49 #else
50 # include <liblustre.h>
51 #endif
52
53 #include <lustre_dlm.h>
54 #include <obd_class.h>
55 #include <libcfs/list.h>
56 #include "ldlm_internal.h"
57
58 #ifdef __KERNEL__
59 static int ldlm_num_threads;
60 CFS_MODULE_PARM(ldlm_num_threads, "i", int, 0444,
61                 "number of DLM service threads to start");
62 #endif
63
64 extern cfs_mem_cache_t *ldlm_resource_slab;
65 extern cfs_mem_cache_t *ldlm_lock_slab;
66 static cfs_semaphore_t  ldlm_ref_sem;
67 static int ldlm_refcount;
68
69 /* LDLM state */
70
71 static struct ldlm_state *ldlm_state;
72
73 inline cfs_time_t round_timeout(cfs_time_t timeout)
74 {
75         return cfs_time_seconds((int)cfs_duration_sec(cfs_time_sub(timeout, 0)) + 1);
76 }
77
78 /* timeout for initial callback (AST) reply (bz10399) */
79 static inline unsigned int ldlm_get_rq_timeout(void)
80 {
81         /* Non-AT value */
82         unsigned int timeout = min(ldlm_timeout, obd_timeout / 3);
83
84         return timeout < 1 ? 1 : timeout;
85 }
86
87 #ifdef __KERNEL__
88 /* w_l_spinlock protects both waiting_locks_list and expired_lock_thread */
89 static cfs_spinlock_t waiting_locks_spinlock;   /* BH lock (timer) */
90 static cfs_list_t waiting_locks_list;
91 static cfs_timer_t waiting_locks_timer;
92
93 static struct expired_lock_thread {
94         cfs_waitq_t               elt_waitq;
95         int                       elt_state;
96         int                       elt_dump;
97         cfs_list_t                elt_expired_locks;
98 } expired_lock_thread;
99 #endif
100
101 #define ELT_STOPPED   0
102 #define ELT_READY     1
103 #define ELT_TERMINATE 2
104
105 struct ldlm_bl_pool {
106         cfs_spinlock_t          blp_lock;
107
108         /*
109          * blp_prio_list is used for callbacks that should be handled
110          * as a priority. It is used for LDLM_FL_DISCARD_DATA requests.
111          * see bug 13843
112          */
113         cfs_list_t              blp_prio_list;
114
115         /*
116          * blp_list is used for all other callbacks which are likely
117          * to take longer to process.
118          */
119         cfs_list_t              blp_list;
120
121         cfs_waitq_t             blp_waitq;
122         cfs_completion_t        blp_comp;
123         cfs_atomic_t            blp_num_threads;
124         cfs_atomic_t            blp_busy_threads;
125         int                     blp_min_threads;
126         int                     blp_max_threads;
127 };
128
129 struct ldlm_bl_work_item {
130         cfs_list_t              blwi_entry;
131         struct ldlm_namespace  *blwi_ns;
132         struct ldlm_lock_desc   blwi_ld;
133         struct ldlm_lock       *blwi_lock;
134         cfs_list_t              blwi_head;
135         int                     blwi_count;
136         cfs_completion_t        blwi_comp;
137         cfs_atomic_t            blwi_ref_count;
138 };
139
140 #ifdef __KERNEL__
141 static inline void ldlm_bl_work_item_get(struct ldlm_bl_work_item *blwi)
142 {
143         cfs_atomic_inc(&blwi->blwi_ref_count);
144 }
145
146 static inline void ldlm_bl_work_item_put(struct ldlm_bl_work_item *blwi)
147 {
148         if (cfs_atomic_dec_and_test(&blwi->blwi_ref_count))
149                 OBD_FREE(blwi, sizeof(*blwi));
150 }
151
152 static inline int have_expired_locks(void)
153 {
154         int need_to_run;
155
156         ENTRY;
157         cfs_spin_lock_bh(&waiting_locks_spinlock);
158         need_to_run = !cfs_list_empty(&expired_lock_thread.elt_expired_locks);
159         cfs_spin_unlock_bh(&waiting_locks_spinlock);
160
161         RETURN(need_to_run);
162 }
163
164 static int expired_lock_main(void *arg)
165 {
166         cfs_list_t *expired = &expired_lock_thread.elt_expired_locks;
167         struct l_wait_info lwi = { 0 };
168         int do_dump;
169
170         ENTRY;
171         cfs_daemonize("ldlm_elt");
172
173         expired_lock_thread.elt_state = ELT_READY;
174         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
175
176         while (1) {
177                 l_wait_event(expired_lock_thread.elt_waitq,
178                              have_expired_locks() ||
179                              expired_lock_thread.elt_state == ELT_TERMINATE,
180                              &lwi);
181
182                 cfs_spin_lock_bh(&waiting_locks_spinlock);
183                 if (expired_lock_thread.elt_dump) {
184                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
185
186                         /* from waiting_locks_callback, but not in timer */
187                         libcfs_debug_dumplog();
188                         libcfs_run_lbug_upcall(__FILE__,
189                                                 "waiting_locks_callback",
190                                                 expired_lock_thread.elt_dump);
191
192                         cfs_spin_lock_bh(&waiting_locks_spinlock);
193                         expired_lock_thread.elt_dump = 0;
194                 }
195
196                 do_dump = 0;
197
198                 while (!cfs_list_empty(expired)) {
199                         struct obd_export *export;
200                         struct ldlm_lock *lock;
201
202                         lock = cfs_list_entry(expired->next, struct ldlm_lock,
203                                           l_pending_chain);
204                         if ((void *)lock < LP_POISON + CFS_PAGE_SIZE &&
205                             (void *)lock >= LP_POISON) {
206                                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
207                                 CERROR("free lock on elt list %p\n", lock);
208                                 LBUG();
209                         }
210                         cfs_list_del_init(&lock->l_pending_chain);
211                         if ((void *)lock->l_export < LP_POISON + CFS_PAGE_SIZE &&
212                             (void *)lock->l_export >= LP_POISON) {
213                                 CERROR("lock with free export on elt list %p\n",
214                                        lock->l_export);
215                                 lock->l_export = NULL;
216                                 LDLM_ERROR(lock, "free export");
217                                 /* release extra ref grabbed by
218                                  * ldlm_add_waiting_lock() or
219                                  * ldlm_failed_ast() */
220                                 LDLM_LOCK_RELEASE(lock);
221                                 continue;
222                         }
223                         export = class_export_lock_get(lock->l_export, lock);
224                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
225
226                         do_dump++;
227                         class_fail_export(export);
228                         class_export_lock_put(export, lock);
229
230                         /* release extra ref grabbed by ldlm_add_waiting_lock()
231                          * or ldlm_failed_ast() */
232                         LDLM_LOCK_RELEASE(lock);
233
234                         cfs_spin_lock_bh(&waiting_locks_spinlock);
235                 }
236                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
237
238                 if (do_dump && obd_dump_on_eviction) {
239                         CERROR("dump the log upon eviction\n");
240                         libcfs_debug_dumplog();
241                 }
242
243                 if (expired_lock_thread.elt_state == ELT_TERMINATE)
244                         break;
245         }
246
247         expired_lock_thread.elt_state = ELT_STOPPED;
248         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
249         RETURN(0);
250 }
251
252 static int ldlm_add_waiting_lock(struct ldlm_lock *lock);
253
254 /**
255  * Check if there is a request in the export request list
256  * which prevents the lock canceling.
257  */
258 static int ldlm_lock_busy(struct ldlm_lock *lock)
259 {
260         struct ptlrpc_request *req;
261         int match = 0;
262         ENTRY;
263
264         if (lock->l_export == NULL)
265                 return 0;
266
267         cfs_spin_lock(&lock->l_export->exp_lock);
268         cfs_list_for_each_entry(req, &lock->l_export->exp_queued_rpc,
269                                 rq_exp_list) {
270                 if (req->rq_ops->hpreq_lock_match) {
271                         match = req->rq_ops->hpreq_lock_match(req, lock);
272                         if (match)
273                                 break;
274                 }
275         }
276         cfs_spin_unlock(&lock->l_export->exp_lock);
277         RETURN(match);
278 }
279
280 /* This is called from within a timer interrupt and cannot schedule */
281 static void waiting_locks_callback(unsigned long unused)
282 {
283         struct ldlm_lock *lock, *last = NULL;
284
285 repeat:
286         cfs_spin_lock_bh(&waiting_locks_spinlock);
287         while (!cfs_list_empty(&waiting_locks_list)) {
288                 lock = cfs_list_entry(waiting_locks_list.next, struct ldlm_lock,
289                                       l_pending_chain);
290                 if (cfs_time_after(lock->l_callback_timeout,
291                                    cfs_time_current()) ||
292                     (lock->l_req_mode == LCK_GROUP))
293                         break;
294
295                 if (ptlrpc_check_suspend()) {
296                         /* there is a case when we talk to one mds, holding
297                          * lock from another mds. this way we easily can get
298                          * here, if second mds is being recovered. so, we
299                          * suspend timeouts. bug 6019 */
300
301                         LDLM_ERROR(lock, "recharge timeout: %s@%s nid %s ",
302                                    lock->l_export->exp_client_uuid.uuid,
303                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
304                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
305
306                         cfs_list_del_init(&lock->l_pending_chain);
307                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
308                         ldlm_add_waiting_lock(lock);
309                         goto repeat;
310                 }
311
312                 /* if timeout overlaps the activation time of suspended timeouts
313                  * then extend it to give a chance for client to reconnect */
314                 if (cfs_time_before(cfs_time_sub(lock->l_callback_timeout,
315                                                  cfs_time_seconds(obd_timeout)/2),
316                                     ptlrpc_suspend_wakeup_time())) {
317                         LDLM_ERROR(lock, "extend timeout due to recovery: %s@%s nid %s ",
318                                    lock->l_export->exp_client_uuid.uuid,
319                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
320                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
321
322                         cfs_list_del_init(&lock->l_pending_chain);
323                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
324                         ldlm_add_waiting_lock(lock);
325                         goto repeat;
326                 }
327
328                 /* Check if we need to prolong timeout */
329                 if (!OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT) &&
330                     ldlm_lock_busy(lock)) {
331                         int cont = 1;
332
333                         if (lock->l_pending_chain.next == &waiting_locks_list)
334                                 cont = 0;
335
336                         LDLM_LOCK_GET(lock);
337
338                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
339                         LDLM_DEBUG(lock, "prolong the busy lock");
340                         ldlm_refresh_waiting_lock(lock,
341                                                   ldlm_get_enq_timeout(lock));
342                         cfs_spin_lock_bh(&waiting_locks_spinlock);
343
344                         if (!cont) {
345                                 LDLM_LOCK_RELEASE(lock);
346                                 break;
347                         }
348
349                         LDLM_LOCK_RELEASE(lock);
350                         continue;
351                 }
352                 lock->l_resource->lr_namespace->ns_timeouts++;
353                 LDLM_ERROR(lock, "lock callback timer expired after %lds: "
354                            "evicting client at %s ",
355                            cfs_time_current_sec()- lock->l_last_activity,
356                            libcfs_nid2str(
357                                    lock->l_export->exp_connection->c_peer.nid));
358
359                 last = lock;
360
361                 /* no needs to take an extra ref on the lock since it was in
362                  * the waiting_locks_list and ldlm_add_waiting_lock()
363                  * already grabbed a ref */
364                 cfs_list_del(&lock->l_pending_chain);
365                 cfs_list_add(&lock->l_pending_chain,
366                              &expired_lock_thread.elt_expired_locks);
367         }
368
369         if (!cfs_list_empty(&expired_lock_thread.elt_expired_locks)) {
370                 if (obd_dump_on_timeout)
371                         expired_lock_thread.elt_dump = __LINE__;
372
373                 cfs_waitq_signal(&expired_lock_thread.elt_waitq);
374         }
375
376         /*
377          * Make sure the timer will fire again if we have any locks
378          * left.
379          */
380         if (!cfs_list_empty(&waiting_locks_list)) {
381                 cfs_time_t timeout_rounded;
382                 lock = cfs_list_entry(waiting_locks_list.next, struct ldlm_lock,
383                                       l_pending_chain);
384                 timeout_rounded = (cfs_time_t)round_timeout(lock->l_callback_timeout);
385                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
386         }
387         cfs_spin_unlock_bh(&waiting_locks_spinlock);
388 }
389
390 /*
391  * Indicate that we're waiting for a client to call us back cancelling a given
392  * lock.  We add it to the pending-callback chain, and schedule the lock-timeout
393  * timer to fire appropriately.  (We round up to the next second, to avoid
394  * floods of timer firings during periods of high lock contention and traffic).
395  * As done by ldlm_add_waiting_lock(), the caller must grab a lock reference
396  * if it has been added to the waiting list (1 is returned).
397  *
398  * Called with the namespace lock held.
399  */
400 static int __ldlm_add_waiting_lock(struct ldlm_lock *lock, int seconds)
401 {
402         cfs_time_t timeout;
403         cfs_time_t timeout_rounded;
404
405         if (!cfs_list_empty(&lock->l_pending_chain))
406                 return 0;
407
408         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT) ||
409             OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
410                 seconds = 1;
411
412         timeout = cfs_time_shift(seconds);
413         if (likely(cfs_time_after(timeout, lock->l_callback_timeout)))
414                 lock->l_callback_timeout = timeout;
415
416         timeout_rounded = round_timeout(lock->l_callback_timeout);
417
418         if (cfs_time_before(timeout_rounded,
419                             cfs_timer_deadline(&waiting_locks_timer)) ||
420             !cfs_timer_is_armed(&waiting_locks_timer)) {
421                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
422         }
423         /* if the new lock has a shorter timeout than something earlier on
424            the list, we'll wait the longer amount of time; no big deal. */
425         /* FIFO */
426         cfs_list_add_tail(&lock->l_pending_chain, &waiting_locks_list);
427         return 1;
428 }
429
430 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
431 {
432         int ret;
433         int timeout = ldlm_get_enq_timeout(lock);
434
435         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
436
437         cfs_spin_lock_bh(&waiting_locks_spinlock);
438         if (lock->l_destroyed) {
439                 static cfs_time_t next;
440                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
441                 LDLM_ERROR(lock, "not waiting on destroyed lock (bug 5653)");
442                 if (cfs_time_after(cfs_time_current(), next)) {
443                         next = cfs_time_shift(14400);
444                         libcfs_debug_dumpstack(NULL);
445                 }
446                 return 0;
447         }
448
449         ret = __ldlm_add_waiting_lock(lock, timeout);
450         if (ret)
451                 /* grab ref on the lock if it has been added to the
452                  * waiting list */
453                 LDLM_LOCK_GET(lock);
454         cfs_spin_unlock_bh(&waiting_locks_spinlock);
455
456         LDLM_DEBUG(lock, "%sadding to wait list(timeout: %d, AT: %s)",
457                    ret == 0 ? "not re-" : "", timeout,
458                    AT_OFF ? "off" : "on");
459         return ret;
460 }
461
462 /*
463  * Remove a lock from the pending list, likely because it had its cancellation
464  * callback arrive without incident.  This adjusts the lock-timeout timer if
465  * needed.  Returns 0 if the lock wasn't pending after all, 1 if it was.
466  * As done by ldlm_del_waiting_lock(), the caller must release the lock
467  * reference when the lock is removed from any list (1 is returned).
468  *
469  * Called with namespace lock held.
470  */
471 static int __ldlm_del_waiting_lock(struct ldlm_lock *lock)
472 {
473         cfs_list_t *list_next;
474
475         if (cfs_list_empty(&lock->l_pending_chain))
476                 return 0;
477
478         list_next = lock->l_pending_chain.next;
479         if (lock->l_pending_chain.prev == &waiting_locks_list) {
480                 /* Removing the head of the list, adjust timer. */
481                 if (list_next == &waiting_locks_list) {
482                         /* No more, just cancel. */
483                         cfs_timer_disarm(&waiting_locks_timer);
484                 } else {
485                         struct ldlm_lock *next;
486                         next = cfs_list_entry(list_next, struct ldlm_lock,
487                                               l_pending_chain);
488                         cfs_timer_arm(&waiting_locks_timer,
489                                       round_timeout(next->l_callback_timeout));
490                 }
491         }
492         cfs_list_del_init(&lock->l_pending_chain);
493
494         return 1;
495 }
496
497 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
498 {
499         int ret;
500
501         if (lock->l_export == NULL) {
502                 /* We don't have a "waiting locks list" on clients. */
503                 CDEBUG(D_DLMTRACE, "Client lock %p : no-op\n", lock);
504                 return 0;
505         }
506
507         cfs_spin_lock_bh(&waiting_locks_spinlock);
508         ret = __ldlm_del_waiting_lock(lock);
509         cfs_spin_unlock_bh(&waiting_locks_spinlock);
510         if (ret)
511                 /* release lock ref if it has indeed been removed
512                  * from a list */
513                 LDLM_LOCK_RELEASE(lock);
514
515         LDLM_DEBUG(lock, "%s", ret == 0 ? "wasn't waiting" : "removed");
516         return ret;
517 }
518
519 /*
520  * Prolong the lock
521  *
522  * Called with namespace lock held.
523  */
524 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
525 {
526         if (lock->l_export == NULL) {
527                 /* We don't have a "waiting locks list" on clients. */
528                 LDLM_DEBUG(lock, "client lock: no-op");
529                 return 0;
530         }
531
532         cfs_spin_lock_bh(&waiting_locks_spinlock);
533
534         if (cfs_list_empty(&lock->l_pending_chain)) {
535                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
536                 LDLM_DEBUG(lock, "wasn't waiting");
537                 return 0;
538         }
539
540         /* we remove/add the lock to the waiting list, so no needs to
541          * release/take a lock reference */
542         __ldlm_del_waiting_lock(lock);
543         __ldlm_add_waiting_lock(lock, timeout);
544         cfs_spin_unlock_bh(&waiting_locks_spinlock);
545
546         LDLM_DEBUG(lock, "refreshed");
547         return 1;
548 }
549 #else /* !__KERNEL__ */
550
551 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
552 {
553         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
554         RETURN(1);
555 }
556
557 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
558 {
559         RETURN(0);
560 }
561
562 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
563 {
564         RETURN(0);
565 }
566 #endif /* __KERNEL__ */
567
568 static void ldlm_failed_ast(struct ldlm_lock *lock, int rc,
569                             const char *ast_type)
570 {
571         LCONSOLE_ERROR_MSG(0x138, "%s: A client on nid %s was evicted due "
572                            "to a lock %s callback time out: rc %d\n",
573                            lock->l_export->exp_obd->obd_name,
574                            obd_export_nid2str(lock->l_export), ast_type, rc);
575
576         if (obd_dump_on_timeout)
577                 libcfs_debug_dumplog();
578 #ifdef __KERNEL__
579         cfs_spin_lock_bh(&waiting_locks_spinlock);
580         if (__ldlm_del_waiting_lock(lock) == 0)
581                 /* the lock was not in any list, grab an extra ref before adding
582                  * the lock to the expired list */
583                 LDLM_LOCK_GET(lock);
584         cfs_list_add(&lock->l_pending_chain,
585                      &expired_lock_thread.elt_expired_locks);
586         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
587         cfs_spin_unlock_bh(&waiting_locks_spinlock);
588 #else
589         class_fail_export(lock->l_export);
590 #endif
591 }
592
593 static int ldlm_handle_ast_error(struct ldlm_lock *lock,
594                                  struct ptlrpc_request *req, int rc,
595                                  const char *ast_type)
596 {
597         lnet_process_id_t peer = req->rq_import->imp_connection->c_peer;
598
599         if (rc == -ETIMEDOUT || rc == -EINTR || rc == -ENOTCONN) {
600                 LASSERT(lock->l_export);
601                 if (lock->l_export->exp_libclient) {
602                         LDLM_DEBUG(lock, "%s AST to liblustre client (nid %s)"
603                                    " timeout, just cancelling lock", ast_type,
604                                    libcfs_nid2str(peer.nid));
605                         ldlm_lock_cancel(lock);
606                         rc = -ERESTART;
607                 } else if (lock->l_flags & LDLM_FL_CANCEL) {
608                         LDLM_DEBUG(lock, "%s AST timeout from nid %s, but "
609                                    "cancel was received (AST reply lost?)",
610                                    ast_type, libcfs_nid2str(peer.nid));
611                         ldlm_lock_cancel(lock);
612                         rc = -ERESTART;
613                 } else {
614                         ldlm_del_waiting_lock(lock);
615                         ldlm_failed_ast(lock, rc, ast_type);
616                 }
617         } else if (rc) {
618                 if (rc == -EINVAL)
619                         LDLM_DEBUG(lock, "client (nid %s) returned %d"
620                                " from %s AST - normal race",
621                                libcfs_nid2str(peer.nid),
622                                req->rq_repmsg ?
623                                lustre_msg_get_status(req->rq_repmsg) : -1,
624                                ast_type);
625                 else
626                         LDLM_ERROR(lock, "client (nid %s) returned %d "
627                                    "from %s AST", libcfs_nid2str(peer.nid),
628                                    (req->rq_repmsg != NULL) ?
629                                    lustre_msg_get_status(req->rq_repmsg) : 0,
630                                    ast_type);
631                 ldlm_lock_cancel(lock);
632                 /* Server-side AST functions are called from ldlm_reprocess_all,
633                  * which needs to be told to please restart its reprocessing. */
634                 rc = -ERESTART;
635         }
636
637         return rc;
638 }
639
640 static int ldlm_cb_interpret(const struct lu_env *env,
641                              struct ptlrpc_request *req, void *data, int rc)
642 {
643         struct ldlm_cb_set_arg *arg;
644         struct ldlm_lock *lock;
645         ENTRY;
646
647         LASSERT(data != NULL);
648
649         arg = req->rq_async_args.pointer_arg[0];
650         lock = req->rq_async_args.pointer_arg[1];
651         LASSERT(lock != NULL);
652         if (rc != 0) {
653                 /* If client canceled the lock but the cancel has not
654                  * been received yet, we need to update lvbo to have the
655                  * proper attributes cached. */
656                 if (rc == -EINVAL && arg->type == LDLM_BL_CALLBACK)
657                         ldlm_res_lvbo_update(lock->l_resource, NULL, 1);
658                 rc = ldlm_handle_ast_error(lock, req, rc,
659                                            arg->type == LDLM_BL_CALLBACK
660                                            ? "blocking" : "completion");
661         }
662
663         LDLM_LOCK_RELEASE(lock);
664
665         if (rc == -ERESTART)
666                 cfs_atomic_set(&arg->restart, 1);
667
668         RETURN(0);
669 }
670
671 static inline int ldlm_bl_and_cp_ast_fini(struct ptlrpc_request *req,
672                                           struct ldlm_cb_set_arg *arg,
673                                           struct ldlm_lock *lock,
674                                           int instant_cancel)
675 {
676         int rc = 0;
677         ENTRY;
678
679         if (unlikely(instant_cancel)) {
680                 rc = ptl_send_rpc(req, 1);
681                 ptlrpc_req_finished(req);
682                 if (rc == 0)
683                         /* If we cancelled the lock, we need to restart
684                          * ldlm_reprocess_queue */
685                         cfs_atomic_set(&arg->restart, 1);
686         } else {
687                 LDLM_LOCK_GET(lock);
688                 ptlrpc_set_add_req(arg->set, req);
689         }
690
691         RETURN(rc);
692 }
693
694 /**
695  * Check if there are requests in the export request list which prevent
696  * the lock canceling and make these requests high priority ones.
697  */
698 static void ldlm_lock_reorder_req(struct ldlm_lock *lock)
699 {
700         struct ptlrpc_request *req;
701         ENTRY;
702
703         if (lock->l_export == NULL) {
704                 LDLM_DEBUG(lock, "client lock: no-op");
705                 RETURN_EXIT;
706         }
707
708         cfs_spin_lock(&lock->l_export->exp_lock);
709         cfs_list_for_each_entry(req, &lock->l_export->exp_queued_rpc,
710                                 rq_exp_list) {
711                 if (!req->rq_hp && req->rq_ops->hpreq_lock_match &&
712                     req->rq_ops->hpreq_lock_match(req, lock))
713                         ptlrpc_hpreq_reorder(req);
714         }
715         cfs_spin_unlock(&lock->l_export->exp_lock);
716         EXIT;
717 }
718
719 /*
720  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
721  * enqueued server lock conflicts with given one.
722  *
723  * Sends blocking ast rpc to the client owning that lock; arms timeout timer
724  * to wait for client response.
725  */
726 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
727                              struct ldlm_lock_desc *desc,
728                              void *data, int flag)
729 {
730         struct ldlm_cb_set_arg *arg = data;
731         struct ldlm_request    *body;
732         struct ptlrpc_request  *req;
733         int                     instant_cancel = 0;
734         int                     rc = 0;
735         ENTRY;
736
737         if (flag == LDLM_CB_CANCELING)
738                 /* Don't need to do anything here. */
739                 RETURN(0);
740
741         LASSERT(lock);
742         LASSERT(data != NULL);
743         if (lock->l_export->exp_obd->obd_recovering != 0) {
744                 LDLM_ERROR(lock, "BUG 6063: lock collide during recovery");
745                 ldlm_lock_dump(D_ERROR, lock, 0);
746         }
747
748         ldlm_lock_reorder_req(lock);
749
750         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
751                                         &RQF_LDLM_BL_CALLBACK,
752                                         LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK);
753         if (req == NULL)
754                 RETURN(-ENOMEM);
755
756         req->rq_async_args.pointer_arg[0] = arg;
757         req->rq_async_args.pointer_arg[1] = lock;
758         req->rq_interpret_reply = ldlm_cb_interpret;
759         req->rq_no_resend = 1;
760
761         lock_res(lock->l_resource);
762         if (lock->l_granted_mode != lock->l_req_mode) {
763                 /* this blocking AST will be communicated as part of the
764                  * completion AST instead */
765                 unlock_res(lock->l_resource);
766                 ptlrpc_req_finished(req);
767                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
768                 RETURN(0);
769         }
770
771         if (lock->l_destroyed) {
772                 /* What's the point? */
773                 unlock_res(lock->l_resource);
774                 ptlrpc_req_finished(req);
775                 RETURN(0);
776         }
777
778         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
779                 instant_cancel = 1;
780
781         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
782         body->lock_handle[0] = lock->l_remote_handle;
783         body->lock_desc = *desc;
784         body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
785
786         LDLM_DEBUG(lock, "server preparing blocking AST");
787
788         ptlrpc_request_set_replen(req);
789         if (instant_cancel) {
790                 unlock_res(lock->l_resource);
791                 ldlm_lock_cancel(lock);
792         } else {
793                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
794                 ldlm_add_waiting_lock(lock);
795                 unlock_res(lock->l_resource);
796         }
797
798         req->rq_send_state = LUSTRE_IMP_FULL;
799         /* ptlrpc_request_alloc_pack already set timeout */
800         if (AT_OFF)
801                 req->rq_timeout = ldlm_get_rq_timeout();
802
803         if (lock->l_export && lock->l_export->exp_nid_stats &&
804             lock->l_export->exp_nid_stats->nid_ldlm_stats)
805                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
806                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
807
808         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
809
810         RETURN(rc);
811 }
812
813 int ldlm_server_completion_ast(struct ldlm_lock *lock, int flags, void *data)
814 {
815         struct ldlm_cb_set_arg *arg = data;
816         struct ldlm_request    *body;
817         struct ptlrpc_request  *req;
818         long                    total_enqueue_wait;
819         int                     instant_cancel = 0;
820         int                     rc = 0;
821         ENTRY;
822
823         LASSERT(lock != NULL);
824         LASSERT(data != NULL);
825
826         total_enqueue_wait = cfs_time_sub(cfs_time_current_sec(),
827                                           lock->l_last_activity);
828
829         req = ptlrpc_request_alloc(lock->l_export->exp_imp_reverse,
830                                     &RQF_LDLM_CP_CALLBACK);
831         if (req == NULL)
832                 RETURN(-ENOMEM);
833
834         lock_res_and_lock(lock);
835         if (lock->l_resource->lr_lvb_len)
836                  req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT,
837                                       lock->l_resource->lr_lvb_len);
838         unlock_res_and_lock(lock);
839
840         rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK);
841         if (rc) {
842                 ptlrpc_request_free(req);
843                 RETURN(rc);
844         }
845
846         req->rq_async_args.pointer_arg[0] = arg;
847         req->rq_async_args.pointer_arg[1] = lock;
848         req->rq_interpret_reply = ldlm_cb_interpret;
849         req->rq_no_resend = 1;
850         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
851
852         body->lock_handle[0] = lock->l_remote_handle;
853         body->lock_flags = flags;
854         ldlm_lock2desc(lock, &body->lock_desc);
855         if (lock->l_resource->lr_lvb_len) {
856                 void *lvb = req_capsule_client_get(&req->rq_pill, &RMF_DLM_LVB);
857
858                 lock_res_and_lock(lock);
859                 memcpy(lvb, lock->l_resource->lr_lvb_data,
860                        lock->l_resource->lr_lvb_len);
861                 unlock_res_and_lock(lock);
862         }
863
864         LDLM_DEBUG(lock, "server preparing completion AST (after %lds wait)",
865                    total_enqueue_wait);
866
867         /* Server-side enqueue wait time estimate, used in
868             __ldlm_add_waiting_lock to set future enqueue timers */
869         if (total_enqueue_wait < ldlm_get_enq_timeout(lock))
870                 at_measured(&lock->l_resource->lr_namespace->ns_at_estimate,
871                             total_enqueue_wait);
872         else
873                 /* bz18618. Don't add lock enqueue time we spend waiting for a
874                    previous callback to fail. Locks waiting legitimately will
875                    get extended by ldlm_refresh_waiting_lock regardless of the
876                    estimate, so it's okay to underestimate here. */
877                 LDLM_DEBUG(lock, "lock completed after %lus; estimate was %ds. "
878                        "It is likely that a previous callback timed out.",
879                        total_enqueue_wait,
880                        at_get(&lock->l_resource->lr_namespace->ns_at_estimate));
881
882         ptlrpc_request_set_replen(req);
883
884         req->rq_send_state = LUSTRE_IMP_FULL;
885         /* ptlrpc_request_pack already set timeout */
886         if (AT_OFF)
887                 req->rq_timeout = ldlm_get_rq_timeout();
888
889         /* We only send real blocking ASTs after the lock is granted */
890         lock_res_and_lock(lock);
891         if (lock->l_flags & LDLM_FL_AST_SENT) {
892                 body->lock_flags |= LDLM_FL_AST_SENT;
893                 /* copy ast flags like LDLM_FL_DISCARD_DATA */
894                 body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
895
896                 /* We might get here prior to ldlm_handle_enqueue setting
897                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
898                  * into waiting list, but this is safe and similar code in
899                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
900                  * that would not only cancel the lock, but will also remove
901                  * it from waiting list */
902                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
903                         unlock_res_and_lock(lock);
904                         ldlm_lock_cancel(lock);
905                         instant_cancel = 1;
906                         lock_res_and_lock(lock);
907                 } else {
908                         /* start the lock-timeout clock */
909                         ldlm_add_waiting_lock(lock);
910                 }
911         }
912         unlock_res_and_lock(lock);
913
914         if (lock->l_export && lock->l_export->exp_nid_stats &&
915             lock->l_export->exp_nid_stats->nid_ldlm_stats)
916                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
917                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
918
919         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
920
921         RETURN(rc);
922 }
923
924 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
925 {
926         struct ldlm_resource  *res = lock->l_resource;
927         struct ldlm_request   *body;
928         struct ptlrpc_request *req;
929         int                    rc;
930         ENTRY;
931
932         LASSERT(lock != NULL);
933
934         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
935                                         &RQF_LDLM_GL_CALLBACK,
936                                         LUSTRE_DLM_VERSION, LDLM_GL_CALLBACK);
937
938         if (req == NULL)
939                 RETURN(-ENOMEM);
940
941         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
942         body->lock_handle[0] = lock->l_remote_handle;
943         ldlm_lock2desc(lock, &body->lock_desc);
944
945         lock_res_and_lock(lock);
946         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
947                              lock->l_resource->lr_lvb_len);
948         unlock_res_and_lock(lock);
949         res = lock->l_resource;
950         ptlrpc_request_set_replen(req);
951
952
953         req->rq_send_state = LUSTRE_IMP_FULL;
954         /* ptlrpc_request_alloc_pack already set timeout */
955         if (AT_OFF)
956                 req->rq_timeout = ldlm_get_rq_timeout();
957
958         if (lock->l_export && lock->l_export->exp_nid_stats &&
959             lock->l_export->exp_nid_stats->nid_ldlm_stats)
960                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
961                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
962
963         rc = ptlrpc_queue_wait(req);
964         if (rc == -ELDLM_NO_LOCK_DATA)
965                 LDLM_DEBUG(lock, "lost race - client has a lock but no inode");
966         else if (rc != 0)
967                 rc = ldlm_handle_ast_error(lock, req, rc, "glimpse");
968         else
969                 rc = ldlm_res_lvbo_update(res, req, 1);
970
971         ptlrpc_req_finished(req);
972         if (rc == -ERESTART)
973                 ldlm_reprocess_all(res);
974
975         RETURN(rc);
976 }
977
978 #ifdef __KERNEL__
979 extern unsigned long long lu_time_stamp_get(void);
980 #else
981 #define lu_time_stamp_get() time(NULL)
982 #endif
983
984 static void ldlm_svc_get_eopc(const struct ldlm_request *dlm_req,
985                        struct lprocfs_stats *srv_stats)
986 {
987         int lock_type = 0, op = 0;
988
989         lock_type = dlm_req->lock_desc.l_resource.lr_type;
990
991         switch (lock_type) {
992         case LDLM_PLAIN:
993                 op = PTLRPC_LAST_CNTR + LDLM_PLAIN_ENQUEUE;
994                 break;
995         case LDLM_EXTENT:
996                 if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT)
997                         op = PTLRPC_LAST_CNTR + LDLM_GLIMPSE_ENQUEUE;
998                 else
999                         op = PTLRPC_LAST_CNTR + LDLM_EXTENT_ENQUEUE;
1000                 break;
1001         case LDLM_FLOCK:
1002                 op = PTLRPC_LAST_CNTR + LDLM_FLOCK_ENQUEUE;
1003                 break;
1004         case LDLM_IBITS:
1005                 op = PTLRPC_LAST_CNTR + LDLM_IBITS_ENQUEUE;
1006                 break;
1007         default:
1008                 op = 0;
1009                 break;
1010         }
1011
1012         if (op)
1013                 lprocfs_counter_incr(srv_stats, op);
1014
1015         return;
1016 }
1017
1018 /*
1019  * Main server-side entry point into LDLM. This is called by ptlrpc service
1020  * threads to carry out client lock enqueueing requests.
1021  */
1022 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
1023                          struct ptlrpc_request *req,
1024                          const struct ldlm_request *dlm_req,
1025                          const struct ldlm_callback_suite *cbs)
1026 {
1027         struct ldlm_reply *dlm_rep;
1028         __u32 flags;
1029         ldlm_error_t err = ELDLM_OK;
1030         struct ldlm_lock *lock = NULL;
1031         void *cookie = NULL;
1032         int rc = 0;
1033         ENTRY;
1034
1035         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
1036
1037         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
1038         flags = dlm_req->lock_flags;
1039
1040         LASSERT(req->rq_export);
1041
1042         if (req->rq_rqbd->rqbd_service->srv_stats)
1043                 ldlm_svc_get_eopc(dlm_req,
1044                                   req->rq_rqbd->rqbd_service->srv_stats);
1045
1046         if (req->rq_export && req->rq_export->exp_nid_stats &&
1047             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1048                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1049                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
1050
1051         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
1052                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
1053                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
1054                           dlm_req->lock_desc.l_resource.lr_type);
1055                 GOTO(out, rc = -EFAULT);
1056         }
1057
1058         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
1059                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
1060                      dlm_req->lock_desc.l_req_mode &
1061                      (dlm_req->lock_desc.l_req_mode-1))) {
1062                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
1063                           dlm_req->lock_desc.l_req_mode);
1064                 GOTO(out, rc = -EFAULT);
1065         }
1066
1067         if (req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) {
1068                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1069                              LDLM_PLAIN)) {
1070                         DEBUG_REQ(D_ERROR, req,
1071                                   "PLAIN lock request from IBITS client?");
1072                         GOTO(out, rc = -EPROTO);
1073                 }
1074         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1075                             LDLM_IBITS)) {
1076                 DEBUG_REQ(D_ERROR, req,
1077                           "IBITS lock request from unaware client?");
1078                 GOTO(out, rc = -EPROTO);
1079         }
1080
1081 #if 0
1082         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
1083            against server's _CONNECT_SUPPORTED flags? (I don't want to use
1084            ibits for mgc/mgs) */
1085
1086         /* INODEBITS_INTEROP: Perform conversion from plain lock to
1087          * inodebits lock if client does not support them. */
1088         if (!(req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) &&
1089             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
1090                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
1091                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
1092                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
1093                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
1094                         dlm_req->lock_desc.l_req_mode = LCK_CR;
1095         }
1096 #endif
1097
1098         if (unlikely(flags & LDLM_FL_REPLAY)) {
1099                 /* Find an existing lock in the per-export lock hash */
1100                 lock = cfs_hash_lookup(req->rq_export->exp_lock_hash,
1101                                        (void *)&dlm_req->lock_handle[0]);
1102                 if (lock != NULL) {
1103                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
1104                                   LPX64, lock->l_handle.h_cookie);
1105                         GOTO(existing_lock, rc = 0);
1106                 }
1107         }
1108
1109         /* The lock's callback data might be set in the policy function */
1110         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
1111                                 dlm_req->lock_desc.l_resource.lr_type,
1112                                 dlm_req->lock_desc.l_req_mode,
1113                                 cbs, NULL, 0);
1114
1115         if (!lock)
1116                 GOTO(out, rc = -ENOMEM);
1117
1118         lock->l_last_activity = cfs_time_current_sec();
1119         lock->l_remote_handle = dlm_req->lock_handle[0];
1120         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
1121
1122         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
1123         /* Don't enqueue a lock onto the export if it has already
1124          * been evicted.  Cancel it now instead. (bug 3822) */
1125         if (req->rq_export->exp_failed) {
1126                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1127                 GOTO(out, rc = -ENOTCONN);
1128         }
1129
1130         lock->l_export = class_export_lock_get(req->rq_export, lock);
1131         if (lock->l_export->exp_lock_hash)
1132                 cfs_hash_add(lock->l_export->exp_lock_hash,
1133                              &lock->l_remote_handle,
1134                              &lock->l_exp_hash);
1135
1136 existing_lock:
1137
1138         if (flags & LDLM_FL_HAS_INTENT) {
1139                 /* In this case, the reply buffer is allocated deep in
1140                  * local_lock_enqueue by the policy function. */
1141                 cookie = req;
1142         } else {
1143                 lock_res_and_lock(lock);
1144                 if (lock->l_resource->lr_lvb_len) {
1145                         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
1146                                              RCL_SERVER,
1147                                              lock->l_resource->lr_lvb_len);
1148                 }
1149                 unlock_res_and_lock(lock);
1150
1151                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
1152                         GOTO(out, rc = -ENOMEM);
1153
1154                 rc = req_capsule_server_pack(&req->rq_pill);
1155                 if (rc)
1156                         GOTO(out, rc);
1157         }
1158
1159         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
1160                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1161         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
1162                 lock->l_req_extent = lock->l_policy_data.l_extent;
1163
1164         err = ldlm_lock_enqueue(ns, &lock, cookie, (int *)&flags);
1165         if (err)
1166                 GOTO(out, err);
1167
1168         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1169         dlm_rep->lock_flags = flags;
1170
1171         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
1172         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
1173
1174         /* We never send a blocking AST until the lock is granted, but
1175          * we can tell it right now */
1176         lock_res_and_lock(lock);
1177
1178         /* Now take into account flags to be inherited from original lock
1179            request both in reply to client and in our own lock flags. */
1180         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1181         lock->l_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1182
1183         /* Don't move a pending lock onto the export if it has already
1184          * been evicted.  Cancel it now instead. (bug 5683) */
1185         if (unlikely(req->rq_export->exp_failed ||
1186                      OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
1187                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1188                 rc = -ENOTCONN;
1189         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
1190                 dlm_rep->lock_flags |= LDLM_FL_AST_SENT;
1191                 if (lock->l_granted_mode == lock->l_req_mode) {
1192                         /*
1193                          * Only cancel lock if it was granted, because it would
1194                          * be destroyed immediately and would never be granted
1195                          * in the future, causing timeouts on client.  Not
1196                          * granted lock will be cancelled immediately after
1197                          * sending completion AST.
1198                          */
1199                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1200                                 unlock_res_and_lock(lock);
1201                                 ldlm_lock_cancel(lock);
1202                                 lock_res_and_lock(lock);
1203                         } else
1204                                 ldlm_add_waiting_lock(lock);
1205                 }
1206         }
1207         /* Make sure we never ever grant usual metadata locks to liblustre
1208            clients */
1209         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1210             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1211              req->rq_export->exp_libclient) {
1212                 if (unlikely(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
1213                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
1214                         CERROR("Granting sync lock to libclient. "
1215                                "req fl %d, rep fl %d, lock fl "LPX64"\n",
1216                                dlm_req->lock_flags, dlm_rep->lock_flags,
1217                                lock->l_flags);
1218                         LDLM_ERROR(lock, "sync lock");
1219                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1220                                 struct ldlm_intent *it;
1221
1222                                 it = req_capsule_client_get(&req->rq_pill,
1223                                                             &RMF_LDLM_INTENT);
1224                                 if (it != NULL) {
1225                                         CERROR("This is intent %s ("LPU64")\n",
1226                                                ldlm_it2str(it->opc), it->opc);
1227                                 }
1228                         }
1229                 }
1230         }
1231
1232         unlock_res_and_lock(lock);
1233
1234         EXIT;
1235  out:
1236         req->rq_status = rc ?: err; /* return either error - bug 11190 */
1237         if (!req->rq_packed_final) {
1238                 err = lustre_pack_reply(req, 1, NULL, NULL);
1239                 if (rc == 0)
1240                         rc = err;
1241         }
1242
1243         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1244          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1245         if (lock) {
1246                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1247                            "(err=%d, rc=%d)", err, rc);
1248
1249                 lock_res_and_lock(lock);
1250                 if (rc == 0) {
1251                         if (lock->l_resource->lr_lvb_len > 0) {
1252                                 void *lvb;
1253
1254                                 lvb = req_capsule_server_get(&req->rq_pill,
1255                                                              &RMF_DLM_LVB);
1256                                 LASSERTF(lvb != NULL, "req %p, lock %p\n",
1257                                          req, lock);
1258
1259                                 memcpy(lvb, lock->l_resource->lr_lvb_data,
1260                                        lock->l_resource->lr_lvb_len);
1261                         }
1262                 } else {
1263                         ldlm_resource_unlink_lock(lock);
1264                         ldlm_lock_destroy_nolock(lock);
1265                 }
1266                 unlock_res_and_lock(lock);
1267
1268                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1269                         ldlm_reprocess_all(lock->l_resource);
1270
1271                 LDLM_LOCK_RELEASE(lock);
1272         }
1273
1274         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1275                           lock, rc);
1276
1277         return rc;
1278 }
1279
1280 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1281                         ldlm_completion_callback completion_callback,
1282                         ldlm_blocking_callback blocking_callback,
1283                         ldlm_glimpse_callback glimpse_callback)
1284 {
1285         struct ldlm_request *dlm_req;
1286         struct ldlm_callback_suite cbs = {
1287                 .lcs_completion = completion_callback,
1288                 .lcs_blocking   = blocking_callback,
1289                 .lcs_glimpse    = glimpse_callback
1290         };
1291         int rc;
1292
1293         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1294         if (dlm_req != NULL) {
1295                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1296                                           req, dlm_req, &cbs);
1297         } else {
1298                 rc = -EFAULT;
1299         }
1300         return rc;
1301 }
1302
1303 int ldlm_handle_convert0(struct ptlrpc_request *req,
1304                          const struct ldlm_request *dlm_req)
1305 {
1306         struct ldlm_reply *dlm_rep;
1307         struct ldlm_lock *lock;
1308         int rc;
1309         ENTRY;
1310
1311         if (req->rq_export && req->rq_export->exp_nid_stats &&
1312             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1313                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1314                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1315
1316         rc = req_capsule_server_pack(&req->rq_pill);
1317         if (rc)
1318                 RETURN(rc);
1319
1320         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1321         dlm_rep->lock_flags = dlm_req->lock_flags;
1322
1323         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1324         if (!lock) {
1325                 req->rq_status = EINVAL;
1326         } else {
1327                 void *res = NULL;
1328
1329                 LDLM_DEBUG(lock, "server-side convert handler START");
1330
1331                 lock->l_last_activity = cfs_time_current_sec();
1332                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1333                                         &dlm_rep->lock_flags);
1334                 if (res) {
1335                         if (ldlm_del_waiting_lock(lock))
1336                                 LDLM_DEBUG(lock, "converted waiting lock");
1337                         req->rq_status = 0;
1338                 } else {
1339                         req->rq_status = EDEADLOCK;
1340                 }
1341         }
1342
1343         if (lock) {
1344                 if (!req->rq_status)
1345                         ldlm_reprocess_all(lock->l_resource);
1346                 LDLM_DEBUG(lock, "server-side convert handler END");
1347                 LDLM_LOCK_PUT(lock);
1348         } else
1349                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1350
1351         RETURN(0);
1352 }
1353
1354 int ldlm_handle_convert(struct ptlrpc_request *req)
1355 {
1356         int rc;
1357         struct ldlm_request *dlm_req;
1358
1359         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1360         if (dlm_req != NULL) {
1361                 rc = ldlm_handle_convert0(req, dlm_req);
1362         } else {
1363                 CERROR ("Can't unpack dlm_req\n");
1364                 rc = -EFAULT;
1365         }
1366         return rc;
1367 }
1368
1369 /* Cancel all the locks whos handles are packed into ldlm_request */
1370 int ldlm_request_cancel(struct ptlrpc_request *req,
1371                         const struct ldlm_request *dlm_req, int first)
1372 {
1373         struct ldlm_resource *res, *pres = NULL;
1374         struct ldlm_lock *lock;
1375         int i, count, done = 0;
1376         ENTRY;
1377
1378         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1379         if (first >= count)
1380                 RETURN(0);
1381
1382         /* There is no lock on the server at the replay time,
1383          * skip lock cancelling to make replay tests to pass. */
1384         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1385                 RETURN(0);
1386
1387         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1388                           "starting at %d", count, first);
1389
1390         for (i = first; i < count; i++) {
1391                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1392                 if (!lock) {
1393                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1394                                           "lock (cookie "LPU64")",
1395                                           dlm_req->lock_handle[i].cookie);
1396                         continue;
1397                 }
1398
1399                 res = lock->l_resource;
1400                 done++;
1401
1402                 if (res != pres) {
1403                         if (pres != NULL) {
1404                                 ldlm_reprocess_all(pres);
1405                                 LDLM_RESOURCE_DELREF(pres);
1406                                 ldlm_resource_putref(pres);
1407                         }
1408                         if (res != NULL) {
1409                                 ldlm_resource_getref(res);
1410                                 LDLM_RESOURCE_ADDREF(res);
1411                                 ldlm_res_lvbo_update(res, NULL, 1);
1412                         }
1413                         pres = res;
1414                 }
1415                 ldlm_lock_cancel(lock);
1416                 LDLM_LOCK_PUT(lock);
1417         }
1418         if (pres != NULL) {
1419                 ldlm_reprocess_all(pres);
1420                 LDLM_RESOURCE_DELREF(pres);
1421                 ldlm_resource_putref(pres);
1422         }
1423         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1424         RETURN(done);
1425 }
1426
1427 int ldlm_handle_cancel(struct ptlrpc_request *req)
1428 {
1429         struct ldlm_request *dlm_req;
1430         int rc;
1431         ENTRY;
1432
1433         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1434         if (dlm_req == NULL) {
1435                 CDEBUG(D_INFO, "bad request buffer for cancel\n");
1436                 RETURN(-EFAULT);
1437         }
1438
1439         if (req->rq_export && req->rq_export->exp_nid_stats &&
1440             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1441                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1442                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1443
1444         rc = req_capsule_server_pack(&req->rq_pill);
1445         if (rc)
1446                 RETURN(rc);
1447
1448         if (!ldlm_request_cancel(req, dlm_req, 0))
1449                 req->rq_status = ESTALE;
1450
1451         if (ptlrpc_reply(req) != 0)
1452                 LBUG();
1453
1454         RETURN(0);
1455 }
1456
1457 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1458                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1459 {
1460         int do_ast;
1461         ENTRY;
1462
1463         LDLM_DEBUG(lock, "client blocking AST callback handler");
1464
1465         lock_res_and_lock(lock);
1466         lock->l_flags |= LDLM_FL_CBPENDING;
1467
1468         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1469                 lock->l_flags |= LDLM_FL_CANCEL;
1470
1471         do_ast = (!lock->l_readers && !lock->l_writers);
1472         unlock_res_and_lock(lock);
1473
1474         if (do_ast) {
1475                 CDEBUG(D_DLMTRACE, "Lock %p already unused, calling callback (%p)\n",
1476                        lock, lock->l_blocking_ast);
1477                 if (lock->l_blocking_ast != NULL)
1478                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1479                                              LDLM_CB_BLOCKING);
1480         } else {
1481                 CDEBUG(D_DLMTRACE, "Lock %p is referenced, will be cancelled later\n",
1482                        lock);
1483         }
1484
1485         LDLM_DEBUG(lock, "client blocking callback handler END");
1486         LDLM_LOCK_RELEASE(lock);
1487         EXIT;
1488 }
1489
1490 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1491                                     struct ldlm_namespace *ns,
1492                                     struct ldlm_request *dlm_req,
1493                                     struct ldlm_lock *lock)
1494 {
1495         CFS_LIST_HEAD(ast_list);
1496         ENTRY;
1497
1498         LDLM_DEBUG(lock, "client completion callback handler START");
1499
1500         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE)) {
1501                 int to = cfs_time_seconds(1);
1502                 while (to > 0) {
1503                         cfs_schedule_timeout_and_set_state(
1504                                 CFS_TASK_INTERRUPTIBLE, to);
1505                         if (lock->l_granted_mode == lock->l_req_mode ||
1506                             lock->l_destroyed)
1507                                 break;
1508                 }
1509         }
1510
1511         lock_res_and_lock(lock);
1512         if (lock->l_destroyed ||
1513             lock->l_granted_mode == lock->l_req_mode) {
1514                 /* bug 11300: the lock has already been granted */
1515                 unlock_res_and_lock(lock);
1516                 LDLM_DEBUG(lock, "Double grant race happened");
1517                 LDLM_LOCK_RELEASE(lock);
1518                 EXIT;
1519                 return;
1520         }
1521
1522         /* If we receive the completion AST before the actual enqueue returned,
1523          * then we might need to switch lock modes, resources, or extents. */
1524         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1525                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1526                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1527         }
1528
1529         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1530                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1531                 LDLM_DEBUG(lock, "completion AST, new policy data");
1532         }
1533
1534         ldlm_resource_unlink_lock(lock);
1535         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1536                    &lock->l_resource->lr_name,
1537                    sizeof(lock->l_resource->lr_name)) != 0) {
1538                 unlock_res_and_lock(lock);
1539                 if (ldlm_lock_change_resource(ns, lock,
1540                                 &dlm_req->lock_desc.l_resource.lr_name) != 0) {
1541                         LDLM_ERROR(lock, "Failed to allocate resource");
1542                         LDLM_LOCK_RELEASE(lock);
1543                         EXIT;
1544                         return;
1545                 }
1546                 LDLM_DEBUG(lock, "completion AST, new resource");
1547                 CERROR("change resource!\n");
1548                 lock_res_and_lock(lock);
1549         }
1550
1551         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1552                 /* BL_AST locks are not needed in lru.
1553                  * let ldlm_cancel_lru() be fast. */
1554                 ldlm_lock_remove_from_lru(lock);
1555                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
1556                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1557         }
1558
1559         if (lock->l_lvb_len) {
1560                 if (req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB,
1561                                          RCL_CLIENT) < lock->l_lvb_len) {
1562                         LDLM_ERROR(lock, "completion AST did not contain "
1563                                    "expected LVB!");
1564                 } else {
1565                         void *lvb = req_capsule_client_get(&req->rq_pill,
1566                                                            &RMF_DLM_LVB);
1567                         memcpy(lock->l_lvb_data, lvb, lock->l_lvb_len);
1568                 }
1569         }
1570
1571         ldlm_grant_lock(lock, &ast_list);
1572         unlock_res_and_lock(lock);
1573
1574         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1575
1576         ldlm_run_ast_work(&ast_list, LDLM_WORK_CP_AST);
1577
1578         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1579                           lock);
1580         LDLM_LOCK_RELEASE(lock);
1581         EXIT;
1582 }
1583
1584 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1585                                     struct ldlm_namespace *ns,
1586                                     struct ldlm_request *dlm_req,
1587                                     struct ldlm_lock *lock)
1588 {
1589         int rc = -ENOSYS;
1590         ENTRY;
1591
1592         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1593
1594         if (lock->l_glimpse_ast != NULL)
1595                 rc = lock->l_glimpse_ast(lock, req);
1596
1597         if (req->rq_repmsg != NULL) {
1598                 ptlrpc_reply(req);
1599         } else {
1600                 req->rq_status = rc;
1601                 ptlrpc_error(req);
1602         }
1603
1604         lock_res_and_lock(lock);
1605         if (lock->l_granted_mode == LCK_PW &&
1606             !lock->l_readers && !lock->l_writers &&
1607             cfs_time_after(cfs_time_current(),
1608                            cfs_time_add(lock->l_last_used,
1609                                         cfs_time_seconds(10)))) {
1610                 unlock_res_and_lock(lock);
1611                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1612                         ldlm_handle_bl_callback(ns, NULL, lock);
1613
1614                 EXIT;
1615                 return;
1616         }
1617         unlock_res_and_lock(lock);
1618         LDLM_LOCK_RELEASE(lock);
1619         EXIT;
1620 }
1621
1622 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1623 {
1624         if (req->rq_no_reply)
1625                 return 0;
1626
1627         req->rq_status = rc;
1628         if (!req->rq_packed_final) {
1629                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1630                 if (rc)
1631                         return rc;
1632         }
1633         return ptlrpc_reply(req);
1634 }
1635
1636 #ifdef __KERNEL__
1637 static int __ldlm_bl_to_thread(struct ldlm_namespace *ns, struct ldlm_bl_work_item *blwi,
1638                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1639                              cfs_list_t *cancels, int count, int mode)
1640 {
1641         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1642         ENTRY;
1643
1644         if (cancels && count == 0) {
1645                 if (mode == LDLM_ASYNC)
1646                         OBD_FREE(blwi, sizeof(*blwi));
1647                 RETURN(0);
1648         }
1649
1650         cfs_init_completion(&blwi->blwi_comp);
1651         cfs_atomic_set(&blwi->blwi_ref_count, 1);
1652
1653         blwi->blwi_ns = ns;
1654         if (ld != NULL)
1655                 blwi->blwi_ld = *ld;
1656         if (count) {
1657                 cfs_list_add(&blwi->blwi_head, cancels);
1658                 cfs_list_del_init(cancels);
1659                 blwi->blwi_count = count;
1660         } else {
1661                 blwi->blwi_lock = lock;
1662         }
1663
1664         cfs_spin_lock(&blp->blp_lock);
1665         if (lock && lock->l_flags & LDLM_FL_DISCARD_DATA) {
1666                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1667                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1668         } else {
1669                 /* other blocking callbacks are added to the regular list */
1670                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1671         }
1672         cfs_spin_unlock(&blp->blp_lock);
1673
1674         if (mode == LDLM_SYNC) {
1675                 /* keep ref count as object is on this stack for SYNC call */
1676                 ldlm_bl_work_item_get(blwi);
1677                 cfs_waitq_signal(&blp->blp_waitq);
1678                 cfs_wait_for_completion(&blwi->blwi_comp);
1679         } else {
1680                 cfs_waitq_signal(&blp->blp_waitq);
1681         }
1682
1683         RETURN(0);
1684 }
1685
1686 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1687                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1688                              struct list_head *cancels, int count, int mode)
1689 {
1690         ENTRY;
1691
1692         if (mode == LDLM_SYNC) {
1693                 /* if it is synchronous call do minimum mem alloc, as it could
1694                  * be triggered from kernel shrinker
1695                  */
1696                 struct ldlm_bl_work_item blwi;
1697                 memset(&blwi, 0, sizeof(blwi));
1698                 /* have extra ref as this obj is on stack */
1699                 RETURN(__ldlm_bl_to_thread(ns, &blwi, ld, lock, cancels, count, mode));
1700         } else {
1701                 struct ldlm_bl_work_item *blwi;
1702                 OBD_ALLOC(blwi, sizeof(*blwi));
1703                 if (blwi == NULL)
1704                         RETURN(-ENOMEM);
1705
1706                 RETURN(__ldlm_bl_to_thread(ns, blwi, ld, lock, cancels, count, mode));
1707         }
1708 }
1709
1710 #endif
1711
1712 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1713                            struct ldlm_lock *lock)
1714 {
1715 #ifdef __KERNEL__
1716         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0, LDLM_ASYNC));
1717 #else
1718         RETURN(-ENOSYS);
1719 #endif
1720 }
1721
1722 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1723                            cfs_list_t *cancels, int count, int mode)
1724 {
1725 #ifdef __KERNEL__
1726         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count, mode));
1727 #else
1728         RETURN(-ENOSYS);
1729 #endif
1730 }
1731
1732 /* Setinfo coming from Server (eg MDT) to Client (eg MDC)! */
1733 static int ldlm_handle_setinfo(struct ptlrpc_request *req)
1734 {
1735         struct obd_device *obd = req->rq_export->exp_obd;
1736         char *key;
1737         void *val;
1738         int keylen, vallen;
1739         int rc = -ENOSYS;
1740         ENTRY;
1741
1742         DEBUG_REQ(D_HSM, req, "%s: handle setinfo\n", obd->obd_name);
1743
1744         req_capsule_set(&req->rq_pill, &RQF_OBD_SET_INFO);
1745
1746         key = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_KEY);
1747         if (key == NULL) {
1748                 DEBUG_REQ(D_IOCTL, req, "no set_info key");
1749                 RETURN(-EFAULT);
1750         }
1751         keylen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_KEY,
1752                                       RCL_CLIENT);
1753         val = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_VAL);
1754         if (val == NULL) {
1755                 DEBUG_REQ(D_IOCTL, req, "no set_info val");
1756                 RETURN(-EFAULT);
1757         }
1758         vallen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_VAL,
1759                                       RCL_CLIENT);
1760
1761         /* We are responsible for swabbing contents of val */
1762
1763         if (KEY_IS(KEY_HSM_COPYTOOL_SEND))
1764                 /* Pass it on to mdc (the "export" in this case) */
1765                 rc = obd_set_info_async(req->rq_export,
1766                                         sizeof(KEY_HSM_COPYTOOL_SEND),
1767                                         KEY_HSM_COPYTOOL_SEND,
1768                                         vallen, val, NULL);
1769         else
1770                 DEBUG_REQ(D_WARNING, req, "ignoring unknown key %s", key);
1771
1772         return rc;
1773 }
1774
1775 static inline void ldlm_callback_errmsg(struct ptlrpc_request *req,
1776                                         const char *msg, int rc,
1777                                         struct lustre_handle *handle)
1778 {
1779         DEBUG_REQ((req->rq_no_reply || rc) ? D_WARNING : D_DLMTRACE, req,
1780                   "%s: [nid %s] [rc %d] [lock "LPX64"]",
1781                   msg, libcfs_id2str(req->rq_peer), rc,
1782                   handle ? handle->cookie : 0);
1783         if (req->rq_no_reply)
1784                 CWARN("No reply was sent, maybe cause bug 21636.\n");
1785         else if (rc)
1786                 CWARN("Send reply failed, maybe cause bug 21636.\n");
1787 }
1788
1789 /* TODO: handle requests in a similar way as MDT: see mdt_handle_common() */
1790 static int ldlm_callback_handler(struct ptlrpc_request *req)
1791 {
1792         struct ldlm_namespace *ns;
1793         struct ldlm_request *dlm_req;
1794         struct ldlm_lock *lock;
1795         int rc;
1796         ENTRY;
1797
1798         /* Requests arrive in sender's byte order.  The ptlrpc service
1799          * handler has already checked and, if necessary, byte-swapped the
1800          * incoming request message body, but I am responsible for the
1801          * message buffers. */
1802
1803         /* do nothing for sec context finalize */
1804         if (lustre_msg_get_opc(req->rq_reqmsg) == SEC_CTX_FINI)
1805                 RETURN(0);
1806
1807         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
1808
1809         if (req->rq_export == NULL) {
1810                 rc = ldlm_callback_reply(req, -ENOTCONN);
1811                 ldlm_callback_errmsg(req, "Operate on unconnected server",
1812                                      rc, NULL);
1813                 RETURN(0);
1814         }
1815
1816         LASSERT(req->rq_export != NULL);
1817         LASSERT(req->rq_export->exp_obd != NULL);
1818
1819         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1820         case LDLM_BL_CALLBACK:
1821                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_BL_CALLBACK))
1822                         RETURN(0);
1823                 break;
1824         case LDLM_CP_CALLBACK:
1825                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CP_CALLBACK))
1826                         RETURN(0);
1827                 break;
1828         case LDLM_GL_CALLBACK:
1829                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_GL_CALLBACK))
1830                         RETURN(0);
1831                 break;
1832         case LDLM_SET_INFO:
1833                 rc = ldlm_handle_setinfo(req);
1834                 ldlm_callback_reply(req, rc);
1835                 RETURN(0);
1836         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
1837                 CERROR("shouldn't be handling OBD_LOG_CANCEL on DLM thread\n");
1838                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
1839                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
1840                         RETURN(0);
1841                 rc = llog_origin_handle_cancel(req);
1842                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
1843                         RETURN(0);
1844                 ldlm_callback_reply(req, rc);
1845                 RETURN(0);
1846         case OBD_QC_CALLBACK:
1847                 req_capsule_set(&req->rq_pill, &RQF_QC_CALLBACK);
1848                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_QC_CALLBACK_NET))
1849                         RETURN(0);
1850                 rc = target_handle_qc_callback(req);
1851                 ldlm_callback_reply(req, rc);
1852                 RETURN(0);
1853         case QUOTA_DQACQ:
1854         case QUOTA_DQREL:
1855                 /* reply in handler */
1856                 req_capsule_set(&req->rq_pill, &RQF_MDS_QUOTA_DQACQ);
1857                 rc = target_handle_dqacq_callback(req);
1858                 RETURN(0);
1859         case LLOG_ORIGIN_HANDLE_CREATE:
1860                 req_capsule_set(&req->rq_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
1861                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1862                         RETURN(0);
1863                 rc = llog_origin_handle_create(req);
1864                 ldlm_callback_reply(req, rc);
1865                 RETURN(0);
1866         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
1867                 req_capsule_set(&req->rq_pill,
1868                                 &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
1869                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1870                         RETURN(0);
1871                 rc = llog_origin_handle_next_block(req);
1872                 ldlm_callback_reply(req, rc);
1873                 RETURN(0);
1874         case LLOG_ORIGIN_HANDLE_READ_HEADER:
1875                 req_capsule_set(&req->rq_pill,
1876                                 &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
1877                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1878                         RETURN(0);
1879                 rc = llog_origin_handle_read_header(req);
1880                 ldlm_callback_reply(req, rc);
1881                 RETURN(0);
1882         case LLOG_ORIGIN_HANDLE_CLOSE:
1883                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1884                         RETURN(0);
1885                 rc = llog_origin_handle_close(req);
1886                 ldlm_callback_reply(req, rc);
1887                 RETURN(0);
1888         default:
1889                 CERROR("unknown opcode %u\n",
1890                        lustre_msg_get_opc(req->rq_reqmsg));
1891                 ldlm_callback_reply(req, -EPROTO);
1892                 RETURN(0);
1893         }
1894
1895         ns = req->rq_export->exp_obd->obd_namespace;
1896         LASSERT(ns != NULL);
1897
1898         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
1899
1900         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1901         if (dlm_req == NULL) {
1902                 rc = ldlm_callback_reply(req, -EPROTO);
1903                 ldlm_callback_errmsg(req, "Operate without parameter", rc,
1904                                      NULL);
1905                 RETURN(0);
1906         }
1907
1908         /* Force a known safe race, send a cancel to the server for a lock
1909          * which the server has already started a blocking callback on. */
1910         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
1911             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1912                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0]);
1913                 if (rc < 0)
1914                         CERROR("ldlm_cli_cancel: %d\n", rc);
1915         }
1916
1917         lock = ldlm_handle2lock_long(&dlm_req->lock_handle[0], 0);
1918         if (!lock) {
1919                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
1920                        "disappeared\n", dlm_req->lock_handle[0].cookie);
1921                 rc = ldlm_callback_reply(req, -EINVAL);
1922                 ldlm_callback_errmsg(req, "Operate with invalid parameter", rc,
1923                                      &dlm_req->lock_handle[0]);
1924                 RETURN(0);
1925         }
1926
1927         if ((lock->l_flags & LDLM_FL_FAIL_LOC) &&
1928             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK)
1929                 OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
1930
1931         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
1932         lock_res_and_lock(lock);
1933         lock->l_flags |= (dlm_req->lock_flags & LDLM_AST_FLAGS);
1934         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1935                 /* If somebody cancels lock and cache is already dropped,
1936                  * or lock is failed before cp_ast received on client,
1937                  * we can tell the server we have no lock. Otherwise, we
1938                  * should send cancel after dropping the cache. */
1939                 if (((lock->l_flags & LDLM_FL_CANCELING) &&
1940                     (lock->l_flags & LDLM_FL_BL_DONE)) ||
1941                     (lock->l_flags & LDLM_FL_FAILED)) {
1942                         LDLM_DEBUG(lock, "callback on lock "
1943                                    LPX64" - lock disappeared\n",
1944                                    dlm_req->lock_handle[0].cookie);
1945                         unlock_res_and_lock(lock);
1946                         LDLM_LOCK_RELEASE(lock);
1947                         rc = ldlm_callback_reply(req, -EINVAL);
1948                         ldlm_callback_errmsg(req, "Operate on stale lock", rc,
1949                                              &dlm_req->lock_handle[0]);
1950                         RETURN(0);
1951                 }
1952                 /* BL_AST locks are not needed in lru.
1953                  * let ldlm_cancel_lru() be fast. */
1954                 ldlm_lock_remove_from_lru(lock);
1955                 lock->l_flags |= LDLM_FL_BL_AST;
1956         }
1957         unlock_res_and_lock(lock);
1958
1959         /* We want the ost thread to get this reply so that it can respond
1960          * to ost requests (write cache writeback) that might be triggered
1961          * in the callback.
1962          *
1963          * But we'd also like to be able to indicate in the reply that we're
1964          * cancelling right now, because it's unused, or have an intent result
1965          * in the reply, so we might have to push the responsibility for sending
1966          * the reply down into the AST handlers, alas. */
1967
1968         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1969         case LDLM_BL_CALLBACK:
1970                 CDEBUG(D_INODE, "blocking ast\n");
1971                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_BL_CALLBACK);
1972                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)) {
1973                         rc = ldlm_callback_reply(req, 0);
1974                         if (req->rq_no_reply || rc)
1975                                 ldlm_callback_errmsg(req, "Normal process", rc,
1976                                                      &dlm_req->lock_handle[0]);
1977                 }
1978                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
1979                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
1980                 break;
1981         case LDLM_CP_CALLBACK:
1982                 CDEBUG(D_INODE, "completion ast\n");
1983                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_CP_CALLBACK);
1984                 ldlm_callback_reply(req, 0);
1985                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
1986                 break;
1987         case LDLM_GL_CALLBACK:
1988                 CDEBUG(D_INODE, "glimpse ast\n");
1989                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_GL_CALLBACK);
1990                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
1991                 break;
1992         default:
1993                 LBUG();                         /* checked above */
1994         }
1995
1996         RETURN(0);
1997 }
1998
1999 static int ldlm_cancel_handler(struct ptlrpc_request *req)
2000 {
2001         int rc;
2002         ENTRY;
2003
2004         /* Requests arrive in sender's byte order.  The ptlrpc service
2005          * handler has already checked and, if necessary, byte-swapped the
2006          * incoming request message body, but I am responsible for the
2007          * message buffers. */
2008
2009         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2010
2011         if (req->rq_export == NULL) {
2012                 struct ldlm_request *dlm_req;
2013
2014                 CERROR("operation %d from %s with bad export cookie "LPU64"\n",
2015                        lustre_msg_get_opc(req->rq_reqmsg),
2016                        libcfs_id2str(req->rq_peer),
2017                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
2018
2019                 if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_CANCEL) {
2020                         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2021                         dlm_req = req_capsule_client_get(&req->rq_pill,
2022                                                          &RMF_DLM_REQ);
2023                         if (dlm_req != NULL)
2024                                 ldlm_lock_dump_handle(D_ERROR,
2025                                                       &dlm_req->lock_handle[0]);
2026                 }
2027                 ldlm_callback_reply(req, -ENOTCONN);
2028                 RETURN(0);
2029         }
2030
2031         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2032
2033         /* XXX FIXME move this back to mds/handler.c, bug 249 */
2034         case LDLM_CANCEL:
2035                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2036                 CDEBUG(D_INODE, "cancel\n");
2037                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL))
2038                         RETURN(0);
2039                 rc = ldlm_handle_cancel(req);
2040                 if (rc)
2041                         break;
2042                 RETURN(0);
2043         case OBD_LOG_CANCEL:
2044                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
2045                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
2046                         RETURN(0);
2047                 rc = llog_origin_handle_cancel(req);
2048                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
2049                         RETURN(0);
2050                 ldlm_callback_reply(req, rc);
2051                 RETURN(0);
2052         default:
2053                 CERROR("invalid opcode %d\n",
2054                        lustre_msg_get_opc(req->rq_reqmsg));
2055                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2056                 ldlm_callback_reply(req, -EINVAL);
2057         }
2058
2059         RETURN(0);
2060 }
2061
2062 void ldlm_revoke_lock_cb(void *obj, void *data)
2063 {
2064         cfs_list_t         *rpc_list = data;
2065         struct ldlm_lock   *lock = obj;
2066
2067         lock_res_and_lock(lock);
2068
2069         if (lock->l_req_mode != lock->l_granted_mode) {
2070                 unlock_res_and_lock(lock);
2071                 return;
2072         }
2073
2074         LASSERT(lock->l_resource);
2075         if (lock->l_resource->lr_type != LDLM_IBITS &&
2076             lock->l_resource->lr_type != LDLM_PLAIN) {
2077                 unlock_res_and_lock(lock);
2078                 return;
2079         }
2080
2081         if (lock->l_flags & LDLM_FL_AST_SENT) {
2082                 unlock_res_and_lock(lock);
2083                 return;
2084         }
2085
2086         LASSERT(lock->l_blocking_ast);
2087         LASSERT(!lock->l_blocking_lock);
2088
2089         lock->l_flags |= LDLM_FL_AST_SENT;
2090         if (lock->l_export && lock->l_export->exp_lock_hash &&
2091             !cfs_hlist_unhashed(&lock->l_exp_hash))
2092                 cfs_hash_del(lock->l_export->exp_lock_hash,
2093                              &lock->l_remote_handle, &lock->l_exp_hash);
2094         cfs_list_add_tail(&lock->l_rk_ast, rpc_list);
2095         LDLM_LOCK_GET(lock);
2096
2097         unlock_res_and_lock(lock);
2098 }
2099
2100 void ldlm_revoke_export_locks(struct obd_export *exp)
2101 {
2102         cfs_list_t  rpc_list;
2103         ENTRY;
2104
2105         CFS_INIT_LIST_HEAD(&rpc_list);
2106         cfs_hash_for_each_empty(exp->exp_lock_hash,
2107                                 ldlm_revoke_lock_cb, &rpc_list);
2108         ldlm_run_ast_work(&rpc_list, LDLM_WORK_REVOKE_AST);
2109
2110         EXIT;
2111 }
2112
2113 #ifdef __KERNEL__
2114 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
2115 {
2116         struct ldlm_bl_work_item *blwi = NULL;
2117         static unsigned int num_bl = 0;
2118
2119         cfs_spin_lock(&blp->blp_lock);
2120         /* process a request from the blp_list at least every blp_num_threads */
2121         if (!cfs_list_empty(&blp->blp_list) &&
2122             (cfs_list_empty(&blp->blp_prio_list) || num_bl == 0))
2123                 blwi = cfs_list_entry(blp->blp_list.next,
2124                                       struct ldlm_bl_work_item, blwi_entry);
2125         else
2126                 if (!cfs_list_empty(&blp->blp_prio_list))
2127                         blwi = cfs_list_entry(blp->blp_prio_list.next,
2128                                               struct ldlm_bl_work_item,
2129                                               blwi_entry);
2130
2131         if (blwi) {
2132                 if (++num_bl >= cfs_atomic_read(&blp->blp_num_threads))
2133                         num_bl = 0;
2134                 cfs_list_del(&blwi->blwi_entry);
2135         }
2136         cfs_spin_unlock(&blp->blp_lock);
2137
2138         return blwi;
2139 }
2140
2141 /* This only contains temporary data until the thread starts */
2142 struct ldlm_bl_thread_data {
2143         char                    bltd_name[CFS_CURPROC_COMM_MAX];
2144         struct ldlm_bl_pool     *bltd_blp;
2145         cfs_completion_t        bltd_comp;
2146         int                     bltd_num;
2147 };
2148
2149 static int ldlm_bl_thread_main(void *arg);
2150
2151 static int ldlm_bl_thread_start(struct ldlm_bl_pool *blp)
2152 {
2153         struct ldlm_bl_thread_data bltd = { .bltd_blp = blp };
2154         int rc;
2155
2156         cfs_init_completion(&bltd.bltd_comp);
2157         rc = cfs_kernel_thread(ldlm_bl_thread_main, &bltd, 0);
2158         if (rc < 0) {
2159                 CERROR("cannot start LDLM thread ldlm_bl_%02d: rc %d\n",
2160                        cfs_atomic_read(&blp->blp_num_threads), rc);
2161                 return rc;
2162         }
2163         cfs_wait_for_completion(&bltd.bltd_comp);
2164
2165         return 0;
2166 }
2167
2168 static int ldlm_bl_thread_main(void *arg)
2169 {
2170         struct ldlm_bl_pool *blp;
2171         ENTRY;
2172
2173         {
2174                 struct ldlm_bl_thread_data *bltd = arg;
2175
2176                 blp = bltd->bltd_blp;
2177
2178                 bltd->bltd_num =
2179                         cfs_atomic_inc_return(&blp->blp_num_threads) - 1;
2180                 cfs_atomic_inc(&blp->blp_busy_threads);
2181
2182                 snprintf(bltd->bltd_name, sizeof(bltd->bltd_name) - 1,
2183                         "ldlm_bl_%02d", bltd->bltd_num);
2184                 cfs_daemonize(bltd->bltd_name);
2185
2186                 cfs_complete(&bltd->bltd_comp);
2187                 /* cannot use bltd after this, it is only on caller's stack */
2188         }
2189
2190         while (1) {
2191                 struct l_wait_info lwi = { 0 };
2192                 struct ldlm_bl_work_item *blwi = NULL;
2193
2194                 blwi = ldlm_bl_get_work(blp);
2195
2196                 if (blwi == NULL) {
2197                         int busy;
2198
2199                         cfs_atomic_dec(&blp->blp_busy_threads);
2200                         l_wait_event_exclusive(blp->blp_waitq,
2201                                          (blwi = ldlm_bl_get_work(blp)) != NULL,
2202                                          &lwi);
2203                         busy = cfs_atomic_inc_return(&blp->blp_busy_threads);
2204
2205                         if (blwi->blwi_ns == NULL)
2206                                 /* added by ldlm_cleanup() */
2207                                 break;
2208
2209                         /* Not fatal if racy and have a few too many threads */
2210                         if (unlikely(busy < blp->blp_max_threads &&
2211                             busy >= cfs_atomic_read(&blp->blp_num_threads)))
2212                                 /* discard the return value, we tried */
2213                                 ldlm_bl_thread_start(blp);
2214                 } else {
2215                         if (blwi->blwi_ns == NULL)
2216                                 /* added by ldlm_cleanup() */
2217                                 break;
2218                 }
2219
2220                 if (blwi->blwi_count) {
2221                         /* The special case when we cancel locks in lru
2222                          * asynchronously, we pass the list of locks here.
2223                          * Thus lock is marked LDLM_FL_CANCELING, and already
2224                          * canceled locally. */
2225                         ldlm_cli_cancel_list(&blwi->blwi_head,
2226                                              blwi->blwi_count, NULL, 0);
2227                 } else {
2228                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
2229                                                 blwi->blwi_lock);
2230                 }
2231                 cfs_complete(&blwi->blwi_comp);
2232                 ldlm_bl_work_item_put(blwi);
2233         }
2234
2235         cfs_atomic_dec(&blp->blp_busy_threads);
2236         cfs_atomic_dec(&blp->blp_num_threads);
2237         cfs_complete(&blp->blp_comp);
2238         RETURN(0);
2239 }
2240
2241 #endif
2242
2243 static int ldlm_setup(void);
2244 static int ldlm_cleanup(void);
2245
2246 int ldlm_get_ref(void)
2247 {
2248         int rc = 0;
2249         ENTRY;
2250         cfs_mutex_down(&ldlm_ref_sem);
2251         if (++ldlm_refcount == 1) {
2252                 rc = ldlm_setup();
2253                 if (rc)
2254                         ldlm_refcount--;
2255         }
2256         cfs_mutex_up(&ldlm_ref_sem);
2257
2258         RETURN(rc);
2259 }
2260
2261 void ldlm_put_ref(void)
2262 {
2263         ENTRY;
2264         cfs_mutex_down(&ldlm_ref_sem);
2265         if (ldlm_refcount == 1) {
2266                 int rc = ldlm_cleanup();
2267                 if (rc)
2268                         CERROR("ldlm_cleanup failed: %d\n", rc);
2269                 else
2270                         ldlm_refcount--;
2271         } else {
2272                 ldlm_refcount--;
2273         }
2274         cfs_mutex_up(&ldlm_ref_sem);
2275
2276         EXIT;
2277 }
2278
2279 /*
2280  * Export handle<->lock hash operations.
2281  */
2282 static unsigned
2283 ldlm_export_lock_hash(cfs_hash_t *hs, void *key, unsigned mask)
2284 {
2285         return cfs_hash_u64_hash(((struct lustre_handle *)key)->cookie, mask);
2286 }
2287
2288 static void *
2289 ldlm_export_lock_key(cfs_hlist_node_t *hnode)
2290 {
2291         struct ldlm_lock *lock;
2292         ENTRY;
2293
2294         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2295         RETURN(&lock->l_remote_handle);
2296 }
2297
2298 static int
2299 ldlm_export_lock_compare(void *key, cfs_hlist_node_t *hnode)
2300 {
2301         ENTRY;
2302         RETURN(lustre_handle_equal(ldlm_export_lock_key(hnode), key));
2303 }
2304
2305 static void *
2306 ldlm_export_lock_get(cfs_hlist_node_t *hnode)
2307 {
2308         struct ldlm_lock *lock;
2309         ENTRY;
2310
2311         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2312         LDLM_LOCK_GET(lock);
2313
2314         RETURN(lock);
2315 }
2316
2317 static void *
2318 ldlm_export_lock_put(cfs_hlist_node_t *hnode)
2319 {
2320         struct ldlm_lock *lock;
2321         ENTRY;
2322
2323         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2324         LDLM_LOCK_RELEASE(lock);
2325
2326         RETURN(lock);
2327 }
2328
2329 static cfs_hash_ops_t ldlm_export_lock_ops = {
2330         .hs_hash    = ldlm_export_lock_hash,
2331         .hs_key     = ldlm_export_lock_key,
2332         .hs_compare = ldlm_export_lock_compare,
2333         .hs_get     = ldlm_export_lock_get,
2334         .hs_put     = ldlm_export_lock_put
2335 };
2336
2337 int ldlm_init_export(struct obd_export *exp)
2338 {
2339         ENTRY;
2340
2341         exp->exp_lock_hash =
2342                 cfs_hash_create(obd_uuid2str(&exp->exp_client_uuid),
2343                                 HASH_EXP_LOCK_CUR_BITS, HASH_EXP_LOCK_MAX_BITS,
2344                                 &ldlm_export_lock_ops, CFS_HASH_REHASH);
2345
2346         if (!exp->exp_lock_hash)
2347                 RETURN(-ENOMEM);
2348
2349         RETURN(0);
2350 }
2351 EXPORT_SYMBOL(ldlm_init_export);
2352
2353 void ldlm_destroy_export(struct obd_export *exp)
2354 {
2355         ENTRY;
2356         cfs_hash_putref(exp->exp_lock_hash);
2357         exp->exp_lock_hash = NULL;
2358         EXIT;
2359 }
2360 EXPORT_SYMBOL(ldlm_destroy_export);
2361
2362 static int ldlm_setup(void)
2363 {
2364         struct ldlm_bl_pool *blp;
2365         int rc = 0;
2366         int ldlm_min_threads = LDLM_THREADS_AUTO_MIN;
2367         int ldlm_max_threads = LDLM_THREADS_AUTO_MAX;
2368 #ifdef __KERNEL__
2369         int i;
2370 #endif
2371         ENTRY;
2372
2373         if (ldlm_state != NULL)
2374                 RETURN(-EALREADY);
2375
2376         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
2377         if (ldlm_state == NULL)
2378                 RETURN(-ENOMEM);
2379
2380 #ifdef LPROCFS
2381         rc = ldlm_proc_setup();
2382         if (rc != 0)
2383                 GOTO(out_free, rc);
2384 #endif
2385
2386 #ifdef __KERNEL__
2387         if (ldlm_num_threads) {
2388                 /* If ldlm_num_threads is set, it is the min and the max. */
2389                 if (ldlm_num_threads > LDLM_THREADS_AUTO_MAX)
2390                         ldlm_num_threads = LDLM_THREADS_AUTO_MAX;
2391                 if (ldlm_num_threads < LDLM_THREADS_AUTO_MIN)
2392                         ldlm_num_threads = LDLM_THREADS_AUTO_MIN;
2393                 ldlm_min_threads = ldlm_max_threads = ldlm_num_threads;
2394         }
2395 #endif
2396
2397         ldlm_state->ldlm_cb_service =
2398                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
2399                                 LDLM_MAXREPSIZE, LDLM_CB_REQUEST_PORTAL,
2400                                 LDLM_CB_REPLY_PORTAL, 2,
2401                                 ldlm_callback_handler, "ldlm_cbd",
2402                                 ldlm_svc_proc_dir, NULL,
2403                                 ldlm_min_threads, ldlm_max_threads,
2404                                 "ldlm_cb",
2405                                 LCT_MD_THREAD|LCT_DT_THREAD, NULL);
2406
2407         if (!ldlm_state->ldlm_cb_service) {
2408                 CERROR("failed to start service\n");
2409                 GOTO(out_proc, rc = -ENOMEM);
2410         }
2411
2412         ldlm_state->ldlm_cancel_service =
2413                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
2414                                 LDLM_MAXREPSIZE, LDLM_CANCEL_REQUEST_PORTAL,
2415                                 LDLM_CANCEL_REPLY_PORTAL, 6,
2416                                 ldlm_cancel_handler, "ldlm_canceld",
2417                                 ldlm_svc_proc_dir, NULL,
2418                                 ldlm_min_threads, ldlm_max_threads,
2419                                 "ldlm_cn",
2420                                 LCT_MD_THREAD|LCT_DT_THREAD|LCT_CL_THREAD,
2421                                 NULL);
2422
2423         if (!ldlm_state->ldlm_cancel_service) {
2424                 CERROR("failed to start service\n");
2425                 GOTO(out_proc, rc = -ENOMEM);
2426         }
2427
2428         OBD_ALLOC(blp, sizeof(*blp));
2429         if (blp == NULL)
2430                 GOTO(out_proc, rc = -ENOMEM);
2431         ldlm_state->ldlm_bl_pool = blp;
2432
2433         cfs_spin_lock_init(&blp->blp_lock);
2434         CFS_INIT_LIST_HEAD(&blp->blp_list);
2435         CFS_INIT_LIST_HEAD(&blp->blp_prio_list);
2436         cfs_waitq_init(&blp->blp_waitq);
2437         cfs_atomic_set(&blp->blp_num_threads, 0);
2438         cfs_atomic_set(&blp->blp_busy_threads, 0);
2439         blp->blp_min_threads = ldlm_min_threads;
2440         blp->blp_max_threads = ldlm_max_threads;
2441
2442 #ifdef __KERNEL__
2443         for (i = 0; i < blp->blp_min_threads; i++) {
2444                 rc = ldlm_bl_thread_start(blp);
2445                 if (rc < 0)
2446                         GOTO(out_thread, rc);
2447         }
2448
2449         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cancel_service);
2450         if (rc)
2451                 GOTO(out_thread, rc);
2452
2453         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cb_service);
2454         if (rc)
2455                 GOTO(out_thread, rc);
2456
2457         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
2458         expired_lock_thread.elt_state = ELT_STOPPED;
2459         cfs_waitq_init(&expired_lock_thread.elt_waitq);
2460
2461         CFS_INIT_LIST_HEAD(&waiting_locks_list);
2462         cfs_spin_lock_init(&waiting_locks_spinlock);
2463         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
2464
2465         rc = cfs_kernel_thread(expired_lock_main, NULL, CLONE_VM | CLONE_FILES);
2466         if (rc < 0) {
2467                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
2468                 GOTO(out_thread, rc);
2469         }
2470
2471         cfs_wait_event(expired_lock_thread.elt_waitq,
2472                        expired_lock_thread.elt_state == ELT_READY);
2473 #endif
2474
2475 #ifdef __KERNEL__
2476         rc = ldlm_pools_init();
2477         if (rc)
2478                 GOTO(out_thread, rc);
2479 #endif
2480         RETURN(0);
2481
2482 #ifdef __KERNEL__
2483  out_thread:
2484         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2485         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2486 #endif
2487
2488  out_proc:
2489 #ifdef LPROCFS
2490         ldlm_proc_cleanup();
2491  out_free:
2492 #endif
2493         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2494         ldlm_state = NULL;
2495         return rc;
2496 }
2497
2498 static int ldlm_cleanup(void)
2499 {
2500 #ifdef __KERNEL__
2501         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
2502 #endif
2503         ENTRY;
2504
2505         if (!cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) ||
2506             !cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
2507                 CERROR("ldlm still has namespaces; clean these up first.\n");
2508                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
2509                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
2510                 RETURN(-EBUSY);
2511         }
2512
2513 #ifdef __KERNEL__
2514         ldlm_pools_fini();
2515 #endif
2516
2517 #ifdef __KERNEL__
2518         while (cfs_atomic_read(&blp->blp_num_threads) > 0) {
2519                 struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
2520
2521                 cfs_init_completion(&blp->blp_comp);
2522
2523                 cfs_spin_lock(&blp->blp_lock);
2524                 cfs_list_add_tail(&blwi.blwi_entry, &blp->blp_list);
2525                 cfs_waitq_signal(&blp->blp_waitq);
2526                 cfs_spin_unlock(&blp->blp_lock);
2527
2528                 cfs_wait_for_completion(&blp->blp_comp);
2529         }
2530         OBD_FREE(blp, sizeof(*blp));
2531
2532         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2533         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2534         ldlm_proc_cleanup();
2535
2536         expired_lock_thread.elt_state = ELT_TERMINATE;
2537         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
2538         cfs_wait_event(expired_lock_thread.elt_waitq,
2539                        expired_lock_thread.elt_state == ELT_STOPPED);
2540 #else
2541         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2542         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2543 #endif
2544
2545         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2546         ldlm_state = NULL;
2547
2548         RETURN(0);
2549 }
2550
2551 int __init ldlm_init(void)
2552 {
2553         cfs_init_mutex(&ldlm_ref_sem);
2554         cfs_init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
2555         cfs_init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
2556         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
2557                                                sizeof(struct ldlm_resource), 0,
2558                                                CFS_SLAB_HWCACHE_ALIGN);
2559         if (ldlm_resource_slab == NULL)
2560                 return -ENOMEM;
2561
2562         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
2563                               sizeof(struct ldlm_lock), 0,
2564                               CFS_SLAB_HWCACHE_ALIGN | CFS_SLAB_DESTROY_BY_RCU);
2565         if (ldlm_lock_slab == NULL) {
2566                 cfs_mem_cache_destroy(ldlm_resource_slab);
2567                 return -ENOMEM;
2568         }
2569
2570         ldlm_interval_slab = cfs_mem_cache_create("interval_node",
2571                                         sizeof(struct ldlm_interval),
2572                                         0, CFS_SLAB_HWCACHE_ALIGN);
2573         if (ldlm_interval_slab == NULL) {
2574                 cfs_mem_cache_destroy(ldlm_resource_slab);
2575                 cfs_mem_cache_destroy(ldlm_lock_slab);
2576                 return -ENOMEM;
2577         }
2578 #if LUSTRE_TRACKS_LOCK_EXP_REFS
2579         class_export_dump_hook = ldlm_dump_export_locks;
2580 #endif
2581         return 0;
2582 }
2583
2584 void __exit ldlm_exit(void)
2585 {
2586         int rc;
2587         if (ldlm_refcount)
2588                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
2589         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
2590         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
2591 #ifdef __KERNEL__
2592         /* ldlm_lock_put() use RCU to call ldlm_lock_free, so need call
2593          * synchronize_rcu() to wait a grace period elapsed, so that
2594          * ldlm_lock_free() get a chance to be called. */
2595         synchronize_rcu();
2596 #endif
2597         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
2598         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
2599         rc = cfs_mem_cache_destroy(ldlm_interval_slab);
2600         LASSERTF(rc == 0, "couldn't free interval node slab\n");
2601 }
2602
2603 /* ldlm_extent.c */
2604 EXPORT_SYMBOL(ldlm_extent_shift_kms);
2605
2606 /* ldlm_lock.c */
2607 EXPORT_SYMBOL(ldlm_get_processing_policy);
2608 EXPORT_SYMBOL(ldlm_lock2desc);
2609 EXPORT_SYMBOL(ldlm_register_intent);
2610 EXPORT_SYMBOL(ldlm_lockname);
2611 EXPORT_SYMBOL(ldlm_typename);
2612 EXPORT_SYMBOL(ldlm_lock2handle);
2613 EXPORT_SYMBOL(__ldlm_handle2lock);
2614 EXPORT_SYMBOL(ldlm_lock_get);
2615 EXPORT_SYMBOL(ldlm_lock_put);
2616 EXPORT_SYMBOL(ldlm_lock_match);
2617 EXPORT_SYMBOL(ldlm_lock_cancel);
2618 EXPORT_SYMBOL(ldlm_lock_addref);
2619 EXPORT_SYMBOL(ldlm_lock_addref_try);
2620 EXPORT_SYMBOL(ldlm_lock_decref);
2621 EXPORT_SYMBOL(ldlm_lock_decref_and_cancel);
2622 EXPORT_SYMBOL(ldlm_lock_change_resource);
2623 EXPORT_SYMBOL(ldlm_it2str);
2624 EXPORT_SYMBOL(ldlm_lock_dump);
2625 EXPORT_SYMBOL(ldlm_lock_dump_handle);
2626 EXPORT_SYMBOL(ldlm_reprocess_all_ns);
2627 EXPORT_SYMBOL(ldlm_lock_allow_match_locked);
2628 EXPORT_SYMBOL(ldlm_lock_allow_match);
2629 EXPORT_SYMBOL(ldlm_lock_downgrade);
2630 EXPORT_SYMBOL(ldlm_lock_convert);
2631
2632 /* ldlm_request.c */
2633 EXPORT_SYMBOL(ldlm_completion_ast_async);
2634 EXPORT_SYMBOL(ldlm_blocking_ast_nocheck);
2635 EXPORT_SYMBOL(ldlm_completion_ast);
2636 EXPORT_SYMBOL(ldlm_blocking_ast);
2637 EXPORT_SYMBOL(ldlm_glimpse_ast);
2638 EXPORT_SYMBOL(ldlm_expired_completion_wait);
2639 EXPORT_SYMBOL(ldlm_prep_enqueue_req);
2640 EXPORT_SYMBOL(ldlm_prep_elc_req);
2641 EXPORT_SYMBOL(ldlm_cli_convert);
2642 EXPORT_SYMBOL(ldlm_cli_enqueue);
2643 EXPORT_SYMBOL(ldlm_cli_enqueue_fini);
2644 EXPORT_SYMBOL(ldlm_cli_enqueue_local);
2645 EXPORT_SYMBOL(ldlm_cli_cancel);
2646 EXPORT_SYMBOL(ldlm_cli_cancel_unused);
2647 EXPORT_SYMBOL(ldlm_cli_cancel_unused_resource);
2648 EXPORT_SYMBOL(ldlm_cli_cancel_req);
2649 EXPORT_SYMBOL(ldlm_replay_locks);
2650 EXPORT_SYMBOL(ldlm_resource_foreach);
2651 EXPORT_SYMBOL(ldlm_namespace_foreach);
2652 EXPORT_SYMBOL(ldlm_namespace_foreach_res);
2653 EXPORT_SYMBOL(ldlm_resource_iterate);
2654 EXPORT_SYMBOL(ldlm_cancel_resource_local);
2655 EXPORT_SYMBOL(ldlm_cli_cancel_list);
2656
2657 /* ldlm_lockd.c */
2658 EXPORT_SYMBOL(ldlm_server_blocking_ast);
2659 EXPORT_SYMBOL(ldlm_server_completion_ast);
2660 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
2661 EXPORT_SYMBOL(ldlm_handle_enqueue);
2662 EXPORT_SYMBOL(ldlm_handle_enqueue0);
2663 EXPORT_SYMBOL(ldlm_handle_cancel);
2664 EXPORT_SYMBOL(ldlm_request_cancel);
2665 EXPORT_SYMBOL(ldlm_handle_convert);
2666 EXPORT_SYMBOL(ldlm_handle_convert0);
2667 EXPORT_SYMBOL(ldlm_del_waiting_lock);
2668 EXPORT_SYMBOL(ldlm_get_ref);
2669 EXPORT_SYMBOL(ldlm_put_ref);
2670 EXPORT_SYMBOL(ldlm_refresh_waiting_lock);
2671 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2672
2673 /* ldlm_resource.c */
2674 EXPORT_SYMBOL(ldlm_namespace_new);
2675 EXPORT_SYMBOL(ldlm_namespace_cleanup);
2676 EXPORT_SYMBOL(ldlm_namespace_free);
2677 EXPORT_SYMBOL(ldlm_namespace_dump);
2678 EXPORT_SYMBOL(ldlm_dump_all_namespaces);
2679 EXPORT_SYMBOL(ldlm_resource_get);
2680 EXPORT_SYMBOL(ldlm_resource_putref);
2681 EXPORT_SYMBOL(ldlm_resource_unlink_lock);
2682
2683 /* ldlm_lib.c */
2684 EXPORT_SYMBOL(client_import_add_conn);
2685 EXPORT_SYMBOL(client_import_del_conn);
2686 EXPORT_SYMBOL(client_obd_setup);
2687 EXPORT_SYMBOL(client_obd_cleanup);
2688 EXPORT_SYMBOL(client_connect_import);
2689 EXPORT_SYMBOL(client_disconnect_export);
2690 EXPORT_SYMBOL(server_disconnect_export);
2691 EXPORT_SYMBOL(target_stop_recovery_thread);
2692 EXPORT_SYMBOL(target_handle_connect);
2693 EXPORT_SYMBOL(target_cleanup_recovery);
2694 EXPORT_SYMBOL(target_destroy_export);
2695 EXPORT_SYMBOL(target_cancel_recovery_timer);
2696 EXPORT_SYMBOL(target_send_reply);
2697 EXPORT_SYMBOL(target_queue_recovery_request);
2698 EXPORT_SYMBOL(target_handle_ping);
2699 EXPORT_SYMBOL(target_pack_pool_reply);
2700 EXPORT_SYMBOL(target_handle_disconnect);
2701
2702 /* l_lock.c */
2703 EXPORT_SYMBOL(lock_res_and_lock);
2704 EXPORT_SYMBOL(unlock_res_and_lock);