Whamcloud - gitweb
25b742b6061eb1706b10a81ed93fbb5c8ca7076c
[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 @cancels. */
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                      struct ldlm_enqueue_info *einfo,
543                      const struct ldlm_res_id *res_id,
544                      ldlm_policy_data_t *policy, int *flags,
545                      void *lvb, __u32 lvb_len, void *lvb_swabber,
546                      struct lustre_handle *lockh, int async)
547 {
548         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
549         struct ldlm_lock *lock;
550         struct ldlm_request *body;
551         struct ldlm_reply *reply;
552         int size[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
553                         [DLM_LOCKREQ_OFF]     = sizeof(*body),
554                         [DLM_REPLY_REC_OFF]   = lvb_len };
555         int is_replay = *flags & LDLM_FL_REPLAY;
556         int req_passed_in = 1, rc, err;
557         struct ptlrpc_request *req;
558         ENTRY;
559
560         LASSERT(exp != NULL);
561
562         /* If we're replaying this lock, just check some invariants.
563          * If we're creating a new lock, get everything all setup nice. */
564         if (is_replay) {
565                 lock = ldlm_handle2lock(lockh);
566                 LASSERT(lock != NULL);
567                 LDLM_DEBUG(lock, "client-side enqueue START");
568                 LASSERT(exp == lock->l_conn_export);
569         } else {
570                 lock = ldlm_lock_create(ns, res_id, einfo->ei_type,
571                                         einfo->ei_mode, einfo->ei_cb_bl,
572                                         einfo->ei_cb_cp, einfo->ei_cb_gl,
573                                         einfo->ei_cbdata, lvb_len);
574                 if (lock == NULL)
575                         RETURN(-ENOMEM);
576                 /* for the local lock, add the reference */
577                 ldlm_lock_addref_internal(lock, einfo->ei_mode);
578                 ldlm_lock2handle(lock, lockh);
579                 lock->l_lvb_swabber = lvb_swabber;
580                 if (policy != NULL) {
581                         /* INODEBITS_INTEROP: If the server does not support
582                          * inodebits, we will request a plain lock in the
583                          * descriptor (ldlm_lock2desc() below) but use an
584                          * inodebits lock internally with both bits set.
585                          */
586                         if (einfo->ei_type == LDLM_IBITS &&
587                             !(exp->exp_connect_flags & OBD_CONNECT_IBITS))
588                                 lock->l_policy_data.l_inodebits.bits =
589                                         MDS_INODELOCK_LOOKUP |
590                                         MDS_INODELOCK_UPDATE;
591                         else
592                                 lock->l_policy_data = *policy;
593                 }
594
595                 if (einfo->ei_type == LDLM_EXTENT)
596                         lock->l_req_extent = policy->l_extent;
597                 LDLM_DEBUG(lock, "client-side enqueue START");
598         }
599
600         /* lock not sent to server yet */
601
602         if (reqp == NULL || *reqp == NULL) {
603                 req = ldlm_prep_enqueue_req(exp, 2, size, NULL, 0);
604                 if (req == NULL) {
605                         failed_lock_cleanup(ns, lock, lockh, einfo->ei_mode);
606                         LDLM_LOCK_PUT(lock);
607                         RETURN(-ENOMEM);
608                 }
609                 req_passed_in = 0;
610                 if (reqp)
611                         *reqp = req;
612         } else {
613                 req = *reqp;
614                 LASSERTF(lustre_msg_buflen(req->rq_reqmsg, DLM_LOCKREQ_OFF) >=
615                          sizeof(*body), "buflen[%d] = %d, not "LPSZ"\n",
616                          DLM_LOCKREQ_OFF,
617                          lustre_msg_buflen(req->rq_reqmsg, DLM_LOCKREQ_OFF),
618                          sizeof(*body));
619         }
620
621         lock->l_conn_export = exp;
622         lock->l_export = NULL;
623         lock->l_blocking_ast = einfo->ei_cb_bl;
624
625         /* Dump lock data into the request buffer */
626         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
627         ldlm_lock2desc(lock, &body->lock_desc);
628         body->lock_flags = *flags;
629         body->lock_handle[0] = *lockh;
630
631         /* Continue as normal. */
632         if (!req_passed_in) {
633                 size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
634                 ptlrpc_req_set_repsize(req, 2 + (lvb_len > 0), size);
635         }
636
637         /*
638          * Liblustre client doesn't get extent locks, except for O_APPEND case
639          * where [0, OBD_OBJECT_EOF] lock is taken, or truncate, where
640          * [i_size, OBD_OBJECT_EOF] lock is taken.
641          */
642         LASSERT(ergo(LIBLUSTRE_CLIENT, einfo->ei_type != LDLM_EXTENT ||
643                      policy->l_extent.end == OBD_OBJECT_EOF));
644
645         if (async) {
646                 LASSERT(reqp != NULL);
647                 RETURN(0);
648         }
649
650         LDLM_DEBUG(lock, "sending request");
651         rc = ptlrpc_queue_wait(req);
652         err = ldlm_cli_enqueue_fini(exp, req, einfo->ei_type, policy ? 1 : 0,
653                                     einfo->ei_mode, flags, lvb, lvb_len,
654                                     lvb_swabber, lockh, rc);
655
656         /* If ldlm_cli_enqueue_fini did not find the lock, we need to free
657          * one reference that we took */
658         if (err == -ENOLCK)
659                 LDLM_LOCK_PUT(lock);
660         else
661                 rc = err;
662
663         if (!req_passed_in && req != NULL) {
664                 ptlrpc_req_finished(req);
665                 if (reqp)
666                         *reqp = NULL;
667         }
668
669         RETURN(rc);
670 }
671
672 static int ldlm_cli_convert_local(struct ldlm_lock *lock, int new_mode,
673                                   int *flags)
674 {
675         struct ldlm_resource *res;
676         int rc;
677         ENTRY;
678         if (lock->l_resource->lr_namespace->ns_client) {
679                 CERROR("Trying to cancel local lock\n");
680                 LBUG();
681         }
682         LDLM_DEBUG(lock, "client-side local convert");
683
684         res = ldlm_lock_convert(lock, new_mode, flags);
685         if (res) {
686                 ldlm_reprocess_all(res);
687                 rc = 0;
688         } else {
689                 rc = EDEADLOCK;
690         }
691         LDLM_DEBUG(lock, "client-side local convert handler END");
692         LDLM_LOCK_PUT(lock);
693         RETURN(rc);
694 }
695
696 /* FIXME: one of ldlm_cli_convert or the server side should reject attempted
697  * conversion of locks which are on the waiting or converting queue */
698 /* Caller of this code is supposed to take care of lock readers/writers
699    accounting */
700 int ldlm_cli_convert(struct lustre_handle *lockh, int new_mode, int *flags)
701 {
702         struct ldlm_request *body;
703         struct ldlm_reply *reply;
704         struct ldlm_lock *lock;
705         struct ldlm_resource *res;
706         struct ptlrpc_request *req;
707         int size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
708                         [DLM_LOCKREQ_OFF]     = sizeof(*body) };
709         int rc;
710         ENTRY;
711
712         lock = ldlm_handle2lock(lockh);
713         if (!lock) {
714                 LBUG();
715                 RETURN(-EINVAL);
716         }
717         *flags = 0;
718
719         if (lock->l_conn_export == NULL)
720                 RETURN(ldlm_cli_convert_local(lock, new_mode, flags));
721
722         LDLM_DEBUG(lock, "client-side convert");
723
724         req = ptlrpc_prep_req(class_exp2cliimp(lock->l_conn_export),
725                               LUSTRE_DLM_VERSION, LDLM_CONVERT, 2, size, NULL);
726         if (!req)
727                 GOTO(out, rc = -ENOMEM);
728
729         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
730         body->lock_handle[0] = lock->l_remote_handle;
731
732         body->lock_desc.l_req_mode = new_mode;
733         body->lock_flags = *flags;
734
735         size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
736         ptlrpc_req_set_repsize(req, 2, size);
737
738         rc = ptlrpc_queue_wait(req);
739         if (rc != ELDLM_OK)
740                 GOTO(out, rc);
741
742         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
743                                    lustre_swab_ldlm_reply);
744         if (reply == NULL) {
745                 CERROR ("Can't unpack ldlm_reply\n");
746                 GOTO (out, rc = -EPROTO);
747         }
748
749         if (req->rq_status)
750                 GOTO(out, rc = req->rq_status);
751
752         res = ldlm_lock_convert(lock, new_mode, &reply->lock_flags);
753         if (res != NULL) {
754                 ldlm_reprocess_all(res);
755                 /* Go to sleep until the lock is granted. */
756                 /* FIXME: or cancelled. */
757                 if (lock->l_completion_ast) {
758                         rc = lock->l_completion_ast(lock, LDLM_FL_WAIT_NOREPROC,
759                                                     NULL);
760                         if (rc)
761                                 GOTO(out, rc);
762                 }
763         } else {
764                 rc = EDEADLOCK;
765         }
766         EXIT;
767  out:
768         LDLM_LOCK_PUT(lock);
769         ptlrpc_req_finished(req);
770         return rc;
771 }
772
773 /* Cancel locks locally.
774  * Returns:
775  * LDLM_FL_LOCAL_ONLY if tere is no need in a CANCEL rpc to the server;
776  * LDLM_FL_CANCELING otherwise;
777  * LDLM_FL_BL_AST if there is a need in a separate CANCEL rpc. */
778 static int ldlm_cli_cancel_local(struct ldlm_lock *lock)
779 {
780         int rc = LDLM_FL_LOCAL_ONLY;
781         ENTRY;
782         
783         if (lock->l_conn_export) {
784                 int local_only;
785
786                 LDLM_DEBUG(lock, "client-side cancel");
787                 /* Set this flag to prevent others from getting new references*/
788                 lock_res_and_lock(lock);
789                 lock->l_flags |= LDLM_FL_CBPENDING;
790                 local_only = (lock->l_flags &
791                               (LDLM_FL_LOCAL_ONLY|LDLM_FL_CANCEL_ON_BLOCK));
792                 ldlm_cancel_callback(lock);
793                 rc = (lock->l_flags & LDLM_FL_BL_AST) ?
794                         LDLM_FL_BL_AST : LDLM_FL_CANCELING;
795                 unlock_res_and_lock(lock);
796
797                 if (local_only) {
798                         CDEBUG(D_DLMTRACE, "not sending request (at caller's "
799                                "instruction)\n");
800                         rc = LDLM_FL_LOCAL_ONLY;
801                 }
802                 ldlm_lock_cancel(lock);
803         } else {
804                 if (lock->l_resource->lr_namespace->ns_client) {
805                         LDLM_ERROR(lock, "Trying to cancel local lock");
806                         LBUG();
807                 }
808                 LDLM_DEBUG(lock, "server-side local cancel");
809                 ldlm_lock_cancel(lock);
810                 ldlm_reprocess_all(lock->l_resource);
811                 LDLM_DEBUG(lock, "server-side local cancel handler END");
812         }
813
814         RETURN(rc);
815 }
816
817 /* Pack @count locks in @head into ldlm_request buffer at the offset @off,
818    of the request @req. */
819 static void ldlm_cancel_pack(struct ptlrpc_request *req, int off,
820                              struct list_head *head, int count)
821 {
822         struct ldlm_request *dlm;
823         struct ldlm_lock *lock;
824         int max, packed = 0;
825         ENTRY;
826
827         dlm = lustre_msg_buf(req->rq_reqmsg, off, sizeof(*dlm));
828         LASSERT(dlm != NULL);
829
830         /* Check the room in the request buffer. */
831         max = lustre_msg_buflen(req->rq_reqmsg, off) - 
832                 sizeof(struct ldlm_request);
833         max /= sizeof(struct lustre_handle);
834         max += LDLM_LOCKREQ_HANDLES;
835         LASSERT(max >= dlm->lock_count + count);
836
837         /* XXX: it would be better to pack lock handles grouped by resource.
838          * so that the server cancel would call filter_lvbo_update() less
839          * frequently. */
840         list_for_each_entry(lock, head, l_bl_ast) {
841                 if (!count--)
842                         break;
843                 LASSERT(lock->l_conn_export);
844                 /* Pack the lock handle to the given request buffer. */
845                 LDLM_DEBUG(lock, "packing");
846                 dlm->lock_handle[dlm->lock_count++] = lock->l_remote_handle;
847                 packed++;
848         }
849         CDEBUG(D_DLMTRACE, "%d locks packed\n", packed);
850         EXIT;
851 }
852
853 /* Prepare and send a batched cancel rpc, it will include count lock handles
854  * of locks given in @head. */
855 int ldlm_cli_cancel_req(struct obd_export *exp, struct list_head *cancels,
856                         int count, int flags)
857 {
858         struct ptlrpc_request *req = NULL;
859         struct ldlm_request *body;
860         int size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
861                 [DLM_LOCKREQ_OFF]     = sizeof(*body) };
862         struct obd_import *imp;
863         int free, sent = 0;
864         int rc = 0;
865         ENTRY;
866
867         LASSERT(exp != NULL);
868         LASSERT(count > 0);
869
870         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_RACE))
871                 RETURN(count);
872
873         free = ldlm_req_handles_avail(exp, size, 2, 0);
874         if (count > free)
875                 count = free;
876
877         size[DLM_LOCKREQ_OFF] = ldlm_request_bufsize(count, LDLM_CANCEL);
878         while (1) {
879                 imp = class_exp2cliimp(exp);
880                 if (imp == NULL || imp->imp_invalid) {
881                         CDEBUG(D_HA, "skipping cancel on invalid import %p\n",
882                                imp);
883                         break;
884                 }
885
886                 req = ptlrpc_prep_req(imp, LUSTRE_DLM_VERSION, LDLM_CANCEL, 2,
887                                       size, NULL);
888                 if (!req)
889                         GOTO(out, rc = -ENOMEM);
890
891                 req->rq_no_resend = 1;
892                 req->rq_no_delay = 1;
893
894                 /* XXX FIXME bug 249 */
895                 req->rq_request_portal = LDLM_CANCEL_REQUEST_PORTAL;
896                 req->rq_reply_portal = LDLM_CANCEL_REPLY_PORTAL;
897
898                 body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF,
899                                       sizeof(*body));
900                 ldlm_cancel_pack(req, DLM_LOCKREQ_OFF, cancels, count);
901
902                 ptlrpc_req_set_repsize(req, 1, NULL);
903                 if (flags & LDLM_FL_ASYNC) {
904                         ptlrpcd_add_req(req);
905                         sent = count;
906                         GOTO(out, 0);
907                 } else {
908                         rc = ptlrpc_queue_wait(req);
909                 }
910                 if (rc == ESTALE) {
911                         CDEBUG(D_DLMTRACE, "client/server (nid %s) "
912                                "out of sync -- not fatal\n",
913                                libcfs_nid2str(req->rq_import->
914                                               imp_connection->c_peer.nid));
915                 } else if (rc == -ETIMEDOUT && /* check there was no reconnect*/
916                            req->rq_import_generation == imp->imp_generation) {
917                         ptlrpc_req_finished(req);
918                         continue;
919                 } else if (rc != ELDLM_OK) {
920                         CERROR("Got rc %d from cancel RPC: canceling "
921                                "anyway\n", rc);
922                         break;
923                 }
924                 sent = count;
925                 break;
926         }
927
928         ptlrpc_req_finished(req);
929         EXIT;
930 out:
931         return sent ? sent : rc;
932 }
933
934 int ldlm_cli_cancel(struct lustre_handle *lockh)
935 {
936         struct ldlm_lock *lock;
937         CFS_LIST_HEAD(head);
938         int rc = 0;
939         ENTRY;
940
941         /* concurrent cancels on the same handle can happen */
942         lock = __ldlm_handle2lock(lockh, LDLM_FL_CANCELING);
943         if (lock == NULL) {
944                 LDLM_DEBUG_NOLOCK("lock is already being destroyed\n");
945                 RETURN(0);
946         }
947         
948         rc = ldlm_cli_cancel_local(lock);
949         if (rc < 0 || rc == LDLM_FL_LOCAL_ONLY)
950                 GOTO(out, rc);
951
952         list_add(&lock->l_bl_ast, &head);
953         rc = ldlm_cli_cancel_req(lock->l_conn_export, &head, 1, 0);
954         EXIT;
955 out:
956         LDLM_LOCK_PUT(lock);
957         return rc < 0 ? rc : 0;
958 }
959
960 /* - Free space in lru for @count new locks,
961  *   redundant unused locks are canceled locally;
962  * - also cancel locally unused aged locks;
963  * - do not cancel more than @max locks;
964  * - GET the found locks and add them into the @cancels list.
965  *
966  * A client lock can be added to the l_bl_ast list only when it is
967  * marked LDLM_FL_CANCELING. Otherwise, somebody is already doing CANCEL.
968  * There are the following use cases: ldlm_cancel_resource_local(),
969  * ldlm_cancel_lru_local() and ldlm_cli_cancel(), which check&set this
970  * flag properly. As any attempt to cancel a lock rely on this flag,
971  * l_bl_ast list is accessed later without any special locking. */
972 int ldlm_cancel_lru_local(struct ldlm_namespace *ns, struct list_head *cancels,
973                           int count, int max, int flags)
974 {
975         cfs_time_t cur = cfs_time_current();
976         struct ldlm_lock *lock, *next;
977         int rc, added = 0, left;
978         ENTRY;
979
980         spin_lock(&ns->ns_unused_lock);
981         count += ns->ns_nr_unused - ns->ns_max_unused;
982         while (!list_empty(&ns->ns_unused_list)) {
983                 if (max && added >= max)
984                         break;
985
986                 list_for_each_entry(lock, &ns->ns_unused_list, l_lru) {
987                         /* somebody is already doing CANCEL or there is a
988                          * blocking request will send cancel. */
989                         if (!(lock->l_flags & LDLM_FL_CANCELING) &&
990                             !(lock->l_flags & LDLM_FL_BL_AST))
991                                 break;
992                 }
993                 if (&lock->l_lru == &ns->ns_unused_list)
994                         break;
995
996                 if ((added >= count) && 
997                     (!(flags & LDLM_CANCEL_AGED) ||
998                      cfs_time_before_64(cur, (__u64)ns->ns_max_age +
999                                         lock->l_last_used)))
1000                         break;
1001
1002                 LDLM_LOCK_GET(lock); /* dropped by bl thread */
1003                 spin_unlock(&ns->ns_unused_lock);
1004
1005                 lock_res_and_lock(lock);
1006                 /* Check flags again under the lock. */
1007                 if ((lock->l_flags & LDLM_FL_CANCELING) ||
1008                     (lock->l_flags & LDLM_FL_BL_AST) ||
1009                     (ldlm_lock_remove_from_lru(lock) == 0)) {
1010                         /* other thread is removing lock from lru or
1011                          * somebody is already doing CANCEL or
1012                          * there is a blocking request which will send
1013                          * cancel by itseft. */
1014                         unlock_res_and_lock(lock);
1015                         LDLM_LOCK_PUT(lock);
1016                         spin_lock(&ns->ns_unused_lock);
1017                         continue;
1018                 }
1019                 LASSERT(!lock->l_readers && !lock->l_writers);
1020
1021                 /* If we have chosen to canecl this lock voluntarily, we better
1022                    send cancel notification to server, so that it frees
1023                    appropriate state. This might lead to a race where while
1024                    we are doing cancel here, server is also silently
1025                    cancelling this lock. */
1026                 lock->l_flags &= ~LDLM_FL_CANCEL_ON_BLOCK;
1027
1028                 /* Setting the CBPENDING flag is a little misleading, but
1029                  * prevents an important race; namely, once CBPENDING is set,
1030                  * the lock can accumulate no more readers/writers.  Since
1031                  * readers and writers are already zero here, ldlm_lock_decref
1032                  * won't see this flag and call l_blocking_ast */
1033                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING;
1034                 /* We can't re-add to l_lru as it confuses the refcounting in
1035                  * ldlm_lock_remove_from_lru() if an AST arrives after we drop
1036                  * ns_lock below. We use l_bl_ast and can't use l_pending_chain
1037                  * as it is used both on server and client nevertheles bug 5666
1038                  * says it is used only on server. --umka */
1039
1040                 LASSERT(list_empty(&lock->l_bl_ast));
1041                 list_add(&lock->l_bl_ast, cancels);
1042                 unlock_res_and_lock(lock);
1043                 spin_lock(&ns->ns_unused_lock);
1044                 added++;
1045         }
1046         spin_unlock(&ns->ns_unused_lock);
1047
1048         /* Handle only @added inserted locks. */
1049         left = added;
1050         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1051                 if (left-- == 0)
1052                         break;
1053
1054                 rc = ldlm_cli_cancel_local(lock);
1055                 if (rc == LDLM_FL_BL_AST) {
1056                         CFS_LIST_HEAD(head);
1057
1058                         LDLM_DEBUG(lock, "Cancel lock separately");
1059                         list_del_init(&lock->l_bl_ast);
1060                         list_add(&lock->l_bl_ast, &head);
1061                         ldlm_cli_cancel_req(lock->l_conn_export, &head, 1, 0);
1062                         rc = LDLM_FL_LOCAL_ONLY;
1063                 }
1064                 if (rc == LDLM_FL_LOCAL_ONLY) {
1065                         /* CANCEL RPC should not be sent to server. */
1066                         list_del_init(&lock->l_bl_ast);
1067                         LDLM_LOCK_PUT(lock);
1068                         added--;
1069                 }
1070
1071         } 
1072         RETURN(added);
1073 }
1074
1075 /* when called with LDLM_ASYNC the blocking callback will be handled
1076  * in a thread and this function will return after the thread has been
1077  * asked to call the callback.  when called with LDLM_SYNC the blocking
1078  * callback will be performed in this function. */
1079 int ldlm_cancel_lru(struct ldlm_namespace *ns, ldlm_sync_t sync)
1080 {
1081         CFS_LIST_HEAD(cancels);
1082         int count, rc;
1083         ENTRY;
1084
1085 #ifndef __KERNEL__
1086         sync = LDLM_SYNC; /* force to be sync in user space */
1087 #endif
1088         count = ldlm_cancel_lru_local(ns, &cancels, 0, 0, 0);
1089         if (sync == LDLM_ASYNC) {
1090                 struct ldlm_lock *lock, *next;
1091                 list_for_each_entry_safe(lock, next, &cancels, l_bl_ast) {
1092                         /* Remove from the list to allow blocking thread to
1093                          * re-use l_bl_ast. */
1094                         list_del_init(&lock->l_bl_ast);
1095                         rc = ldlm_bl_to_thread(ns, NULL, lock,
1096                                                LDLM_FL_CANCELING);
1097                         if (rc)
1098                                 list_add_tail(&lock->l_bl_ast, &next->l_bl_ast);
1099                 }
1100         }
1101
1102         /* If some locks are left in the list in ASYNC mode, or
1103          * this is SYNC mode, cancel the list. */
1104         ldlm_cli_cancel_list(&cancels, count, NULL, DLM_LOCKREQ_OFF, 0);
1105         RETURN(0);
1106 }
1107
1108 /* Find and cancel locally unused locks found on resource, matched to the
1109  * given policy, mode. GET the found locks and add them into the @cancels
1110  * list. */
1111 int ldlm_cancel_resource_local(struct ldlm_resource *res,
1112                                struct list_head *cancels,
1113                                ldlm_policy_data_t *policy,
1114                                ldlm_mode_t mode, int lock_flags,
1115                                int flags, void *opaque)
1116 {
1117         struct ldlm_lock *lock, *next;
1118         int count = 0, left;
1119         ENTRY;
1120
1121         lock_res(res);
1122         list_for_each_entry(lock, &res->lr_granted, l_res_link) {
1123                 if (opaque != NULL && lock->l_ast_data != opaque) {
1124                         LDLM_ERROR(lock, "data %p doesn't match opaque %p",
1125                                    lock->l_ast_data, opaque);
1126                         //LBUG();
1127                         continue;
1128                 }
1129
1130                 if (lock->l_readers || lock->l_writers) {
1131                         if (flags & LDLM_FL_WARN) {
1132                                 LDLM_ERROR(lock, "lock in use");
1133                                 //LBUG();
1134                         }
1135                         continue;
1136                 }
1137
1138                 /* If somebody is already doing CANCEL, or blocking ast came,
1139                  * skip this lock. */
1140                 if (lock->l_flags & LDLM_FL_BL_AST || 
1141                     lock->l_flags & LDLM_FL_CANCELING)
1142                         continue;
1143
1144                 if (lockmode_compat(lock->l_granted_mode, mode))
1145                         continue;
1146
1147                 /* If policy is given and this is IBITS lock, add to list only
1148                  * those locks that match by policy. */
1149                 if (policy && (lock->l_resource->lr_type == LDLM_IBITS) &&
1150                     !(lock->l_policy_data.l_inodebits.bits &
1151                       policy->l_inodebits.bits))
1152                         continue;
1153
1154                 /* See CBPENDING comment in ldlm_cancel_lru */
1155                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING |
1156                         lock_flags;
1157
1158                 LASSERT(list_empty(&lock->l_bl_ast));
1159                 list_add(&lock->l_bl_ast, cancels);
1160                 LDLM_LOCK_GET(lock);
1161                 count++;
1162         }
1163         unlock_res(res);
1164
1165         /* Handle only @count inserted locks. */
1166         left = count;
1167         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1168                 int rc = LDLM_FL_LOCAL_ONLY;
1169
1170                 if (left-- == 0)
1171                         break;
1172                 if (flags & LDLM_FL_LOCAL_ONLY)
1173                         ldlm_lock_cancel(lock);
1174                 else
1175                         rc = ldlm_cli_cancel_local(lock);
1176
1177                 if (rc == LDLM_FL_BL_AST) {
1178                         CFS_LIST_HEAD(head);
1179
1180                         LDLM_DEBUG(lock, "Cancel lock separately");
1181                         list_del_init(&lock->l_bl_ast);
1182                         list_add(&lock->l_bl_ast, &head);
1183                         ldlm_cli_cancel_req(lock->l_conn_export, &head, 1, 0);
1184                         rc = LDLM_FL_LOCAL_ONLY;
1185                 }
1186                 if (rc == LDLM_FL_LOCAL_ONLY) {
1187                         /* CANCEL RPC should not be sent to server. */
1188                         list_del_init(&lock->l_bl_ast);
1189                         LDLM_LOCK_PUT(lock);
1190                         count--;
1191                 }
1192         }
1193         RETURN(count);
1194 }
1195
1196 /* If @req is NULL, send CANCEL request to server with handles of locks 
1197  * in the @cancels. If EARLY_CANCEL is not supported, send CANCEL requests 
1198  * separately per lock.
1199  * If @req is not NULL, put handles of locks in @cancels into the request 
1200  * buffer at the offset @off.
1201  * Destroy @cancels at the end. */
1202 int ldlm_cli_cancel_list(struct list_head *cancels, int count,
1203                          struct ptlrpc_request *req, int off, int flags)
1204 {
1205         struct ldlm_lock *lock;
1206         int res = 0;
1207         ENTRY;
1208
1209         if (list_empty(cancels) || count == 0)
1210                 RETURN(0);
1211         
1212         /* XXX: requests (both batched and not) could be sent in parallel. 
1213          * Usually it is enough to have just 1 RPC, but it is possible that
1214          * there are to many locks to be cancelled in LRU or on a resource.
1215          * It would also speed up the case when the server does not support
1216          * the feature. */
1217         while (count > 0) {
1218                 LASSERT(!list_empty(cancels));
1219                 lock = list_entry(cancels->next, struct ldlm_lock, l_bl_ast);
1220                 LASSERT(lock->l_conn_export);
1221
1222                 if (exp_connect_cancelset(lock->l_conn_export)) {
1223                         res = count;
1224                         if (req)
1225                                 ldlm_cancel_pack(req, off, cancels, count);
1226                         else
1227                                 res = ldlm_cli_cancel_req(lock->l_conn_export,
1228                                                           cancels, count, flags);
1229                 } else {
1230                         res = ldlm_cli_cancel_req(lock->l_conn_export,
1231                                                   cancels, 1, flags);
1232                 }
1233
1234                 if (res < 0) {
1235                         CERROR("ldlm_cli_cancel_list: %d\n", res);
1236                         res = count;
1237                 }
1238
1239                 count -= res;
1240                 ldlm_lock_list_put(cancels, l_bl_ast, res);
1241         }
1242         LASSERT(list_empty(cancels));
1243         LASSERT(count == 0);
1244         RETURN(0);
1245 }
1246
1247 int ldlm_cli_cancel_unused_resource(struct ldlm_namespace *ns,
1248                                     const struct ldlm_res_id *res_id,
1249                                     ldlm_policy_data_t *policy,
1250                                     ldlm_mode_t mode, int flags, void *opaque)
1251 {
1252         struct ldlm_resource *res;
1253         CFS_LIST_HEAD(cancels);
1254         int count;
1255         int rc;
1256         ENTRY;
1257
1258         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1259         if (res == NULL) {
1260                 /* This is not a problem. */
1261                 CDEBUG(D_INFO, "No resource "LPU64"\n", res_id->name[0]);
1262                 RETURN(0);
1263         }
1264
1265         count = ldlm_cancel_resource_local(res, &cancels, policy, mode,
1266                                            0, flags, opaque);
1267         rc = ldlm_cli_cancel_list(&cancels, count, NULL,
1268                                   DLM_LOCKREQ_OFF, flags);
1269         if (rc != ELDLM_OK)
1270                 CERROR("ldlm_cli_cancel_unused_resource: %d\n", rc);
1271
1272         ldlm_resource_putref(res);
1273         RETURN(0);
1274 }
1275
1276 static inline int have_no_nsresource(struct ldlm_namespace *ns)
1277 {
1278         int no_resource = 0;
1279
1280         spin_lock(&ns->ns_hash_lock);
1281         if (ns->ns_resources == 0)
1282                 no_resource = 1;
1283         spin_unlock(&ns->ns_hash_lock);
1284
1285         RETURN(no_resource);
1286 }
1287
1288 /* Cancel all locks on a namespace (or a specific resource, if given)
1289  * that have 0 readers/writers.
1290  *
1291  * If flags & LDLM_FL_LOCAL_ONLY, throw the locks away without trying
1292  * to notify the server. */
1293 int ldlm_cli_cancel_unused(struct ldlm_namespace *ns,
1294                            const struct ldlm_res_id *res_id,
1295                            int flags, void *opaque)
1296 {
1297         int i;
1298         ENTRY;
1299
1300         if (ns == NULL)
1301                 RETURN(ELDLM_OK);
1302
1303         if (res_id)
1304                 RETURN(ldlm_cli_cancel_unused_resource(ns, res_id, NULL,
1305                                                        LCK_MINMODE, flags,
1306                                                        opaque));
1307
1308         spin_lock(&ns->ns_hash_lock);
1309         for (i = 0; i < RES_HASH_SIZE; i++) {
1310                 struct list_head *tmp;
1311                 tmp = ns->ns_hash[i].next;
1312                 while (tmp != &(ns->ns_hash[i])) {
1313                         struct ldlm_resource *res;
1314                         int rc;
1315
1316                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1317                         ldlm_resource_getref(res);
1318                         spin_unlock(&ns->ns_hash_lock);
1319
1320                         rc = ldlm_cli_cancel_unused_resource(ns, &res->lr_name,
1321                                                              NULL, LCK_MINMODE,
1322                                                              flags, opaque);
1323
1324                         if (rc)
1325                                 CERROR("ldlm_cli_cancel_unused ("LPU64"): %d\n",
1326                                        res->lr_name.name[0], rc);
1327
1328                         spin_lock(&ns->ns_hash_lock);
1329                         tmp = tmp->next;
1330                         ldlm_resource_putref_locked(res);
1331                 }
1332         }
1333         spin_unlock(&ns->ns_hash_lock);
1334
1335         RETURN(ELDLM_OK);
1336 }
1337
1338 /* join/split resource locks to/from lru list */
1339 int ldlm_cli_join_lru(struct ldlm_namespace *ns,
1340                       const struct ldlm_res_id *res_id, int join)
1341 {
1342         struct ldlm_resource *res;
1343         struct ldlm_lock *lock, *n;
1344         int count = 0;
1345         ENTRY;
1346
1347         LASSERT(ns->ns_client == LDLM_NAMESPACE_CLIENT);
1348
1349         res = ldlm_resource_get(ns, NULL, res_id, LDLM_EXTENT, 0);
1350         if (res == NULL)
1351                 RETURN(count);
1352         LASSERT(res->lr_type == LDLM_EXTENT);
1353
1354         lock_res(res);
1355         if (!join)
1356                 goto split;
1357
1358         list_for_each_entry_safe (lock, n, &res->lr_granted, l_res_link) {
1359                 if (list_empty(&lock->l_lru) &&
1360                     !lock->l_readers && !lock->l_writers &&
1361                     !(lock->l_flags & LDLM_FL_LOCAL) &&
1362                     !(lock->l_flags & LDLM_FL_CBPENDING)) {
1363                         lock->l_last_used = cfs_time_current();
1364                         spin_lock(&ns->ns_unused_lock);
1365                         LASSERT(ns->ns_nr_unused >= 0);
1366                         list_add_tail(&lock->l_lru, &ns->ns_unused_list);
1367                         ns->ns_nr_unused++;
1368                         spin_unlock(&ns->ns_unused_lock);
1369                         lock->l_flags &= ~LDLM_FL_NO_LRU;
1370                         LDLM_DEBUG(lock, "join lock to lru");
1371                         count++;
1372                 }
1373         }
1374         goto unlock;
1375 split:
1376         spin_lock(&ns->ns_unused_lock);
1377         list_for_each_entry_safe (lock, n, &ns->ns_unused_list, l_lru) {
1378                 if (lock->l_resource == res) {
1379                         ldlm_lock_remove_from_lru_nolock(lock);
1380                         lock->l_flags |= LDLM_FL_NO_LRU;
1381                         LDLM_DEBUG(lock, "split lock from lru");
1382                         count++;
1383                 }
1384         }
1385         spin_unlock(&ns->ns_unused_lock);
1386 unlock:
1387         unlock_res(res);
1388         ldlm_resource_putref(res);
1389         RETURN(count);
1390 }
1391
1392 /* Lock iterators. */
1393
1394 int ldlm_resource_foreach(struct ldlm_resource *res, ldlm_iterator_t iter,
1395                           void *closure)
1396 {
1397         struct list_head *tmp, *next;
1398         struct ldlm_lock *lock;
1399         int rc = LDLM_ITER_CONTINUE;
1400
1401         ENTRY;
1402
1403         if (!res)
1404                 RETURN(LDLM_ITER_CONTINUE);
1405
1406         lock_res(res);
1407         list_for_each_safe(tmp, next, &res->lr_granted) {
1408                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1409
1410                 if (iter(lock, closure) == LDLM_ITER_STOP)
1411                         GOTO(out, rc = LDLM_ITER_STOP);
1412         }
1413
1414         list_for_each_safe(tmp, next, &res->lr_converting) {
1415                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1416
1417                 if (iter(lock, closure) == LDLM_ITER_STOP)
1418                         GOTO(out, rc = LDLM_ITER_STOP);
1419         }
1420
1421         list_for_each_safe(tmp, next, &res->lr_waiting) {
1422                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1423
1424                 if (iter(lock, closure) == LDLM_ITER_STOP)
1425                         GOTO(out, rc = LDLM_ITER_STOP);
1426         }
1427  out:
1428         unlock_res(res);
1429         RETURN(rc);
1430 }
1431
1432 struct iter_helper_data {
1433         ldlm_iterator_t iter;
1434         void *closure;
1435 };
1436
1437 static int ldlm_iter_helper(struct ldlm_lock *lock, void *closure)
1438 {
1439         struct iter_helper_data *helper = closure;
1440         return helper->iter(lock, helper->closure);
1441 }
1442
1443 static int ldlm_res_iter_helper(struct ldlm_resource *res, void *closure)
1444 {
1445         return ldlm_resource_foreach(res, ldlm_iter_helper, closure);
1446 }
1447
1448 int ldlm_namespace_foreach(struct ldlm_namespace *ns, ldlm_iterator_t iter,
1449                            void *closure)
1450 {
1451         struct iter_helper_data helper = { iter: iter, closure: closure };
1452         return ldlm_namespace_foreach_res(ns, ldlm_res_iter_helper, &helper);
1453 }
1454
1455 int ldlm_namespace_foreach_res(struct ldlm_namespace *ns,
1456                                ldlm_res_iterator_t iter, void *closure)
1457 {
1458         int i, rc = LDLM_ITER_CONTINUE;
1459         struct ldlm_resource *res;
1460         struct list_head *tmp;
1461
1462         ENTRY;
1463         spin_lock(&ns->ns_hash_lock);
1464         for (i = 0; i < RES_HASH_SIZE; i++) {
1465                 tmp = ns->ns_hash[i].next;
1466                 while (tmp != &(ns->ns_hash[i])) {
1467                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1468                         ldlm_resource_getref(res);
1469                         spin_unlock(&ns->ns_hash_lock);
1470
1471                         rc = iter(res, closure);
1472
1473                         spin_lock(&ns->ns_hash_lock);
1474                         tmp = tmp->next;
1475                         ldlm_resource_putref_locked(res);
1476                         if (rc == LDLM_ITER_STOP)
1477                                 GOTO(out, rc);
1478                 }
1479         }
1480  out:
1481         spin_unlock(&ns->ns_hash_lock);
1482         RETURN(rc);
1483 }
1484
1485 /* non-blocking function to manipulate a lock whose cb_data is being put away.*/
1486 void ldlm_resource_iterate(struct ldlm_namespace *ns,
1487                            const struct ldlm_res_id *res_id,
1488                            ldlm_iterator_t iter, void *data)
1489 {
1490         struct ldlm_resource *res;
1491         ENTRY;
1492
1493         if (ns == NULL) {
1494                 CERROR("must pass in namespace\n");
1495                 LBUG();
1496         }
1497
1498         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1499         if (res == NULL) {
1500                 EXIT;
1501                 return;
1502         }
1503
1504         ldlm_resource_foreach(res, iter, data);
1505         ldlm_resource_putref(res);
1506         EXIT;
1507 }
1508
1509 /* Lock replay */
1510
1511 static int ldlm_chain_lock_for_replay(struct ldlm_lock *lock, void *closure)
1512 {
1513         struct list_head *list = closure;
1514
1515         /* we use l_pending_chain here, because it's unused on clients. */
1516         LASSERTF(list_empty(&lock->l_pending_chain),"lock %p next %p prev %p\n",
1517                  lock, &lock->l_pending_chain.next,&lock->l_pending_chain.prev);
1518         /* bug 9573: don't replay locks left after eviction */
1519         if (!(lock->l_flags & LDLM_FL_FAILED))
1520                 list_add(&lock->l_pending_chain, list);
1521         return LDLM_ITER_CONTINUE;
1522 }
1523
1524 static int replay_lock_interpret(struct ptlrpc_request *req,
1525                                  struct ldlm_async_args *aa, int rc)
1526 {
1527         struct ldlm_lock *lock;
1528         struct ldlm_reply *reply;
1529
1530         ENTRY;
1531         atomic_dec(&req->rq_import->imp_replay_inflight);
1532         if (rc != ELDLM_OK)
1533                 GOTO(out, rc);
1534
1535
1536         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
1537                                    lustre_swab_ldlm_reply);
1538         if (reply == NULL) {
1539                 CERROR("Can't unpack ldlm_reply\n");
1540                 GOTO (out, rc = -EPROTO);
1541         }
1542
1543         lock = ldlm_handle2lock(&aa->lock_handle);
1544         if (!lock) {
1545                 CERROR("received replay ack for unknown local cookie "LPX64
1546                        " remote cookie "LPX64 " from server %s id %s\n",
1547                        aa->lock_handle.cookie, reply->lock_handle.cookie,
1548                        req->rq_export->exp_client_uuid.uuid,
1549                        libcfs_id2str(req->rq_peer));
1550                 GOTO(out, rc = -ESTALE);
1551         }
1552
1553         lock->l_remote_handle = reply->lock_handle;
1554         LDLM_DEBUG(lock, "replayed lock:");
1555         ptlrpc_import_recovery_state_machine(req->rq_import);
1556         LDLM_LOCK_PUT(lock);
1557 out:
1558         if (rc != ELDLM_OK)
1559                 ptlrpc_connect_import(req->rq_import, NULL);
1560
1561
1562         RETURN(rc);
1563 }
1564
1565 static int replay_one_lock(struct obd_import *imp, struct ldlm_lock *lock)
1566 {
1567         struct ptlrpc_request *req;
1568         struct ldlm_request *body;
1569         struct ldlm_reply *reply;
1570         struct ldlm_async_args *aa;
1571         int buffers = 2;
1572         int size[3] = { sizeof(struct ptlrpc_body) };
1573         int flags;
1574         ENTRY;
1575
1576
1577         /* Bug 11974: Do not replay a lock which is actively being canceled */
1578         if (lock->l_flags & LDLM_FL_CANCELING) {
1579                 LDLM_DEBUG(lock, "Not replaying canceled lock:");
1580                 RETURN(0);
1581         }
1582
1583         /* If this is reply-less callback lock, we cannot replay it, since
1584          * server might have long dropped it, but notification of that event was
1585          * lost by network. (and server granted conflicting lock already) */
1586         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1587                 LDLM_DEBUG(lock, "Not replaying reply-less lock:");
1588                 ldlm_lock_cancel(lock);
1589                 RETURN(0);
1590         }
1591         /*
1592          * If granted mode matches the requested mode, this lock is granted.
1593          *
1594          * If they differ, but we have a granted mode, then we were granted
1595          * one mode and now want another: ergo, converting.
1596          *
1597          * If we haven't been granted anything and are on a resource list,
1598          * then we're blocked/waiting.
1599          *
1600          * If we haven't been granted anything and we're NOT on a resource list,
1601          * then we haven't got a reply yet and don't have a known disposition.
1602          * This happens whenever a lock enqueue is the request that triggers
1603          * recovery.
1604          */
1605         if (lock->l_granted_mode == lock->l_req_mode)
1606                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_GRANTED;
1607         else if (lock->l_granted_mode)
1608                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_CONV;
1609         else if (!list_empty(&lock->l_res_link))
1610                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_WAIT;
1611         else
1612                 flags = LDLM_FL_REPLAY;
1613
1614         size[DLM_LOCKREQ_OFF] = sizeof(*body);
1615         req = ptlrpc_prep_req(imp, LUSTRE_DLM_VERSION, LDLM_ENQUEUE, 2, size,
1616                               NULL);
1617         if (!req)
1618                 RETURN(-ENOMEM);
1619
1620         /* We're part of recovery, so don't wait for it. */
1621         req->rq_send_state = LUSTRE_IMP_REPLAY_LOCKS;
1622
1623         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
1624         ldlm_lock2desc(lock, &body->lock_desc);
1625         body->lock_flags = flags;
1626
1627         ldlm_lock2handle(lock, &body->lock_handle[0]);
1628         size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
1629         if (lock->l_lvb_len != 0) {
1630                 buffers = 3;
1631                 size[DLM_REPLY_REC_OFF] = lock->l_lvb_len;
1632         }
1633         ptlrpc_req_set_repsize(req, buffers, size);
1634         /* notify the server we've replayed all requests.
1635          * also, we mark the request to be put on a dedicated
1636          * queue to be processed after all request replayes.
1637          * bug 6063 */
1638         lustre_msg_set_flags(req->rq_reqmsg, MSG_REQ_REPLAY_DONE);
1639
1640         LDLM_DEBUG(lock, "replaying lock:");
1641
1642         atomic_inc(&req->rq_import->imp_replay_inflight);
1643         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
1644         aa = (struct ldlm_async_args *)&req->rq_async_args;
1645         aa->lock_handle = body->lock_handle[0];
1646         req->rq_interpret_reply = replay_lock_interpret;
1647         ptlrpcd_add_req(req);
1648
1649         RETURN(0);
1650 }
1651
1652 int ldlm_replay_locks(struct obd_import *imp)
1653 {
1654         struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
1655         struct list_head list;
1656         struct ldlm_lock *lock, *next;
1657         int rc = 0;
1658
1659         ENTRY;
1660         CFS_INIT_LIST_HEAD(&list);
1661
1662         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
1663
1664         /* ensure this doesn't fall to 0 before all have been queued */
1665         atomic_inc(&imp->imp_replay_inflight);
1666
1667         (void)ldlm_namespace_foreach(ns, ldlm_chain_lock_for_replay, &list);
1668
1669         list_for_each_entry_safe(lock, next, &list, l_pending_chain) {
1670                 list_del_init(&lock->l_pending_chain);
1671                 if (rc)
1672                         continue; /* or try to do the rest? */
1673                 rc = replay_one_lock(imp, lock);
1674         }
1675
1676         atomic_dec(&imp->imp_replay_inflight);
1677
1678         RETURN(rc);
1679 }