Whamcloud - gitweb
f06737c94b80d2a4d322efdafd376a2f63e11e68
[fs/lustre-release.git] / lustre / ldlm / ldlm_request.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  Copyright (C) 2002, 2003 Cluster File Systems, Inc.
5  *
6  *   This file is part of the Lustre file system, http://www.lustre.org
7  *   Lustre is a trademark of Cluster File Systems, Inc.
8  *
9  *   You may have signed or agreed to another license before downloading
10  *   this software.  If so, you are bound by the terms and conditions
11  *   of that agreement, and the following does not apply to you.  See the
12  *   LICENSE file included with this distribution for more information.
13  *
14  *   If you did not agree to a different license, then this copy of Lustre
15  *   is open source software; you can redistribute it and/or modify it
16  *   under the terms of version 2 of the GNU General Public License as
17  *   published by the Free Software Foundation.
18  *
19  *   In either case, Lustre is distributed in the hope that it will be
20  *   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
21  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *   license text for more details.
23  */
24
25 #define DEBUG_SUBSYSTEM S_LDLM
26 #ifndef __KERNEL__
27 #include <signal.h>
28 #include <liblustre.h>
29 #endif
30
31 #include <lustre_dlm.h>
32 #include <obd_class.h>
33 #include <obd.h>
34
35 #include "ldlm_internal.h"
36
37 static void interrupted_completion_wait(void *data)
38 {
39 }
40
41 struct lock_wait_data {
42         struct ldlm_lock *lwd_lock;
43         __u32             lwd_conn_cnt;
44 };
45
46 struct ldlm_async_args {
47         struct lustre_handle lock_handle;
48 };
49
50 int ldlm_expired_completion_wait(void *data)
51 {
52         struct lock_wait_data *lwd = data;
53         struct ldlm_lock *lock = lwd->lwd_lock;
54         struct obd_import *imp;
55         struct obd_device *obd;
56
57         ENTRY;
58         if (lock->l_conn_export == NULL) {
59                 static cfs_time_t next_dump = 0, last_dump = 0;
60
61                 if (ptlrpc_check_suspend())
62                         RETURN(0);
63
64                 LDLM_ERROR(lock, "lock timed out (enqueued at %lu, %lus ago); "
65                            "not entering recovery in server code, just going "
66                            "back to sleep", lock->l_enqueued_time.tv_sec,
67                            CURRENT_SECONDS - lock->l_enqueued_time.tv_sec);
68                 if (cfs_time_after(cfs_time_current(), next_dump)) {
69                         last_dump = next_dump;
70                         next_dump = cfs_time_shift(300);
71                         ldlm_namespace_dump(D_DLMTRACE,
72                                             lock->l_resource->lr_namespace);
73                         if (last_dump == 0)
74                                 libcfs_debug_dumplog();
75                 }
76                 RETURN(0);
77         }
78
79         obd = lock->l_conn_export->exp_obd;
80         imp = obd->u.cli.cl_import;
81         ptlrpc_fail_import(imp, lwd->lwd_conn_cnt);
82         LDLM_ERROR(lock, "lock timed out (enqueued at %lu, %lus ago), entering "
83                    "recovery for %s@%s", lock->l_enqueued_time.tv_sec,
84                    CURRENT_SECONDS - lock->l_enqueued_time.tv_sec,
85                    obd2cli_tgt(obd), imp->imp_connection->c_remote_uuid.uuid);
86
87         RETURN(0);
88 }
89
90 int ldlm_completion_ast(struct ldlm_lock *lock, int flags, void *data)
91 {
92         /* XXX ALLOCATE - 160 bytes */
93         struct lock_wait_data lwd;
94         struct obd_device *obd;
95         struct obd_import *imp = NULL;
96         struct l_wait_info lwi;
97         int rc = 0;
98         ENTRY;
99
100         if (flags == LDLM_FL_WAIT_NOREPROC) {
101                 LDLM_DEBUG(lock, "client-side enqueue waiting on pending lock");
102                 goto noreproc;
103         }
104
105         if (!(flags & (LDLM_FL_BLOCK_WAIT | LDLM_FL_BLOCK_GRANTED |
106                        LDLM_FL_BLOCK_CONV))) {
107                 cfs_waitq_signal(&lock->l_waitq);
108                 RETURN(0);
109         }
110
111         LDLM_DEBUG(lock, "client-side enqueue returned a blocked lock, "
112                    "sleeping");
113         ldlm_lock_dump(D_OTHER, lock, 0);
114         ldlm_reprocess_all(lock->l_resource);
115
116 noreproc:
117
118         obd = class_exp2obd(lock->l_conn_export);
119
120         /* if this is a local lock, then there is no import */
121         if (obd != NULL)
122                 imp = obd->u.cli.cl_import;
123
124         lwd.lwd_lock = lock;
125
126         if (lock->l_flags & LDLM_FL_NO_TIMEOUT) {
127                 LDLM_DEBUG(lock, "waiting indefinitely because of NO_TIMEOUT");
128                 lwi = LWI_INTR(interrupted_completion_wait, &lwd);
129         } else {
130                 lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(obd_timeout),
131                                        ldlm_expired_completion_wait,
132                                        interrupted_completion_wait, &lwd);
133         }
134
135         if (imp != NULL) {
136                 spin_lock(&imp->imp_lock);
137                 lwd.lwd_conn_cnt = imp->imp_conn_cnt;
138                 spin_unlock(&imp->imp_lock);
139         }
140
141         /* Go to sleep until the lock is granted or cancelled. */
142         rc = l_wait_event(lock->l_waitq,
143                           ((lock->l_req_mode == lock->l_granted_mode) ||
144                            (lock->l_flags & LDLM_FL_FAILED)), &lwi);
145
146         if (lock->l_destroyed || lock->l_flags & LDLM_FL_FAILED) {
147                 LDLM_DEBUG(lock, "client-side enqueue waking up: destroyed");
148                 RETURN(-EIO);
149         }
150
151         if (rc) {
152                 LDLM_DEBUG(lock, "client-side enqueue waking up: failed (%d)",
153                            rc);
154                 RETURN(rc);
155         }
156
157         LDLM_DEBUG(lock, "client-side enqueue waking up: granted");
158         RETURN(0);
159 }
160
161 /*
162  * ->l_blocking_ast() callback for LDLM locks acquired by server-side OBDs.
163  */
164 int ldlm_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
165                       void *data, int flag)
166 {
167         int do_ast;
168         ENTRY;
169
170         if (flag == LDLM_CB_CANCELING) {
171                 /* Don't need to do anything here. */
172                 RETURN(0);
173         }
174
175         lock_res_and_lock(lock);
176         /* Get this: if ldlm_blocking_ast is racing with intent_policy, such
177          * that ldlm_blocking_ast is called just before intent_policy method
178          * takes the ns_lock, then by the time we get the lock, we might not
179          * be the correct blocking function anymore.  So check, and return
180          * early, if so. */
181         if (lock->l_blocking_ast != ldlm_blocking_ast) {
182                 unlock_res_and_lock(lock);
183                 RETURN(0);
184         }
185
186         lock->l_flags |= LDLM_FL_CBPENDING;
187         do_ast = (!lock->l_readers && !lock->l_writers);
188         unlock_res_and_lock(lock);
189
190         if (do_ast) {
191                 struct lustre_handle lockh;
192                 int rc;
193
194                 LDLM_DEBUG(lock, "already unused, calling ldlm_cli_cancel");
195                 ldlm_lock2handle(lock, &lockh);
196                 rc = ldlm_cli_cancel(&lockh);
197                 if (rc < 0)
198                         CERROR("ldlm_cli_cancel: %d\n", rc);
199         } else {
200                 LDLM_DEBUG(lock, "Lock still has references, will be "
201                            "cancelled later");
202         }
203         RETURN(0);
204 }
205
206 /*
207  * ->l_glimpse_ast() for DLM extent locks acquired on the server-side. See
208  * comment in filter_intent_policy() on why you may need this.
209  */
210 int ldlm_glimpse_ast(struct ldlm_lock *lock, void *reqp)
211 {
212         /*
213          * Returning -ELDLM_NO_LOCK_DATA actually works, but the reason for
214          * that is rather subtle: with OST-side locking, it may so happen that
215          * _all_ extent locks are held by the OST. If client wants to obtain
216          * current file size it calls ll{,u}_glimpse_size(), and (as locks are
217          * on the server), dummy glimpse callback fires and does
218          * nothing. Client still receives correct file size due to the
219          * following fragment in filter_intent_policy():
220          *
221          * rc = l->l_glimpse_ast(l, NULL); // this will update the LVB
222          * if (rc != 0 && res->lr_namespace->ns_lvbo &&
223          *     res->lr_namespace->ns_lvbo->lvbo_update) {
224          *         res->lr_namespace->ns_lvbo->lvbo_update(res, NULL, 0, 1);
225          * }
226          *
227          * that is, after glimpse_ast() fails, filter_lvbo_update() runs, and
228          * returns correct file size to the client.
229          */
230         return -ELDLM_NO_LOCK_DATA;
231 }
232
233 int ldlm_cli_enqueue_local(struct ldlm_namespace *ns,
234                            const struct ldlm_res_id *res_id,
235                            ldlm_type_t type, ldlm_policy_data_t *policy,
236                            ldlm_mode_t mode, int *flags,
237                            ldlm_blocking_callback blocking,
238                            ldlm_completion_callback completion,
239                            ldlm_glimpse_callback glimpse,
240                            void *data, __u32 lvb_len, void *lvb_swabber,
241                            struct lustre_handle *lockh)
242 {
243         struct ldlm_lock *lock;
244         int err;
245         ENTRY;
246
247         LASSERT(!(*flags & LDLM_FL_REPLAY));
248         if (unlikely(ns->ns_client)) {
249                 CERROR("Trying to enqueue local lock in a shadow namespace\n");
250                 LBUG();
251         }
252
253         lock = ldlm_lock_create(ns, res_id, type, mode, blocking,
254                                 completion, glimpse, data, lvb_len);
255         if (unlikely(!lock))
256                 GOTO(out_nolock, err = -ENOMEM);
257         LDLM_DEBUG(lock, "client-side local enqueue handler, new lock created");
258
259         ldlm_lock_addref_internal(lock, mode);
260         ldlm_lock2handle(lock, lockh);
261         lock_res_and_lock(lock);
262         lock->l_flags |= LDLM_FL_LOCAL;
263         if (*flags & LDLM_FL_ATOMIC_CB)
264                 lock->l_flags |= LDLM_FL_ATOMIC_CB;
265         lock->l_lvb_swabber = lvb_swabber;
266         unlock_res_and_lock(lock);
267         if (policy != NULL)
268                 lock->l_policy_data = *policy;
269         if (type == LDLM_EXTENT)
270                 lock->l_req_extent = policy->l_extent;
271
272         err = ldlm_lock_enqueue(ns, &lock, policy, flags);
273         if (unlikely(err != ELDLM_OK))
274                 GOTO(out, err);
275
276         if (policy != NULL)
277                 *policy = lock->l_policy_data;
278
279         LDLM_DEBUG_NOLOCK("client-side local enqueue handler END (lock %p)",
280                           lock);
281
282         if (lock->l_completion_ast)
283                 lock->l_completion_ast(lock, *flags, NULL);
284
285         LDLM_DEBUG(lock, "client-side local enqueue END");
286         EXIT;
287  out:
288         LDLM_LOCK_PUT(lock);
289  out_nolock:
290         return err;
291 }
292
293 static void failed_lock_cleanup(struct ldlm_namespace *ns,
294                                 struct ldlm_lock *lock,
295                                 struct lustre_handle *lockh, int mode)
296 {
297         /* Set a flag to prevent us from sending a CANCEL (bug 407) */
298         lock_res_and_lock(lock);
299         lock->l_flags |= LDLM_FL_LOCAL_ONLY;
300         unlock_res_and_lock(lock);
301         LDLM_DEBUG(lock, "setting FL_LOCAL_ONLY");
302
303         ldlm_lock_decref_and_cancel(lockh, mode);
304
305         /* XXX - HACK because we shouldn't call ldlm_lock_destroy()
306          *       from llite/file.c/ll_file_flock(). */
307         if (lock->l_resource->lr_type == LDLM_FLOCK) {
308                 ldlm_lock_destroy(lock);
309         }
310 }
311
312 int ldlm_cli_enqueue_fini(struct obd_export *exp, struct ptlrpc_request *req,
313                           ldlm_type_t type, __u8 with_policy, ldlm_mode_t mode,
314                           int *flags, void *lvb, __u32 lvb_len,
315                           void *lvb_swabber, struct lustre_handle *lockh,int rc)
316 {
317         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
318         int is_replay = *flags & LDLM_FL_REPLAY;
319         struct ldlm_lock *lock;
320         struct ldlm_reply *reply;
321         int cleanup_phase = 1;
322         ENTRY;
323
324         lock = ldlm_handle2lock(lockh);
325         /* ldlm_cli_enqueue is holding a reference on this lock. */
326         if (!lock) {
327                 LASSERT(type == LDLM_FLOCK);
328                 RETURN(-ENOLCK);
329         }
330
331         if (rc != ELDLM_OK) {
332                 LASSERT(!is_replay);
333                 LDLM_DEBUG(lock, "client-side enqueue END (%s)",
334                            rc == ELDLM_LOCK_ABORTED ? "ABORTED" : "FAILED");
335                 if (rc == ELDLM_LOCK_ABORTED) {
336                         /* Before we return, swab the reply */
337                         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF,
338                                                    sizeof(*reply),
339                                                    lustre_swab_ldlm_reply);
340                         if (reply == NULL) {
341                                 CERROR("Can't unpack ldlm_reply\n");
342                                 rc = -EPROTO;
343                         }
344                         if (lvb_len) {
345                                 void *tmplvb;
346                                 tmplvb = lustre_swab_repbuf(req,
347                                                             DLM_REPLY_REC_OFF,
348                                                             lvb_len,
349                                                             lvb_swabber);
350                                 if (tmplvb == NULL)
351                                         GOTO(cleanup, rc = -EPROTO);
352                                 if (lvb != NULL)
353                                         memcpy(lvb, tmplvb, lvb_len);
354                         }
355                 }
356                 GOTO(cleanup, rc);
357         }
358
359         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
360                                    lustre_swab_ldlm_reply);
361         if (reply == NULL) {
362                 CERROR("Can't unpack ldlm_reply\n");
363                 GOTO(cleanup, rc = -EPROTO);
364         }
365
366         /* lock enqueued on the server */
367         cleanup_phase = 0;
368
369         lock_res_and_lock(lock);
370         lock->l_remote_handle = reply->lock_handle;
371         *flags = reply->lock_flags;
372         lock->l_flags |= reply->lock_flags & LDLM_INHERIT_FLAGS;
373         /* move NO_TIMEOUT flag to the lock to force ldlm_lock_match()
374          * to wait with no timeout as well */
375         lock->l_flags |= reply->lock_flags & LDLM_FL_NO_TIMEOUT;
376         unlock_res_and_lock(lock);
377
378         CDEBUG(D_INFO, "local: %p, remote cookie: "LPX64", flags: 0x%x\n",
379                lock, reply->lock_handle.cookie, *flags);
380
381         /* If enqueue returned a blocked lock but the completion handler has
382          * already run, then it fixed up the resource and we don't need to do it
383          * again. */
384         if ((*flags) & LDLM_FL_LOCK_CHANGED) {
385                 int newmode = reply->lock_desc.l_req_mode;
386                 LASSERT(!is_replay);
387                 if (newmode && newmode != lock->l_req_mode) {
388                         LDLM_DEBUG(lock, "server returned different mode %s",
389                                    ldlm_lockname[newmode]);
390                         lock->l_req_mode = newmode;
391                 }
392
393                 if (memcmp(reply->lock_desc.l_resource.lr_name.name,
394                           lock->l_resource->lr_name.name,
395                           sizeof(struct ldlm_res_id))) {
396                         CDEBUG(D_INFO, "remote intent success, locking "
397                                         "(%ld,%ld,%ld) instead of "
398                                         "(%ld,%ld,%ld)\n",
399                               (long)reply->lock_desc.l_resource.lr_name.name[0],
400                               (long)reply->lock_desc.l_resource.lr_name.name[1],
401                               (long)reply->lock_desc.l_resource.lr_name.name[2],
402                               (long)lock->l_resource->lr_name.name[0],
403                               (long)lock->l_resource->lr_name.name[1],
404                               (long)lock->l_resource->lr_name.name[2]);
405
406                         ldlm_lock_change_resource(ns, lock,
407                                           &reply->lock_desc.l_resource.lr_name);
408                         if (lock->l_resource == NULL) {
409                                 LBUG();
410                                 GOTO(cleanup, rc = -ENOMEM);
411                         }
412                         LDLM_DEBUG(lock, "client-side enqueue, new resource");
413                 }
414                 if (with_policy)
415                         if (!(type == LDLM_IBITS && !(exp->exp_connect_flags &
416                                                     OBD_CONNECT_IBITS)))
417                                 lock->l_policy_data =
418                                                  reply->lock_desc.l_policy_data;
419                 if (type != LDLM_PLAIN)
420                         LDLM_DEBUG(lock,"client-side enqueue, new policy data");
421         }
422
423         if ((*flags) & LDLM_FL_AST_SENT ||
424             /* Cancel extent locks as soon as possible on a liblustre client,
425              * because it cannot handle asynchronous ASTs robustly (see
426              * bug 7311). */
427             (LIBLUSTRE_CLIENT && type == LDLM_EXTENT)) {
428                 lock_res_and_lock(lock);
429                 lock->l_flags |= LDLM_FL_CBPENDING;
430                 unlock_res_and_lock(lock);
431                 LDLM_DEBUG(lock, "enqueue reply includes blocking AST");
432         }
433
434         /* If the lock has already been granted by a completion AST, don't
435          * clobber the LVB with an older one. */
436         if (lvb_len && (lock->l_req_mode != lock->l_granted_mode)) {
437                 void *tmplvb;
438                 tmplvb = lustre_swab_repbuf(req, DLM_REPLY_REC_OFF, lvb_len,
439                                             lvb_swabber);
440                 if (tmplvb == NULL)
441                         GOTO(cleanup, rc = -EPROTO);
442                 memcpy(lock->l_lvb_data, tmplvb, lvb_len);
443         }
444
445         if (!is_replay) {
446                 rc = ldlm_lock_enqueue(ns, &lock, NULL, flags);
447                 if (lock->l_completion_ast != NULL) {
448                         int err = lock->l_completion_ast(lock, *flags, NULL);
449                         if (!rc)
450                                 rc = err;
451                         if (rc && type != LDLM_FLOCK) /* bug 9425, bug 10250 */
452                                 cleanup_phase = 1;
453                 }
454         }
455
456         if (lvb_len && lvb != NULL) {
457                 /* Copy the LVB here, and not earlier, because the completion
458                  * AST (if any) can override what we got in the reply */
459                 memcpy(lvb, lock->l_lvb_data, lvb_len);
460         }
461
462         LDLM_DEBUG(lock, "client-side enqueue END");
463         EXIT;
464 cleanup:
465         if (cleanup_phase == 1 && rc)
466                 failed_lock_cleanup(ns, lock, lockh, mode);
467         /* Put lock 2 times, the second reference is held by ldlm_cli_enqueue */
468         LDLM_LOCK_PUT(lock);
469         LDLM_LOCK_PUT(lock);
470         return rc;
471 }
472
473 /* PAGE_SIZE-512 is to allow TCP/IP and LNET headers to fit into
474  * a single page on the send/receive side. XXX: 512 should be changed
475  * to more adequate value. */
476 #define ldlm_req_handles_avail(exp, size, bufcount, off)                \
477 ({                                                                      \
478         int _avail = min_t(int, LDLM_MAXREQSIZE, PAGE_SIZE - 512);      \
479         int _s = size[DLM_LOCKREQ_OFF];                                 \
480         size[DLM_LOCKREQ_OFF] = sizeof(struct ldlm_request);            \
481         _avail -= lustre_msg_size(class_exp2cliimp(exp)->imp_msg_magic, \
482                                 bufcount, size);                        \
483         _avail /= sizeof(struct lustre_handle);                         \
484         _avail += LDLM_LOCKREQ_HANDLES - off;                           \
485         size[DLM_LOCKREQ_OFF] = _s;                                     \
486         _avail;                                                         \
487 })
488
489 /* Cancel lru locks and pack them into the enqueue request. Pack there the given
490  * @count locks in @cancel. */
491 struct ptlrpc_request *ldlm_prep_enqueue_req(struct obd_export *exp,
492                                              int bufcount, int *size,
493                                              struct list_head *cancels,
494                                              int count)
495 {
496         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
497         struct ldlm_request *dlm = NULL;
498         struct ptlrpc_request *req;
499         CFS_LIST_HEAD(head);
500         ENTRY;
501         
502         if (cancels == NULL)
503                 cancels = &head;
504         if (exp_connect_cancelset(exp)) {
505                 /* Estimate the amount of available space in the request. */
506                 int avail = ldlm_req_handles_avail(exp, size, bufcount,
507                                                    LDLM_ENQUEUE_CANCEL_OFF);
508                 LASSERT(avail >= count);
509                 
510                 /* Cancel lru locks here _only_ if the server supports 
511                  * EARLY_CANCEL. Otherwise we have to send extra CANCEL
512                  * rpc right on enqueue, what will make it slower, vs. 
513                  * asynchronous rpc in blocking thread. */
514                 count += ldlm_cancel_lru_local(ns, cancels, 1, avail - count,
515                                                LDLM_CANCEL_AGED);
516                 size[DLM_LOCKREQ_OFF] =
517                         ldlm_request_bufsize(count, LDLM_ENQUEUE);
518         }
519         req = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_DLM_VERSION,
520                               LDLM_ENQUEUE, bufcount, size, NULL);
521         if (exp_connect_cancelset(exp) && req) {
522                 dlm = lustre_msg_buf(req->rq_reqmsg,
523                                      DLM_LOCKREQ_OFF, sizeof(*dlm));
524                 /* Skip first lock handler in ldlm_request_pack(), this method
525                  * will incrment @lock_count according to the lock handle amount
526                  * actually written to the buffer. */
527                 dlm->lock_count = LDLM_ENQUEUE_CANCEL_OFF;
528                 ldlm_cli_cancel_list(cancels, count, req, DLM_LOCKREQ_OFF, 0);
529         } else {
530                 ldlm_lock_list_put(cancels, l_bl_ast, count);
531         }
532         RETURN(req);
533 }
534
535 /* If a request has some specific initialisation it is passed in @reqp,
536  * otherwise it is created in ldlm_cli_enqueue.
537  *
538  * Supports sync and async requests, pass @async flag accordingly. If a
539  * request was created in ldlm_cli_enqueue and it is the async request,
540  * pass it to the caller in @reqp. */
541 int ldlm_cli_enqueue(struct obd_export *exp, struct ptlrpc_request **reqp,
542                      const struct ldlm_res_id *res_id,
543                      ldlm_type_t type, ldlm_policy_data_t *policy,
544                      ldlm_mode_t mode, int *flags,
545                      ldlm_blocking_callback blocking,
546                      ldlm_completion_callback completion,
547                      ldlm_glimpse_callback glimpse,
548                      void *data, void *lvb, __u32 lvb_len, void *lvb_swabber,
549                      struct lustre_handle *lockh, int async)
550 {
551         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
552         struct ldlm_lock *lock;
553         struct ldlm_request *body;
554         struct ldlm_reply *reply;
555         int size[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
556                         [DLM_LOCKREQ_OFF]     = sizeof(*body),
557                         [DLM_REPLY_REC_OFF]   = lvb_len };
558         int is_replay = *flags & LDLM_FL_REPLAY;
559         int req_passed_in = 1, rc, err;
560         struct ptlrpc_request *req;
561         ENTRY;
562
563         LASSERT(exp != NULL);
564
565         /* If we're replaying this lock, just check some invariants.
566          * If we're creating a new lock, get everything all setup nice. */
567         if (is_replay) {
568                 lock = ldlm_handle2lock(lockh);
569                 LASSERT(lock != NULL);
570                 LDLM_DEBUG(lock, "client-side enqueue START");
571                 LASSERT(exp == lock->l_conn_export);
572         } else {
573                 lock = ldlm_lock_create(ns, res_id, type, mode, blocking,
574                                         completion, glimpse, data, lvb_len);
575                 if (lock == NULL)
576                         RETURN(-ENOMEM);
577                 /* for the local lock, add the reference */
578                 ldlm_lock_addref_internal(lock, mode);
579                 ldlm_lock2handle(lock, lockh);
580                 lock->l_lvb_swabber = lvb_swabber;
581                 if (policy != NULL) {
582                         /* INODEBITS_INTEROP: If the server does not support
583                          * inodebits, we will request a plain lock in the
584                          * descriptor (ldlm_lock2desc() below) but use an
585                          * inodebits lock internally with both bits set.
586                          */
587                         if (type == LDLM_IBITS && !(exp->exp_connect_flags &
588                                                     OBD_CONNECT_IBITS))
589                                 lock->l_policy_data.l_inodebits.bits =
590                                         MDS_INODELOCK_LOOKUP |
591                                         MDS_INODELOCK_UPDATE;
592                         else
593                                 lock->l_policy_data = *policy;
594                 }
595
596                 if (type == LDLM_EXTENT)
597                         lock->l_req_extent = policy->l_extent;
598                 LDLM_DEBUG(lock, "client-side enqueue START");
599         }
600
601         /* lock not sent to server yet */
602
603         if (reqp == NULL || *reqp == NULL) {
604                 req = ldlm_prep_enqueue_req(exp, 2, size, NULL, 0);
605                 if (req == NULL) {
606                         failed_lock_cleanup(ns, lock, lockh, mode);
607                         LDLM_LOCK_PUT(lock);
608                         RETURN(-ENOMEM);
609                 }
610                 req_passed_in = 0;
611                 if (reqp)
612                         *reqp = req;
613         } else {
614                 req = *reqp;
615                 LASSERTF(lustre_msg_buflen(req->rq_reqmsg, DLM_LOCKREQ_OFF) >=
616                          sizeof(*body), "buflen[%d] = %d, not "LPSZ"\n",
617                          DLM_LOCKREQ_OFF,
618                          lustre_msg_buflen(req->rq_reqmsg, DLM_LOCKREQ_OFF),
619                          sizeof(*body));
620         }
621
622         lock->l_conn_export = exp;
623         lock->l_export = NULL;
624         lock->l_blocking_ast = blocking;
625
626         /* Dump lock data into the request buffer */
627         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
628         ldlm_lock2desc(lock, &body->lock_desc);
629         body->lock_flags = *flags;
630         body->lock_handle[0] = *lockh;
631
632         /* Continue as normal. */
633         if (!req_passed_in) {
634                 size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
635                 ptlrpc_req_set_repsize(req, 2 + (lvb_len > 0), size);
636         }
637
638         /*
639          * Liblustre client doesn't get extent locks, except for O_APPEND case
640          * where [0, OBD_OBJECT_EOF] lock is taken, or truncate, where
641          * [i_size, OBD_OBJECT_EOF] lock is taken.
642          */
643         LASSERT(ergo(LIBLUSTRE_CLIENT, type != LDLM_EXTENT ||
644                      policy->l_extent.end == OBD_OBJECT_EOF));
645
646         if (async) {
647                 LASSERT(reqp != NULL);
648                 RETURN(0);
649         }
650
651         LDLM_DEBUG(lock, "sending request");
652         rc = ptlrpc_queue_wait(req);
653         err = ldlm_cli_enqueue_fini(exp, req, type, policy ? 1 : 0,
654                                     mode, flags, lvb, lvb_len, lvb_swabber,
655                                     lockh, rc);
656
657         /* If ldlm_cli_enqueue_fini did not find the lock, we need to free
658          * one reference that we took */
659         if (err == -ENOLCK)
660                 LDLM_LOCK_PUT(lock);
661         else
662                 rc = err;
663
664         if (!req_passed_in && req != NULL) {
665                 ptlrpc_req_finished(req);
666                 if (reqp)
667                         *reqp = NULL;
668         }
669
670         RETURN(rc);
671 }
672
673 static int ldlm_cli_convert_local(struct ldlm_lock *lock, int new_mode,
674                                   int *flags)
675 {
676         struct ldlm_resource *res;
677         int rc;
678         ENTRY;
679         if (lock->l_resource->lr_namespace->ns_client) {
680                 CERROR("Trying to cancel local lock\n");
681                 LBUG();
682         }
683         LDLM_DEBUG(lock, "client-side local convert");
684
685         res = ldlm_lock_convert(lock, new_mode, flags);
686         if (res) {
687                 ldlm_reprocess_all(res);
688                 rc = 0;
689         } else {
690                 rc = EDEADLOCK;
691         }
692         LDLM_DEBUG(lock, "client-side local convert handler END");
693         LDLM_LOCK_PUT(lock);
694         RETURN(rc);
695 }
696
697 /* FIXME: one of ldlm_cli_convert or the server side should reject attempted
698  * conversion of locks which are on the waiting or converting queue */
699 /* Caller of this code is supposed to take care of lock readers/writers
700    accounting */
701 int ldlm_cli_convert(struct lustre_handle *lockh, int new_mode, int *flags)
702 {
703         struct ldlm_request *body;
704         struct ldlm_reply *reply;
705         struct ldlm_lock *lock;
706         struct ldlm_resource *res;
707         struct ptlrpc_request *req;
708         int size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
709                         [DLM_LOCKREQ_OFF]     = sizeof(*body) };
710         int rc;
711         ENTRY;
712
713         lock = ldlm_handle2lock(lockh);
714         if (!lock) {
715                 LBUG();
716                 RETURN(-EINVAL);
717         }
718         *flags = 0;
719
720         if (lock->l_conn_export == NULL)
721                 RETURN(ldlm_cli_convert_local(lock, new_mode, flags));
722
723         LDLM_DEBUG(lock, "client-side convert");
724
725         req = ptlrpc_prep_req(class_exp2cliimp(lock->l_conn_export),
726                               LUSTRE_DLM_VERSION, LDLM_CONVERT, 2, size, NULL);
727         if (!req)
728                 GOTO(out, rc = -ENOMEM);
729
730         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
731         body->lock_handle[0] = lock->l_remote_handle;
732
733         body->lock_desc.l_req_mode = new_mode;
734         body->lock_flags = *flags;
735
736         size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
737         ptlrpc_req_set_repsize(req, 2, size);
738
739         rc = ptlrpc_queue_wait(req);
740         if (rc != ELDLM_OK)
741                 GOTO(out, rc);
742
743         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
744                                    lustre_swab_ldlm_reply);
745         if (reply == NULL) {
746                 CERROR ("Can't unpack ldlm_reply\n");
747                 GOTO (out, rc = -EPROTO);
748         }
749
750         if (req->rq_status)
751                 GOTO(out, rc = req->rq_status);
752
753         res = ldlm_lock_convert(lock, new_mode, &reply->lock_flags);
754         if (res != NULL) {
755                 ldlm_reprocess_all(res);
756                 /* Go to sleep until the lock is granted. */
757                 /* FIXME: or cancelled. */
758                 if (lock->l_completion_ast) {
759                         rc = lock->l_completion_ast(lock, LDLM_FL_WAIT_NOREPROC,
760                                                     NULL);
761                         if (rc)
762                                 GOTO(out, rc);
763                 }
764         } else {
765                 rc = EDEADLOCK;
766         }
767         EXIT;
768  out:
769         LDLM_LOCK_PUT(lock);
770         ptlrpc_req_finished(req);
771         return rc;
772 }
773
774 /* Cancel locks locally.
775  * Returns: 1 if there is a need to send a cancel RPC to server. 0 otherwise. */
776 static int ldlm_cli_cancel_local(struct ldlm_lock *lock)
777 {
778         int rc = 0;
779         ENTRY;
780         
781         if (lock->l_conn_export) {
782                 int local_only;
783
784                 LDLM_DEBUG(lock, "client-side cancel");
785                 /* Set this flag to prevent others from getting new references*/
786                 lock_res_and_lock(lock);
787                 lock->l_flags |= LDLM_FL_CBPENDING;
788                 local_only = (lock->l_flags &
789                               (LDLM_FL_LOCAL_ONLY|LDLM_FL_CANCEL_ON_BLOCK));
790                 ldlm_cancel_callback(lock);
791                 unlock_res_and_lock(lock);
792
793                 if (local_only)
794                         CDEBUG(D_INFO, "not sending request (at caller's "
795                                "instruction)\n");
796                 else
797                         rc = 1;
798
799                 ldlm_lock_cancel(lock);
800         } else {
801                 if (lock->l_resource->lr_namespace->ns_client) {
802                         LDLM_ERROR(lock, "Trying to cancel local lock");
803                         LBUG();
804                 }
805                 LDLM_DEBUG(lock, "server-side local cancel");
806                 ldlm_lock_cancel(lock);
807                 ldlm_reprocess_all(lock->l_resource);
808                 LDLM_DEBUG(lock, "server-side local cancel handler END");
809         }
810
811         RETURN(rc);
812 }
813
814 /* Pack @count locks in @head into ldlm_request buffer at the offset @off,
815    of the request @req. */
816 static void ldlm_cancel_pack(struct ptlrpc_request *req, int off,
817                              struct list_head *head, int count)
818 {
819         struct ldlm_request *dlm;
820         struct ldlm_lock *lock;
821         int max;
822         ENTRY;
823
824         dlm = lustre_msg_buf(req->rq_reqmsg, off, sizeof(*dlm));
825         LASSERT(dlm != NULL);
826
827         /* Check the room in the request buffer. */
828         max = lustre_msg_buflen(req->rq_reqmsg, off) - 
829                 sizeof(struct ldlm_request);
830         max /= sizeof(struct lustre_handle);
831         max += LDLM_LOCKREQ_HANDLES;
832         LASSERT(max >= dlm->lock_count + count);
833
834         /* XXX: it would be better to pack lock handles grouped by resource.
835          * so that the server cancel would call filter_lvbo_update() less
836          * frequently. */
837         list_for_each_entry(lock, head, l_bl_ast) {
838                 if (!count--)
839                         break;
840                 /* Pack the lock handle to the given request buffer. */
841                 LASSERT(lock->l_conn_export);
842                 /* Cannot be set on a lock in a resource granted list.*/
843                 LASSERT(!(lock->l_flags &
844                           (LDLM_FL_LOCAL_ONLY|LDLM_FL_CANCEL_ON_BLOCK)));
845                 /* If @lock is marked CANCEL_ON_BLOCK, cancel
846                  * will not be sent in ldlm_cli_cancel(). It 
847                  * is used for liblustre clients, no cancel on 
848                  * block requests. However, even for liblustre 
849                  * clients, when the flag is set, batched cancel
850                  * should be sent (what if no block rpc has
851                  * come). To not send another separated rpc in
852                  * this case, the caller pass CANCEL_ON_BLOCK
853                  * flag to ldlm_cli_cancel_unused_resource(). */
854                 dlm->lock_handle[dlm->lock_count++] = lock->l_remote_handle;
855         }
856         EXIT;
857 }
858
859 /* Prepare and send a batched cancel rpc, it will include count lock handles
860  * of locks given in @head. */
861 int ldlm_cli_cancel_req(struct obd_export *exp, struct list_head *cancels,
862                         int count, int flags)
863 {
864         struct ptlrpc_request *req = NULL;
865         struct ldlm_request *body;
866         int size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
867                 [DLM_LOCKREQ_OFF]     = sizeof(*body) };
868         struct obd_import *imp;
869         int free, sent = 0;
870         int rc = 0;
871         ENTRY;
872
873         LASSERT(exp != NULL);
874         LASSERT(count > 0);
875
876         free = ldlm_req_handles_avail(exp, size, 2, 0);
877         if (count > free)
878                 count = free;
879
880         size[DLM_LOCKREQ_OFF] = ldlm_request_bufsize(count, LDLM_CANCEL);
881         while (1) {
882                 imp = class_exp2cliimp(exp);
883                 if (imp == NULL || imp->imp_invalid) {
884                         CDEBUG(D_HA, "skipping cancel on invalid import %p\n",
885                                imp);
886                         break;
887                 }
888
889                 req = ptlrpc_prep_req(imp, LUSTRE_DLM_VERSION, LDLM_CANCEL, 2,
890                                       size, NULL);
891                 if (!req)
892                         GOTO(out, rc = -ENOMEM);
893
894                 req->rq_no_resend = 1;
895                 req->rq_no_delay = 1;
896
897                 /* XXX FIXME bug 249 */
898                 req->rq_request_portal = LDLM_CANCEL_REQUEST_PORTAL;
899                 req->rq_reply_portal = LDLM_CANCEL_REPLY_PORTAL;
900
901                 body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF,
902                                       sizeof(*body));
903                 ldlm_cancel_pack(req, DLM_LOCKREQ_OFF, cancels, count);
904
905                 ptlrpc_req_set_repsize(req, 1, NULL);
906                 if (flags & LDLM_FL_ASYNC) {
907                         ptlrpcd_add_req(req);
908                         sent = count;
909                         GOTO(out, 0);
910                 } else {
911                         rc = ptlrpc_queue_wait(req);
912                 }
913                 if (rc == ESTALE) {
914                         CDEBUG(D_DLMTRACE, "client/server (nid %s) "
915                                "out of sync -- not fatal\n",
916                                libcfs_nid2str(req->rq_import->
917                                               imp_connection->c_peer.nid));
918                 } else if (rc == -ETIMEDOUT && /* check there was no reconnect*/
919                            req->rq_import_generation == imp->imp_generation) {
920                         ptlrpc_req_finished(req);
921                         continue;
922                 } else if (rc != ELDLM_OK) {
923                         CERROR("Got rc %d from cancel RPC: canceling "
924                                "anyway\n", rc);
925                         break;
926                 }
927                 sent = count;
928                 break;
929         }
930
931         ptlrpc_req_finished(req);
932         EXIT;
933 out:
934         return sent ? sent : rc;
935 }
936
937 int ldlm_cli_cancel(struct lustre_handle *lockh)
938 {
939         struct ldlm_lock *lock;
940         CFS_LIST_HEAD(head);
941         int rc = 0;
942         ENTRY;
943
944         /* concurrent cancels on the same handle can happen */
945         lock = __ldlm_handle2lock(lockh, LDLM_FL_CANCELING);
946         if (lock == NULL)
947                 RETURN(0);
948
949         rc = ldlm_cli_cancel_local(lock);
950         if (rc <= 0)
951                 GOTO(out, rc);
952
953         list_add(&lock->l_bl_ast, &head);
954         rc = ldlm_cli_cancel_req(lock->l_conn_export, &head, 1, 0);
955         EXIT;
956 out:
957         LDLM_LOCK_PUT(lock);
958         return rc < 0 ? rc : 0;
959 }
960
961 /* - Free space in lru for @count new locks,
962  *   redundant unused locks are canceled locally;
963  * - also cancel locally unused aged locks;
964  * - do not cancel more than @max locks;
965  * - GET the found locks and add them into the @cancels list.
966  *
967  * A client lock can be added to the l_bl_ast list only when it is
968  * marked LDLM_FL_CANCELING. Otherwise, somebody is already doing CANCEL.
969  * There are the following use cases: ldlm_cancel_resource_local(),
970  * ldlm_cancel_lru_local() and ldlm_cli_cancel(), which check&set this
971  * flag properly. As any attempt to cancel a lock rely on this flag,
972  * l_bl_ast list is accessed later without any special locking. */
973 int ldlm_cancel_lru_local(struct ldlm_namespace *ns, struct list_head *cancels,
974                           int count, int max, int flags)
975 {
976         cfs_time_t cur = cfs_time_current();
977         struct ldlm_lock *lock, *next;
978         int rc, added = 0, left;
979         ENTRY;
980
981         spin_lock(&ns->ns_unused_lock);
982         count += ns->ns_nr_unused - ns->ns_max_unused;
983         while (!list_empty(&ns->ns_unused_list)) {
984                 struct list_head *tmp = ns->ns_unused_list.next;
985                 lock = list_entry(tmp, struct ldlm_lock, l_lru);
986
987                 if (max && added >= max)
988                         break;
989
990                 if ((added >= count) && 
991                     (!(flags & LDLM_CANCEL_AGED) ||
992                      cfs_time_before_64(cur, ns->ns_max_age +
993                                         lock->l_last_used)))
994                         break;
995
996                 LDLM_LOCK_GET(lock); /* dropped by bl thread */
997                 spin_unlock(&ns->ns_unused_lock);
998
999                 lock_res_and_lock(lock);
1000                 if ((ldlm_lock_remove_from_lru(lock) == 0) ||
1001                     (lock->l_flags & LDLM_FL_CANCELING)) {
1002                         /* other thread is removing lock from lru or
1003                          * somebody is already doing CANCEL. */
1004                         unlock_res_and_lock(lock);
1005                         LDLM_LOCK_PUT(lock);
1006                         spin_lock(&ns->ns_unused_lock);
1007                         continue;
1008                 }
1009                 LASSERT(!lock->l_readers && !lock->l_writers);
1010
1011                 /* If we have chosen to canecl this lock voluntarily, we better
1012                    send cancel notification to server, so that it frees
1013                    appropriate state. This might lead to a race where while
1014                    we are doing cancel here, server is also silently
1015                    cancelling this lock. */
1016                 lock->l_flags &= ~LDLM_FL_CANCEL_ON_BLOCK;
1017
1018                 /* Setting the CBPENDING flag is a little misleading, but
1019                  * prevents an important race; namely, once CBPENDING is set,
1020                  * the lock can accumulate no more readers/writers.  Since
1021                  * readers and writers are already zero here, ldlm_lock_decref
1022                  * won't see this flag and call l_blocking_ast */
1023                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING;
1024                 /* We can't re-add to l_lru as it confuses the refcounting in
1025                  * ldlm_lock_remove_from_lru() if an AST arrives after we drop
1026                  * ns_lock below. We use l_bl_ast and can't use l_pending_chain
1027                  * as it is used both on server and client nevertheles bug 5666
1028                  * says it is used only on server. --umka */
1029
1030                 LASSERT(list_empty(&lock->l_bl_ast));
1031                 list_add(&lock->l_bl_ast, cancels);
1032                 unlock_res_and_lock(lock);
1033                 spin_lock(&ns->ns_unused_lock);
1034                 added++;
1035         }
1036         spin_unlock(&ns->ns_unused_lock);
1037
1038         /* Handle only @added inserted locks. */
1039         left = added;
1040         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1041                 if (left-- == 0)
1042                         break;
1043                 rc = ldlm_cli_cancel_local(lock);
1044                 if (rc == 0) {
1045                         /* CANCEL RPC should not be sent to server. */
1046                         list_del_init(&lock->l_bl_ast);
1047                         LDLM_LOCK_PUT(lock);
1048                         added--;
1049                 }
1050         } 
1051         RETURN(added);
1052 }
1053
1054 /* when called with LDLM_ASYNC the blocking callback will be handled
1055  * in a thread and this function will return after the thread has been
1056  * asked to call the callback.  when called with LDLM_SYNC the blocking
1057  * callback will be performed in this function. */
1058 int ldlm_cancel_lru(struct ldlm_namespace *ns, ldlm_sync_t sync)
1059 {
1060         CFS_LIST_HEAD(cancels);
1061         int count, rc;
1062         ENTRY;
1063
1064 #ifndef __KERNEL__
1065         sync = LDLM_SYNC; /* force to be sync in user space */
1066 #endif
1067         count = ldlm_cancel_lru_local(ns, &cancels, 0, 0, 0);
1068         if (sync == LDLM_ASYNC) {
1069                 struct ldlm_lock *lock, *next;
1070                 list_for_each_entry_safe(lock, next, &cancels, l_bl_ast) {
1071                         /* Remove from the list to allow blocking thread to
1072                          * re-use l_bl_ast. */
1073                         list_del_init(&lock->l_bl_ast);
1074                         rc = ldlm_bl_to_thread(ns, NULL, lock,
1075                                                LDLM_FL_CANCELING);
1076                         if (rc)
1077                                 list_add_tail(&lock->l_bl_ast, &next->l_bl_ast);
1078                 }
1079         }
1080
1081         /* If some locks are left in the list in ASYNC mode, or
1082          * this is SYNC mode, cancel the list. */
1083         ldlm_cli_cancel_list(&cancels, count, NULL, DLM_LOCKREQ_OFF, 0);
1084         RETURN(0);
1085 }
1086
1087 /* Find and cancel locally unused locks found on resource, matched to the
1088  * given policy, mode. GET the found locks and add them into the @cancels
1089  * list. */
1090 int ldlm_cancel_resource_local(struct ldlm_resource *res,
1091                                struct list_head *cancels,
1092                                ldlm_policy_data_t *policy,
1093                                ldlm_mode_t mode, int lock_flags,
1094                                int flags, void *opaque)
1095 {
1096         struct ldlm_lock *lock, *next;
1097         int count = 0, left;
1098         ENTRY;
1099
1100         lock_res(res);
1101         list_for_each_entry(lock, &res->lr_granted, l_res_link) {
1102                 if (opaque != NULL && lock->l_ast_data != opaque) {
1103                         LDLM_ERROR(lock, "data %p doesn't match opaque %p",
1104                                    lock->l_ast_data, opaque);
1105                         //LBUG();
1106                         continue;
1107                 }
1108
1109                 if (lock->l_readers || lock->l_writers) {
1110                         if (flags & LDLM_FL_WARN) {
1111                                 LDLM_ERROR(lock, "lock in use");
1112                                 //LBUG();
1113                         }
1114                         continue;
1115                 }
1116
1117                 if (lockmode_compat(lock->l_granted_mode, mode))
1118                         continue;
1119
1120                 /* If policy is given and this is IBITS lock, add to list only
1121                  * those locks that match by policy. */
1122                 if (policy && (lock->l_resource->lr_type == LDLM_IBITS) &&
1123                     !(lock->l_policy_data.l_inodebits.bits &
1124                       policy->l_inodebits.bits))
1125                         continue;
1126
1127                 /* If somebody is already doing CANCEL, skip it. */
1128                 if (lock->l_flags & LDLM_FL_CANCELING)
1129                         continue;
1130                 
1131                 /* See CBPENDING comment in ldlm_cancel_lru */
1132                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING |
1133                         lock_flags;
1134
1135                 LASSERT(list_empty(&lock->l_bl_ast));
1136                 list_add(&lock->l_bl_ast, cancels);
1137                 LDLM_LOCK_GET(lock);
1138                 count++;
1139         }
1140         unlock_res(res);
1141
1142         /* Handle only @count inserted locks. */
1143         left = count;
1144         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1145                 int rc = 0;
1146
1147                 if (left-- == 0)
1148                         break;
1149                 if (flags & LDLM_FL_LOCAL_ONLY)
1150                         ldlm_lock_cancel(lock);
1151                 else
1152                         rc = ldlm_cli_cancel_local(lock);
1153
1154                 if (rc == 0) {
1155                         /* CANCEL RPC should not be sent to server. */
1156                         list_del_init(&lock->l_bl_ast);
1157                         LDLM_LOCK_PUT(lock);
1158                         count--;
1159                 }
1160         }
1161         RETURN(count);
1162 }
1163
1164 /* If @req is NULL, send CANCEL request to server with handles of locks 
1165  * in the @cancels. If EARLY_CANCEL is not supported, send CANCEL requests 
1166  * separately per lock.
1167  * If @req is not NULL, put handles of locks in @cancels into the request 
1168  * buffer at the offset @off.
1169  * Destroy @cancels at the end. */
1170 int ldlm_cli_cancel_list(struct list_head *cancels, int count,
1171                          struct ptlrpc_request *req, int off, int flags)
1172 {
1173         struct ldlm_lock *lock;
1174         int res = 0;
1175         ENTRY;
1176
1177         if (list_empty(cancels) || count == 0)
1178                 RETURN(0);
1179         
1180         /* XXX: requests (both batched and not) could be sent in parallel. 
1181          * Usually it is enough to have just 1 RPC, but it is possible that
1182          * there are to many locks to be cancelled in LRU or on a resource.
1183          * It would also speed up the case when the server does not support
1184          * the feature. */
1185         while (count > 0) {
1186                 LASSERT(!list_empty(cancels));
1187                 lock = list_entry(cancels->next, struct ldlm_lock, l_bl_ast);
1188                 LASSERT(lock->l_conn_export);
1189
1190                 if (exp_connect_cancelset(lock->l_conn_export)) {
1191                         res = count;
1192                         if (req)
1193                                 ldlm_cancel_pack(req, off, cancels, count);
1194                         else
1195                                 res = ldlm_cli_cancel_req(lock->l_conn_export,
1196                                                           cancels, count, flags);
1197                 } else {
1198                         res = ldlm_cli_cancel_req(lock->l_conn_export,
1199                                                   cancels, 1, flags);
1200                 }
1201
1202                 if (res < 0) {
1203                         CERROR("ldlm_cli_cancel_list: %d\n", res);
1204                         res = count;
1205                 }
1206
1207                 count -= res;
1208                 ldlm_lock_list_put(cancels, l_bl_ast, res);
1209         }
1210         LASSERT(list_empty(cancels));
1211         LASSERT(count == 0);
1212         RETURN(0);
1213 }
1214
1215 int ldlm_cli_cancel_unused_resource(struct ldlm_namespace *ns,
1216                                     const struct ldlm_res_id *res_id,
1217                                     ldlm_policy_data_t *policy,
1218                                     int mode, int flags, void *opaque)
1219 {
1220         struct ldlm_resource *res;
1221         CFS_LIST_HEAD(cancels);
1222         int count;
1223         int rc;
1224         ENTRY;
1225
1226         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1227         if (res == NULL) {
1228                 /* This is not a problem. */
1229                 CDEBUG(D_INFO, "No resource "LPU64"\n", res_id->name[0]);
1230                 RETURN(0);
1231         }
1232
1233         count = ldlm_cancel_resource_local(res, &cancels, policy, mode,
1234                                            0, flags, opaque);
1235         rc = ldlm_cli_cancel_list(&cancels, count, NULL,
1236                                   DLM_LOCKREQ_OFF, flags);
1237         if (rc != ELDLM_OK)
1238                 CERROR("ldlm_cli_cancel_unused_resource: %d\n", rc);
1239
1240         ldlm_resource_putref(res);
1241         RETURN(0);
1242 }
1243
1244 static inline int have_no_nsresource(struct ldlm_namespace *ns)
1245 {
1246         int no_resource = 0;
1247
1248         spin_lock(&ns->ns_hash_lock);
1249         if (ns->ns_resources == 0)
1250                 no_resource = 1;
1251         spin_unlock(&ns->ns_hash_lock);
1252
1253         RETURN(no_resource);
1254 }
1255
1256 /* Cancel all locks on a namespace (or a specific resource, if given)
1257  * that have 0 readers/writers.
1258  *
1259  * If flags & LDLM_FL_LOCAL_ONLY, throw the locks away without trying
1260  * to notify the server. */
1261 int ldlm_cli_cancel_unused(struct ldlm_namespace *ns,
1262                            const struct ldlm_res_id *res_id,
1263                            int flags, void *opaque)
1264 {
1265         int i;
1266         ENTRY;
1267
1268         if (ns == NULL)
1269                 RETURN(ELDLM_OK);
1270
1271         if (res_id)
1272                 RETURN(ldlm_cli_cancel_unused_resource(ns, res_id, NULL,
1273                                                        LCK_MINMODE, flags,
1274                                                        opaque));
1275
1276         spin_lock(&ns->ns_hash_lock);
1277         for (i = 0; i < RES_HASH_SIZE; i++) {
1278                 struct list_head *tmp;
1279                 tmp = ns->ns_hash[i].next;
1280                 while (tmp != &(ns->ns_hash[i])) {
1281                         struct ldlm_resource *res;
1282                         int rc;
1283
1284                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1285                         ldlm_resource_getref(res);
1286                         spin_unlock(&ns->ns_hash_lock);
1287
1288                         rc = ldlm_cli_cancel_unused_resource(ns, &res->lr_name,
1289                                                              NULL, LCK_MINMODE,
1290                                                              flags, opaque);
1291
1292                         if (rc)
1293                                 CERROR("ldlm_cli_cancel_unused ("LPU64"): %d\n",
1294                                        res->lr_name.name[0], rc);
1295
1296                         spin_lock(&ns->ns_hash_lock);
1297                         tmp = tmp->next;
1298                         ldlm_resource_putref_locked(res);
1299                 }
1300         }
1301         spin_unlock(&ns->ns_hash_lock);
1302
1303         RETURN(ELDLM_OK);
1304 }
1305
1306 /* join/split resource locks to/from lru list */
1307 int ldlm_cli_join_lru(struct ldlm_namespace *ns,
1308                       const struct ldlm_res_id *res_id, int join)
1309 {
1310         struct ldlm_resource *res;
1311         struct ldlm_lock *lock, *n;
1312         int count = 0;
1313         ENTRY;
1314
1315         LASSERT(ns->ns_client == LDLM_NAMESPACE_CLIENT);
1316
1317         res = ldlm_resource_get(ns, NULL, res_id, LDLM_EXTENT, 0);
1318         if (res == NULL)
1319                 RETURN(count);
1320         LASSERT(res->lr_type == LDLM_EXTENT);
1321
1322         lock_res(res);
1323         if (!join)
1324                 goto split;
1325
1326         list_for_each_entry_safe (lock, n, &res->lr_granted, l_res_link) {
1327                 if (list_empty(&lock->l_lru) &&
1328                     !lock->l_readers && !lock->l_writers &&
1329                     !(lock->l_flags & LDLM_FL_LOCAL) &&
1330                     !(lock->l_flags & LDLM_FL_CBPENDING)) {
1331                         lock->l_last_used = cfs_time_current();
1332                         spin_lock(&ns->ns_unused_lock);
1333                         LASSERT(ns->ns_nr_unused >= 0);
1334                         list_add_tail(&lock->l_lru, &ns->ns_unused_list);
1335                         ns->ns_nr_unused++;
1336                         spin_unlock(&ns->ns_unused_lock);
1337                         lock->l_flags &= ~LDLM_FL_NO_LRU;
1338                         LDLM_DEBUG(lock, "join lock to lru");
1339                         count++;
1340                 }
1341         }
1342         goto unlock;
1343 split:
1344         spin_lock(&ns->ns_unused_lock);
1345         list_for_each_entry_safe (lock, n, &ns->ns_unused_list, l_lru) {
1346                 if (lock->l_resource == res) {
1347                         ldlm_lock_remove_from_lru_nolock(lock);
1348                         lock->l_flags |= LDLM_FL_NO_LRU;
1349                         LDLM_DEBUG(lock, "split lock from lru");
1350                         count++;
1351                 }
1352         }
1353         spin_unlock(&ns->ns_unused_lock);
1354 unlock:
1355         unlock_res(res);
1356         ldlm_resource_putref(res);
1357         RETURN(count);
1358 }
1359
1360 /* Lock iterators. */
1361
1362 int ldlm_resource_foreach(struct ldlm_resource *res, ldlm_iterator_t iter,
1363                           void *closure)
1364 {
1365         struct list_head *tmp, *next;
1366         struct ldlm_lock *lock;
1367         int rc = LDLM_ITER_CONTINUE;
1368
1369         ENTRY;
1370
1371         if (!res)
1372                 RETURN(LDLM_ITER_CONTINUE);
1373
1374         lock_res(res);
1375         list_for_each_safe(tmp, next, &res->lr_granted) {
1376                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1377
1378                 if (iter(lock, closure) == LDLM_ITER_STOP)
1379                         GOTO(out, rc = LDLM_ITER_STOP);
1380         }
1381
1382         list_for_each_safe(tmp, next, &res->lr_converting) {
1383                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1384
1385                 if (iter(lock, closure) == LDLM_ITER_STOP)
1386                         GOTO(out, rc = LDLM_ITER_STOP);
1387         }
1388
1389         list_for_each_safe(tmp, next, &res->lr_waiting) {
1390                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1391
1392                 if (iter(lock, closure) == LDLM_ITER_STOP)
1393                         GOTO(out, rc = LDLM_ITER_STOP);
1394         }
1395  out:
1396         unlock_res(res);
1397         RETURN(rc);
1398 }
1399
1400 struct iter_helper_data {
1401         ldlm_iterator_t iter;
1402         void *closure;
1403 };
1404
1405 static int ldlm_iter_helper(struct ldlm_lock *lock, void *closure)
1406 {
1407         struct iter_helper_data *helper = closure;
1408         return helper->iter(lock, helper->closure);
1409 }
1410
1411 static int ldlm_res_iter_helper(struct ldlm_resource *res, void *closure)
1412 {
1413         return ldlm_resource_foreach(res, ldlm_iter_helper, closure);
1414 }
1415
1416 int ldlm_namespace_foreach(struct ldlm_namespace *ns, ldlm_iterator_t iter,
1417                            void *closure)
1418 {
1419         struct iter_helper_data helper = { iter: iter, closure: closure };
1420         return ldlm_namespace_foreach_res(ns, ldlm_res_iter_helper, &helper);
1421 }
1422
1423 int ldlm_namespace_foreach_res(struct ldlm_namespace *ns,
1424                                ldlm_res_iterator_t iter, void *closure)
1425 {
1426         int i, rc = LDLM_ITER_CONTINUE;
1427         struct ldlm_resource *res;
1428         struct list_head *tmp;
1429
1430         ENTRY;
1431         spin_lock(&ns->ns_hash_lock);
1432         for (i = 0; i < RES_HASH_SIZE; i++) {
1433                 tmp = ns->ns_hash[i].next;
1434                 while (tmp != &(ns->ns_hash[i])) {
1435                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1436                         ldlm_resource_getref(res);
1437                         spin_unlock(&ns->ns_hash_lock);
1438
1439                         rc = iter(res, closure);
1440
1441                         spin_lock(&ns->ns_hash_lock);
1442                         tmp = tmp->next;
1443                         ldlm_resource_putref_locked(res);
1444                         if (rc == LDLM_ITER_STOP)
1445                                 GOTO(out, rc);
1446                 }
1447         }
1448  out:
1449         spin_unlock(&ns->ns_hash_lock);
1450         RETURN(rc);
1451 }
1452
1453 /* non-blocking function to manipulate a lock whose cb_data is being put away.*/
1454 void ldlm_resource_iterate(struct ldlm_namespace *ns,
1455                            const struct ldlm_res_id *res_id,
1456                            ldlm_iterator_t iter, void *data)
1457 {
1458         struct ldlm_resource *res;
1459         ENTRY;
1460
1461         if (ns == NULL) {
1462                 CERROR("must pass in namespace\n");
1463                 LBUG();
1464         }
1465
1466         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1467         if (res == NULL) {
1468                 EXIT;
1469                 return;
1470         }
1471
1472         ldlm_resource_foreach(res, iter, data);
1473         ldlm_resource_putref(res);
1474         EXIT;
1475 }
1476
1477 /* Lock replay */
1478
1479 static int ldlm_chain_lock_for_replay(struct ldlm_lock *lock, void *closure)
1480 {
1481         struct list_head *list = closure;
1482
1483         /* we use l_pending_chain here, because it's unused on clients. */
1484         LASSERTF(list_empty(&lock->l_pending_chain),"lock %p next %p prev %p\n",
1485                  lock, &lock->l_pending_chain.next,&lock->l_pending_chain.prev);
1486         /* bug 9573: don't replay locks left after eviction */
1487         if (!(lock->l_flags & LDLM_FL_FAILED))
1488                 list_add(&lock->l_pending_chain, list);
1489         return LDLM_ITER_CONTINUE;
1490 }
1491
1492 static int replay_lock_interpret(struct ptlrpc_request *req,
1493                                  struct ldlm_async_args *aa, int rc)
1494 {
1495         struct ldlm_lock *lock;
1496         struct ldlm_reply *reply;
1497
1498         ENTRY;
1499         atomic_dec(&req->rq_import->imp_replay_inflight);
1500         if (rc != ELDLM_OK)
1501                 GOTO(out, rc);
1502
1503
1504         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
1505                                    lustre_swab_ldlm_reply);
1506         if (reply == NULL) {
1507                 CERROR("Can't unpack ldlm_reply\n");
1508                 GOTO (out, rc = -EPROTO);
1509         }
1510
1511         lock = ldlm_handle2lock(&aa->lock_handle);
1512         if (!lock) {
1513                 CERROR("received replay ack for unknown local cookie "LPX64
1514                        " remote cookie "LPX64 " from server %s id %s\n",
1515                        aa->lock_handle.cookie, reply->lock_handle.cookie,
1516                        req->rq_export->exp_client_uuid.uuid,
1517                        libcfs_id2str(req->rq_peer));
1518                 GOTO(out, rc = -ESTALE);
1519         }
1520
1521         lock->l_remote_handle = reply->lock_handle;
1522         LDLM_DEBUG(lock, "replayed lock:");
1523         ptlrpc_import_recovery_state_machine(req->rq_import);
1524         LDLM_LOCK_PUT(lock);
1525 out:
1526         if (rc != ELDLM_OK)
1527                 ptlrpc_connect_import(req->rq_import, NULL);
1528
1529
1530         RETURN(rc);
1531 }
1532
1533 static int replay_one_lock(struct obd_import *imp, struct ldlm_lock *lock)
1534 {
1535         struct ptlrpc_request *req;
1536         struct ldlm_request *body;
1537         struct ldlm_reply *reply;
1538         struct ldlm_async_args *aa;
1539         int buffers = 2;
1540         int size[3] = { sizeof(struct ptlrpc_body) };
1541         int flags;
1542         ENTRY;
1543
1544
1545         /* Bug 11974: Do not replay a lock which is actively being canceled */
1546         if (lock->l_flags & LDLM_FL_CANCELING) {
1547                 LDLM_DEBUG(lock, "Not replaying canceled lock:");
1548                 RETURN(0);
1549         }
1550
1551         /* If this is reply-less callback lock, we cannot replay it, since
1552          * server might have long dropped it, but notification of that event was
1553          * lost by network. (and server granted conflicting lock already) */
1554         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1555                 LDLM_DEBUG(lock, "Not replaying reply-less lock:");
1556                 ldlm_lock_cancel(lock);
1557                 RETURN(0);
1558         }
1559         /*
1560          * If granted mode matches the requested mode, this lock is granted.
1561          *
1562          * If they differ, but we have a granted mode, then we were granted
1563          * one mode and now want another: ergo, converting.
1564          *
1565          * If we haven't been granted anything and are on a resource list,
1566          * then we're blocked/waiting.
1567          *
1568          * If we haven't been granted anything and we're NOT on a resource list,
1569          * then we haven't got a reply yet and don't have a known disposition.
1570          * This happens whenever a lock enqueue is the request that triggers
1571          * recovery.
1572          */
1573         if (lock->l_granted_mode == lock->l_req_mode)
1574                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_GRANTED;
1575         else if (lock->l_granted_mode)
1576                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_CONV;
1577         else if (!list_empty(&lock->l_res_link))
1578                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_WAIT;
1579         else
1580                 flags = LDLM_FL_REPLAY;
1581
1582         size[DLM_LOCKREQ_OFF] = sizeof(*body);
1583         req = ptlrpc_prep_req(imp, LUSTRE_DLM_VERSION, LDLM_ENQUEUE, 2, size,
1584                               NULL);
1585         if (!req)
1586                 RETURN(-ENOMEM);
1587
1588         /* We're part of recovery, so don't wait for it. */
1589         req->rq_send_state = LUSTRE_IMP_REPLAY_LOCKS;
1590
1591         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
1592         ldlm_lock2desc(lock, &body->lock_desc);
1593         body->lock_flags = flags;
1594
1595         ldlm_lock2handle(lock, &body->lock_handle[0]);
1596         size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
1597         if (lock->l_lvb_len != 0) {
1598                 buffers = 3;
1599                 size[DLM_REPLY_REC_OFF] = lock->l_lvb_len;
1600         }
1601         ptlrpc_req_set_repsize(req, buffers, size);
1602         /* notify the server we've replayed all requests.
1603          * also, we mark the request to be put on a dedicated
1604          * queue to be processed after all request replayes.
1605          * bug 6063 */
1606         lustre_msg_set_flags(req->rq_reqmsg, MSG_REQ_REPLAY_DONE);
1607
1608         LDLM_DEBUG(lock, "replaying lock:");
1609
1610         atomic_inc(&req->rq_import->imp_replay_inflight);
1611         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
1612         aa = (struct ldlm_async_args *)&req->rq_async_args;
1613         aa->lock_handle = body->lock_handle[0];
1614         req->rq_interpret_reply = replay_lock_interpret;
1615         ptlrpcd_add_req(req);
1616
1617         RETURN(0);
1618 }
1619
1620 int ldlm_replay_locks(struct obd_import *imp)
1621 {
1622         struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
1623         struct list_head list;
1624         struct ldlm_lock *lock, *next;
1625         int rc = 0;
1626
1627         ENTRY;
1628         CFS_INIT_LIST_HEAD(&list);
1629
1630         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
1631
1632         /* ensure this doesn't fall to 0 before all have been queued */
1633         atomic_inc(&imp->imp_replay_inflight);
1634
1635         (void)ldlm_namespace_foreach(ns, ldlm_chain_lock_for_replay, &list);
1636
1637         list_for_each_entry_safe(lock, next, &list, l_pending_chain) {
1638                 list_del_init(&lock->l_pending_chain);
1639                 if (rc)
1640                         continue; /* or try to do the rest? */
1641                 rc = replay_one_lock(imp, lock);
1642         }
1643
1644         atomic_dec(&imp->imp_replay_inflight);
1645
1646         RETURN(rc);
1647 }