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