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