GNU Linux-libre 4.9-gnu1
[releases.git] / drivers / staging / lustre / lustre / osc / osc_request.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2015, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  */
32
33 #define DEBUG_SUBSYSTEM S_OSC
34
35 #include "../../include/linux/libcfs/libcfs.h"
36
37 #include "../include/lustre_dlm.h"
38 #include "../include/lustre_net.h"
39 #include "../include/lustre/lustre_user.h"
40 #include "../include/obd_cksum.h"
41
42 #include "../include/lustre_ha.h"
43 #include "../include/lprocfs_status.h"
44 #include "../include/lustre/lustre_ioctl.h"
45 #include "../include/lustre_debug.h"
46 #include "../include/lustre_param.h"
47 #include "../include/lustre_fid.h"
48 #include "../include/obd_class.h"
49 #include "../include/obd.h"
50 #include "osc_internal.h"
51 #include "osc_cl_internal.h"
52
53 atomic_t osc_pool_req_count;
54 unsigned int osc_reqpool_maxreqcount;
55 struct ptlrpc_request_pool *osc_rq_pool;
56
57 /* max memory used for request pool, unit is MB */
58 static unsigned int osc_reqpool_mem_max = 5;
59 module_param(osc_reqpool_mem_max, uint, 0444);
60
61 struct osc_brw_async_args {
62         struct obdo       *aa_oa;
63         int             aa_requested_nob;
64         int             aa_nio_count;
65         u32             aa_page_count;
66         int             aa_resends;
67         struct brw_page  **aa_ppga;
68         struct client_obd *aa_cli;
69         struct list_head         aa_oaps;
70         struct list_head         aa_exts;
71         struct cl_req     *aa_clerq;
72 };
73
74 struct osc_async_args {
75         struct obd_info   *aa_oi;
76 };
77
78 struct osc_setattr_args {
79         struct obdo      *sa_oa;
80         obd_enqueue_update_f sa_upcall;
81         void            *sa_cookie;
82 };
83
84 struct osc_fsync_args {
85         struct obd_info     *fa_oi;
86         obd_enqueue_update_f fa_upcall;
87         void            *fa_cookie;
88 };
89
90 struct osc_enqueue_args {
91         struct obd_export       *oa_exp;
92         enum ldlm_type          oa_type;
93         enum ldlm_mode          oa_mode;
94         __u64               *oa_flags;
95         osc_enqueue_upcall_f    oa_upcall;
96         void                 *oa_cookie;
97         struct ost_lvb     *oa_lvb;
98         struct lustre_handle    oa_lockh;
99         unsigned int          oa_agl:1;
100 };
101
102 static void osc_release_ppga(struct brw_page **ppga, u32 count);
103 static int brw_interpret(const struct lu_env *env,
104                          struct ptlrpc_request *req, void *data, int rc);
105
106 /* Unpack OSC object metadata from disk storage (LE byte order). */
107 static int osc_unpackmd(struct obd_export *exp, struct lov_stripe_md **lsmp,
108                         struct lov_mds_md *lmm, int lmm_bytes)
109 {
110         int lsm_size;
111         struct obd_import *imp = class_exp2cliimp(exp);
112
113         if (lmm) {
114                 if (lmm_bytes < sizeof(*lmm)) {
115                         CERROR("%s: lov_mds_md too small: %d, need %d\n",
116                                exp->exp_obd->obd_name, lmm_bytes,
117                                (int)sizeof(*lmm));
118                         return -EINVAL;
119                 }
120                 /* XXX LOV_MAGIC etc check? */
121
122                 if (unlikely(ostid_id(&lmm->lmm_oi) == 0)) {
123                         CERROR("%s: zero lmm_object_id: rc = %d\n",
124                                exp->exp_obd->obd_name, -EINVAL);
125                         return -EINVAL;
126                 }
127         }
128
129         lsm_size = lov_stripe_md_size(1);
130         if (!lsmp)
131                 return lsm_size;
132
133         if (*lsmp && !lmm) {
134                 kfree((*lsmp)->lsm_oinfo[0]);
135                 kfree(*lsmp);
136                 *lsmp = NULL;
137                 return 0;
138         }
139
140         if (!*lsmp) {
141                 *lsmp = kzalloc(lsm_size, GFP_NOFS);
142                 if (unlikely(!*lsmp))
143                         return -ENOMEM;
144                 (*lsmp)->lsm_oinfo[0] = kzalloc(sizeof(struct lov_oinfo),
145                                                 GFP_NOFS);
146                 if (unlikely(!(*lsmp)->lsm_oinfo[0])) {
147                         kfree(*lsmp);
148                         return -ENOMEM;
149                 }
150                 loi_init((*lsmp)->lsm_oinfo[0]);
151         } else if (unlikely(ostid_id(&(*lsmp)->lsm_oi) == 0)) {
152                 return -EBADF;
153         }
154
155         if (lmm)
156                 /* XXX zero *lsmp? */
157                 ostid_le_to_cpu(&lmm->lmm_oi, &(*lsmp)->lsm_oi);
158
159         if (imp &&
160             (imp->imp_connect_data.ocd_connect_flags & OBD_CONNECT_MAXBYTES))
161                 (*lsmp)->lsm_maxbytes = imp->imp_connect_data.ocd_maxbytes;
162         else
163                 (*lsmp)->lsm_maxbytes = LUSTRE_EXT3_STRIPE_MAXBYTES;
164
165         return lsm_size;
166 }
167
168 static inline void osc_pack_req_body(struct ptlrpc_request *req,
169                                      struct obd_info *oinfo)
170 {
171         struct ost_body *body;
172
173         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
174         LASSERT(body);
175
176         lustre_set_wire_obdo(&req->rq_import->imp_connect_data, &body->oa,
177                              oinfo->oi_oa);
178 }
179
180 static int osc_getattr_interpret(const struct lu_env *env,
181                                  struct ptlrpc_request *req,
182                                  struct osc_async_args *aa, int rc)
183 {
184         struct ost_body *body;
185
186         if (rc != 0)
187                 goto out;
188
189         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
190         if (body) {
191                 CDEBUG(D_INODE, "mode: %o\n", body->oa.o_mode);
192                 lustre_get_wire_obdo(&req->rq_import->imp_connect_data,
193                                      aa->aa_oi->oi_oa, &body->oa);
194
195                 /* This should really be sent by the OST */
196                 aa->aa_oi->oi_oa->o_blksize = DT_MAX_BRW_SIZE;
197                 aa->aa_oi->oi_oa->o_valid |= OBD_MD_FLBLKSZ;
198         } else {
199                 CDEBUG(D_INFO, "can't unpack ost_body\n");
200                 rc = -EPROTO;
201                 aa->aa_oi->oi_oa->o_valid = 0;
202         }
203 out:
204         rc = aa->aa_oi->oi_cb_up(aa->aa_oi, rc);
205         return rc;
206 }
207
208 static int osc_getattr_async(struct obd_export *exp, struct obd_info *oinfo,
209                              struct ptlrpc_request_set *set)
210 {
211         struct ptlrpc_request *req;
212         struct osc_async_args *aa;
213         int rc;
214
215         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_OST_GETATTR);
216         if (!req)
217                 return -ENOMEM;
218
219         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_GETATTR);
220         if (rc) {
221                 ptlrpc_request_free(req);
222                 return rc;
223         }
224
225         osc_pack_req_body(req, oinfo);
226
227         ptlrpc_request_set_replen(req);
228         req->rq_interpret_reply = (ptlrpc_interpterer_t)osc_getattr_interpret;
229
230         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
231         aa = ptlrpc_req_async_args(req);
232         aa->aa_oi = oinfo;
233
234         ptlrpc_set_add_req(set, req);
235         return 0;
236 }
237
238 static int osc_getattr(const struct lu_env *env, struct obd_export *exp,
239                        struct obd_info *oinfo)
240 {
241         struct ptlrpc_request *req;
242         struct ost_body *body;
243         int rc;
244
245         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_OST_GETATTR);
246         if (!req)
247                 return -ENOMEM;
248
249         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_GETATTR);
250         if (rc) {
251                 ptlrpc_request_free(req);
252                 return rc;
253         }
254
255         osc_pack_req_body(req, oinfo);
256
257         ptlrpc_request_set_replen(req);
258
259         rc = ptlrpc_queue_wait(req);
260         if (rc)
261                 goto out;
262
263         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
264         if (!body) {
265                 rc = -EPROTO;
266                 goto out;
267         }
268
269         CDEBUG(D_INODE, "mode: %o\n", body->oa.o_mode);
270         lustre_get_wire_obdo(&req->rq_import->imp_connect_data, oinfo->oi_oa,
271                              &body->oa);
272
273         oinfo->oi_oa->o_blksize = cli_brw_size(exp->exp_obd);
274         oinfo->oi_oa->o_valid |= OBD_MD_FLBLKSZ;
275
276  out:
277         ptlrpc_req_finished(req);
278         return rc;
279 }
280
281 static int osc_setattr(const struct lu_env *env, struct obd_export *exp,
282                        struct obd_info *oinfo, struct obd_trans_info *oti)
283 {
284         struct ptlrpc_request *req;
285         struct ost_body *body;
286         int rc;
287
288         LASSERT(oinfo->oi_oa->o_valid & OBD_MD_FLGROUP);
289
290         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_OST_SETATTR);
291         if (!req)
292                 return -ENOMEM;
293
294         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_SETATTR);
295         if (rc) {
296                 ptlrpc_request_free(req);
297                 return rc;
298         }
299
300         osc_pack_req_body(req, oinfo);
301
302         ptlrpc_request_set_replen(req);
303
304         rc = ptlrpc_queue_wait(req);
305         if (rc)
306                 goto out;
307
308         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
309         if (!body) {
310                 rc = -EPROTO;
311                 goto out;
312         }
313
314         lustre_get_wire_obdo(&req->rq_import->imp_connect_data, oinfo->oi_oa,
315                              &body->oa);
316
317 out:
318         ptlrpc_req_finished(req);
319         return rc;
320 }
321
322 static int osc_setattr_interpret(const struct lu_env *env,
323                                  struct ptlrpc_request *req,
324                                  struct osc_setattr_args *sa, int rc)
325 {
326         struct ost_body *body;
327
328         if (rc != 0)
329                 goto out;
330
331         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
332         if (!body) {
333                 rc = -EPROTO;
334                 goto out;
335         }
336
337         lustre_get_wire_obdo(&req->rq_import->imp_connect_data, sa->sa_oa,
338                              &body->oa);
339 out:
340         rc = sa->sa_upcall(sa->sa_cookie, rc);
341         return rc;
342 }
343
344 int osc_setattr_async_base(struct obd_export *exp, struct obd_info *oinfo,
345                            struct obd_trans_info *oti,
346                            obd_enqueue_update_f upcall, void *cookie,
347                            struct ptlrpc_request_set *rqset)
348 {
349         struct ptlrpc_request *req;
350         struct osc_setattr_args *sa;
351         int rc;
352
353         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_OST_SETATTR);
354         if (!req)
355                 return -ENOMEM;
356
357         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_SETATTR);
358         if (rc) {
359                 ptlrpc_request_free(req);
360                 return rc;
361         }
362
363         if (oti && oinfo->oi_oa->o_valid & OBD_MD_FLCOOKIE)
364                 oinfo->oi_oa->o_lcookie = *oti->oti_logcookies;
365
366         osc_pack_req_body(req, oinfo);
367
368         ptlrpc_request_set_replen(req);
369
370         /* do mds to ost setattr asynchronously */
371         if (!rqset) {
372                 /* Do not wait for response. */
373                 ptlrpcd_add_req(req);
374         } else {
375                 req->rq_interpret_reply =
376                         (ptlrpc_interpterer_t)osc_setattr_interpret;
377
378                 CLASSERT(sizeof(*sa) <= sizeof(req->rq_async_args));
379                 sa = ptlrpc_req_async_args(req);
380                 sa->sa_oa = oinfo->oi_oa;
381                 sa->sa_upcall = upcall;
382                 sa->sa_cookie = cookie;
383
384                 if (rqset == PTLRPCD_SET)
385                         ptlrpcd_add_req(req);
386                 else
387                         ptlrpc_set_add_req(rqset, req);
388         }
389
390         return 0;
391 }
392
393 static int osc_setattr_async(struct obd_export *exp, struct obd_info *oinfo,
394                              struct obd_trans_info *oti,
395                              struct ptlrpc_request_set *rqset)
396 {
397         return osc_setattr_async_base(exp, oinfo, oti,
398                                       oinfo->oi_cb_up, oinfo, rqset);
399 }
400
401 static int osc_create(const struct lu_env *env, struct obd_export *exp,
402                       struct obdo *oa, struct obd_trans_info *oti)
403 {
404         struct ptlrpc_request *req;
405         struct ost_body *body;
406         int rc;
407
408         LASSERT(oa);
409         LASSERT(oa->o_valid & OBD_MD_FLGROUP);
410         LASSERT(fid_seq_is_echo(ostid_seq(&oa->o_oi)));
411
412         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_OST_CREATE);
413         if (!req) {
414                 rc = -ENOMEM;
415                 goto out;
416         }
417
418         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_CREATE);
419         if (rc) {
420                 ptlrpc_request_free(req);
421                 goto out;
422         }
423
424         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
425         LASSERT(body);
426
427         lustre_set_wire_obdo(&req->rq_import->imp_connect_data, &body->oa, oa);
428
429         ptlrpc_request_set_replen(req);
430
431         if ((oa->o_valid & OBD_MD_FLFLAGS) &&
432             oa->o_flags == OBD_FL_DELORPHAN) {
433                 DEBUG_REQ(D_HA, req,
434                           "delorphan from OST integration");
435                 /* Don't resend the delorphan req */
436                 req->rq_no_resend = 1;
437                 req->rq_no_delay = 1;
438         }
439
440         rc = ptlrpc_queue_wait(req);
441         if (rc)
442                 goto out_req;
443
444         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
445         if (!body) {
446                 rc = -EPROTO;
447                 goto out_req;
448         }
449
450         CDEBUG(D_INFO, "oa flags %x\n", oa->o_flags);
451         lustre_get_wire_obdo(&req->rq_import->imp_connect_data, oa, &body->oa);
452
453         oa->o_blksize = cli_brw_size(exp->exp_obd);
454         oa->o_valid |= OBD_MD_FLBLKSZ;
455
456         if (oti && oa->o_valid & OBD_MD_FLCOOKIE) {
457                 if (!oti->oti_logcookies)
458                         oti->oti_logcookies = &oti->oti_onecookie;
459                 *oti->oti_logcookies = oa->o_lcookie;
460         }
461
462         CDEBUG(D_HA, "transno: %lld\n",
463                lustre_msg_get_transno(req->rq_repmsg));
464 out_req:
465         ptlrpc_req_finished(req);
466 out:
467         return rc;
468 }
469
470 int osc_punch_base(struct obd_export *exp, struct obd_info *oinfo,
471                    obd_enqueue_update_f upcall, void *cookie,
472                    struct ptlrpc_request_set *rqset)
473 {
474         struct ptlrpc_request *req;
475         struct osc_setattr_args *sa;
476         struct ost_body *body;
477         int rc;
478
479         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_OST_PUNCH);
480         if (!req)
481                 return -ENOMEM;
482
483         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_PUNCH);
484         if (rc) {
485                 ptlrpc_request_free(req);
486                 return rc;
487         }
488         req->rq_request_portal = OST_IO_PORTAL; /* bug 7198 */
489         ptlrpc_at_set_req_timeout(req);
490
491         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
492         LASSERT(body);
493         lustre_set_wire_obdo(&req->rq_import->imp_connect_data, &body->oa,
494                              oinfo->oi_oa);
495
496         ptlrpc_request_set_replen(req);
497
498         req->rq_interpret_reply = (ptlrpc_interpterer_t)osc_setattr_interpret;
499         CLASSERT(sizeof(*sa) <= sizeof(req->rq_async_args));
500         sa = ptlrpc_req_async_args(req);
501         sa->sa_oa = oinfo->oi_oa;
502         sa->sa_upcall = upcall;
503         sa->sa_cookie = cookie;
504         if (rqset == PTLRPCD_SET)
505                 ptlrpcd_add_req(req);
506         else
507                 ptlrpc_set_add_req(rqset, req);
508
509         return 0;
510 }
511
512 static int osc_sync_interpret(const struct lu_env *env,
513                               struct ptlrpc_request *req,
514                               void *arg, int rc)
515 {
516         struct osc_fsync_args *fa = arg;
517         struct ost_body *body;
518
519         if (rc)
520                 goto out;
521
522         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
523         if (!body) {
524                 CERROR("can't unpack ost_body\n");
525                 rc = -EPROTO;
526                 goto out;
527         }
528
529         *fa->fa_oi->oi_oa = body->oa;
530 out:
531         rc = fa->fa_upcall(fa->fa_cookie, rc);
532         return rc;
533 }
534
535 int osc_sync_base(struct obd_export *exp, struct obd_info *oinfo,
536                   obd_enqueue_update_f upcall, void *cookie,
537                   struct ptlrpc_request_set *rqset)
538 {
539         struct ptlrpc_request *req;
540         struct ost_body *body;
541         struct osc_fsync_args *fa;
542         int rc;
543
544         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_OST_SYNC);
545         if (!req)
546                 return -ENOMEM;
547
548         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_SYNC);
549         if (rc) {
550                 ptlrpc_request_free(req);
551                 return rc;
552         }
553
554         /* overload the size and blocks fields in the oa with start/end */
555         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
556         LASSERT(body);
557         lustre_set_wire_obdo(&req->rq_import->imp_connect_data, &body->oa,
558                              oinfo->oi_oa);
559
560         ptlrpc_request_set_replen(req);
561         req->rq_interpret_reply = osc_sync_interpret;
562
563         CLASSERT(sizeof(*fa) <= sizeof(req->rq_async_args));
564         fa = ptlrpc_req_async_args(req);
565         fa->fa_oi = oinfo;
566         fa->fa_upcall = upcall;
567         fa->fa_cookie = cookie;
568
569         if (rqset == PTLRPCD_SET)
570                 ptlrpcd_add_req(req);
571         else
572                 ptlrpc_set_add_req(rqset, req);
573
574         return 0;
575 }
576
577 /* Find and cancel locally locks matched by @mode in the resource found by
578  * @objid. Found locks are added into @cancel list. Returns the amount of
579  * locks added to @cancels list.
580  */
581 static int osc_resource_get_unused(struct obd_export *exp, struct obdo *oa,
582                                    struct list_head *cancels,
583                                    enum ldlm_mode mode, __u64 lock_flags)
584 {
585         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
586         struct ldlm_res_id res_id;
587         struct ldlm_resource *res;
588         int count;
589
590         /* Return, i.e. cancel nothing, only if ELC is supported (flag in
591          * export) but disabled through procfs (flag in NS).
592          *
593          * This distinguishes from a case when ELC is not supported originally,
594          * when we still want to cancel locks in advance and just cancel them
595          * locally, without sending any RPC.
596          */
597         if (exp_connect_cancelset(exp) && !ns_connect_cancelset(ns))
598                 return 0;
599
600         ostid_build_res_name(&oa->o_oi, &res_id);
601         res = ldlm_resource_get(ns, NULL, &res_id, 0, 0);
602         if (IS_ERR(res))
603                 return 0;
604
605         LDLM_RESOURCE_ADDREF(res);
606         count = ldlm_cancel_resource_local(res, cancels, NULL, mode,
607                                            lock_flags, 0, NULL);
608         LDLM_RESOURCE_DELREF(res);
609         ldlm_resource_putref(res);
610         return count;
611 }
612
613 static int osc_destroy_interpret(const struct lu_env *env,
614                                  struct ptlrpc_request *req, void *data,
615                                  int rc)
616 {
617         struct client_obd *cli = &req->rq_import->imp_obd->u.cli;
618
619         atomic_dec(&cli->cl_destroy_in_flight);
620         wake_up(&cli->cl_destroy_waitq);
621         return 0;
622 }
623
624 static int osc_can_send_destroy(struct client_obd *cli)
625 {
626         if (atomic_inc_return(&cli->cl_destroy_in_flight) <=
627             cli->cl_max_rpcs_in_flight) {
628                 /* The destroy request can be sent */
629                 return 1;
630         }
631         if (atomic_dec_return(&cli->cl_destroy_in_flight) <
632             cli->cl_max_rpcs_in_flight) {
633                 /*
634                  * The counter has been modified between the two atomic
635                  * operations.
636                  */
637                 wake_up(&cli->cl_destroy_waitq);
638         }
639         return 0;
640 }
641
642 /* Destroy requests can be async always on the client, and we don't even really
643  * care about the return code since the client cannot do anything at all about
644  * a destroy failure.
645  * When the MDS is unlinking a filename, it saves the file objects into a
646  * recovery llog, and these object records are cancelled when the OST reports
647  * they were destroyed and sync'd to disk (i.e. transaction committed).
648  * If the client dies, or the OST is down when the object should be destroyed,
649  * the records are not cancelled, and when the OST reconnects to the MDS next,
650  * it will retrieve the llog unlink logs and then sends the log cancellation
651  * cookies to the MDS after committing destroy transactions.
652  */
653 static int osc_destroy(const struct lu_env *env, struct obd_export *exp,
654                        struct obdo *oa, struct obd_trans_info *oti)
655 {
656         struct client_obd *cli = &exp->exp_obd->u.cli;
657         struct ptlrpc_request *req;
658         struct ost_body *body;
659         LIST_HEAD(cancels);
660         int rc, count;
661
662         if (!oa) {
663                 CDEBUG(D_INFO, "oa NULL\n");
664                 return -EINVAL;
665         }
666
667         count = osc_resource_get_unused(exp, oa, &cancels, LCK_PW,
668                                         LDLM_FL_DISCARD_DATA);
669
670         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_OST_DESTROY);
671         if (!req) {
672                 ldlm_lock_list_put(&cancels, l_bl_ast, count);
673                 return -ENOMEM;
674         }
675
676         rc = ldlm_prep_elc_req(exp, req, LUSTRE_OST_VERSION, OST_DESTROY,
677                                0, &cancels, count);
678         if (rc) {
679                 ptlrpc_request_free(req);
680                 return rc;
681         }
682
683         req->rq_request_portal = OST_IO_PORTAL; /* bug 7198 */
684         ptlrpc_at_set_req_timeout(req);
685
686         if (oti && oa->o_valid & OBD_MD_FLCOOKIE)
687                 oa->o_lcookie = *oti->oti_logcookies;
688         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
689         LASSERT(body);
690         lustre_set_wire_obdo(&req->rq_import->imp_connect_data, &body->oa, oa);
691
692         ptlrpc_request_set_replen(req);
693
694         /* If osc_destroy is for destroying the unlink orphan,
695          * sent from MDT to OST, which should not be blocked here,
696          * because the process might be triggered by ptlrpcd, and
697          * it is not good to block ptlrpcd thread (b=16006
698          **/
699         if (!(oa->o_flags & OBD_FL_DELORPHAN)) {
700                 req->rq_interpret_reply = osc_destroy_interpret;
701                 if (!osc_can_send_destroy(cli)) {
702                         struct l_wait_info lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP,
703                                                           NULL);
704
705                         /*
706                          * Wait until the number of on-going destroy RPCs drops
707                          * under max_rpc_in_flight
708                          */
709                         l_wait_event_exclusive(cli->cl_destroy_waitq,
710                                                osc_can_send_destroy(cli), &lwi);
711                 }
712         }
713
714         /* Do not wait for response */
715         ptlrpcd_add_req(req);
716         return 0;
717 }
718
719 static void osc_announce_cached(struct client_obd *cli, struct obdo *oa,
720                                 long writing_bytes)
721 {
722         u32 bits = OBD_MD_FLBLOCKS | OBD_MD_FLGRANT;
723
724         LASSERT(!(oa->o_valid & bits));
725
726         oa->o_valid |= bits;
727         spin_lock(&cli->cl_loi_list_lock);
728         oa->o_dirty = cli->cl_dirty_pages << PAGE_SHIFT;
729         if (unlikely(cli->cl_dirty_pages - cli->cl_dirty_transit >
730                      cli->cl_dirty_max_pages)) {
731                 CERROR("dirty %lu - %lu > dirty_max %lu\n",
732                        cli->cl_dirty_pages, cli->cl_dirty_transit,
733                        cli->cl_dirty_max_pages);
734                 oa->o_undirty = 0;
735         } else if (unlikely(atomic_long_read(&obd_dirty_pages) -
736                             atomic_long_read(&obd_dirty_transit_pages) >
737                             (obd_max_dirty_pages + 1))) {
738                 /* The atomic_read() allowing the atomic_inc() are
739                  * not covered by a lock thus they may safely race and trip
740                  * this CERROR() unless we add in a small fudge factor (+1).
741                  */
742                 CERROR("%s: dirty %ld + %ld > system dirty_max %lu\n",
743                        cli->cl_import->imp_obd->obd_name,
744                        atomic_long_read(&obd_dirty_pages),
745                        atomic_long_read(&obd_dirty_transit_pages),
746                        obd_max_dirty_pages);
747                 oa->o_undirty = 0;
748         } else if (unlikely(cli->cl_dirty_max_pages - cli->cl_dirty_pages >
749                    0x7fffffff)) {
750                 CERROR("dirty %lu - dirty_max %lu too big???\n",
751                        cli->cl_dirty_pages, cli->cl_dirty_max_pages);
752                 oa->o_undirty = 0;
753         } else {
754                 unsigned long max_in_flight;
755
756                 max_in_flight = (cli->cl_max_pages_per_rpc << PAGE_SHIFT) *
757                                 (cli->cl_max_rpcs_in_flight + 1);
758                 oa->o_undirty = max(cli->cl_dirty_max_pages << PAGE_SHIFT,
759                                     max_in_flight);
760         }
761         oa->o_grant = cli->cl_avail_grant + cli->cl_reserved_grant;
762         oa->o_dropped = cli->cl_lost_grant;
763         cli->cl_lost_grant = 0;
764         spin_unlock(&cli->cl_loi_list_lock);
765         CDEBUG(D_CACHE, "dirty: %llu undirty: %u dropped %u grant: %llu\n",
766                oa->o_dirty, oa->o_undirty, oa->o_dropped, oa->o_grant);
767 }
768
769 void osc_update_next_shrink(struct client_obd *cli)
770 {
771         cli->cl_next_shrink_grant =
772                 cfs_time_shift(cli->cl_grant_shrink_interval);
773         CDEBUG(D_CACHE, "next time %ld to shrink grant\n",
774                cli->cl_next_shrink_grant);
775 }
776
777 static void __osc_update_grant(struct client_obd *cli, u64 grant)
778 {
779         spin_lock(&cli->cl_loi_list_lock);
780         cli->cl_avail_grant += grant;
781         spin_unlock(&cli->cl_loi_list_lock);
782 }
783
784 static void osc_update_grant(struct client_obd *cli, struct ost_body *body)
785 {
786         if (body->oa.o_valid & OBD_MD_FLGRANT) {
787                 CDEBUG(D_CACHE, "got %llu extra grant\n", body->oa.o_grant);
788                 __osc_update_grant(cli, body->oa.o_grant);
789         }
790 }
791
792 static int osc_set_info_async(const struct lu_env *env, struct obd_export *exp,
793                               u32 keylen, void *key, u32 vallen,
794                               void *val, struct ptlrpc_request_set *set);
795
796 static int osc_shrink_grant_interpret(const struct lu_env *env,
797                                       struct ptlrpc_request *req,
798                                       void *aa, int rc)
799 {
800         struct client_obd *cli = &req->rq_import->imp_obd->u.cli;
801         struct obdo *oa = ((struct osc_brw_async_args *)aa)->aa_oa;
802         struct ost_body *body;
803
804         if (rc != 0) {
805                 __osc_update_grant(cli, oa->o_grant);
806                 goto out;
807         }
808
809         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
810         LASSERT(body);
811         osc_update_grant(cli, body);
812 out:
813         kmem_cache_free(obdo_cachep, oa);
814         return rc;
815 }
816
817 static void osc_shrink_grant_local(struct client_obd *cli, struct obdo *oa)
818 {
819         spin_lock(&cli->cl_loi_list_lock);
820         oa->o_grant = cli->cl_avail_grant / 4;
821         cli->cl_avail_grant -= oa->o_grant;
822         spin_unlock(&cli->cl_loi_list_lock);
823         if (!(oa->o_valid & OBD_MD_FLFLAGS)) {
824                 oa->o_valid |= OBD_MD_FLFLAGS;
825                 oa->o_flags = 0;
826         }
827         oa->o_flags |= OBD_FL_SHRINK_GRANT;
828         osc_update_next_shrink(cli);
829 }
830
831 /* Shrink the current grant, either from some large amount to enough for a
832  * full set of in-flight RPCs, or if we have already shrunk to that limit
833  * then to enough for a single RPC.  This avoids keeping more grant than
834  * needed, and avoids shrinking the grant piecemeal.
835  */
836 static int osc_shrink_grant(struct client_obd *cli)
837 {
838         __u64 target_bytes = (cli->cl_max_rpcs_in_flight + 1) *
839                              (cli->cl_max_pages_per_rpc << PAGE_SHIFT);
840
841         spin_lock(&cli->cl_loi_list_lock);
842         if (cli->cl_avail_grant <= target_bytes)
843                 target_bytes = cli->cl_max_pages_per_rpc << PAGE_SHIFT;
844         spin_unlock(&cli->cl_loi_list_lock);
845
846         return osc_shrink_grant_to_target(cli, target_bytes);
847 }
848
849 int osc_shrink_grant_to_target(struct client_obd *cli, __u64 target_bytes)
850 {
851         int rc = 0;
852         struct ost_body *body;
853
854         spin_lock(&cli->cl_loi_list_lock);
855         /* Don't shrink if we are already above or below the desired limit
856          * We don't want to shrink below a single RPC, as that will negatively
857          * impact block allocation and long-term performance.
858          */
859         if (target_bytes < cli->cl_max_pages_per_rpc << PAGE_SHIFT)
860                 target_bytes = cli->cl_max_pages_per_rpc << PAGE_SHIFT;
861
862         if (target_bytes >= cli->cl_avail_grant) {
863                 spin_unlock(&cli->cl_loi_list_lock);
864                 return 0;
865         }
866         spin_unlock(&cli->cl_loi_list_lock);
867
868         body = kzalloc(sizeof(*body), GFP_NOFS);
869         if (!body)
870                 return -ENOMEM;
871
872         osc_announce_cached(cli, &body->oa, 0);
873
874         spin_lock(&cli->cl_loi_list_lock);
875         body->oa.o_grant = cli->cl_avail_grant - target_bytes;
876         cli->cl_avail_grant = target_bytes;
877         spin_unlock(&cli->cl_loi_list_lock);
878         if (!(body->oa.o_valid & OBD_MD_FLFLAGS)) {
879                 body->oa.o_valid |= OBD_MD_FLFLAGS;
880                 body->oa.o_flags = 0;
881         }
882         body->oa.o_flags |= OBD_FL_SHRINK_GRANT;
883         osc_update_next_shrink(cli);
884
885         rc = osc_set_info_async(NULL, cli->cl_import->imp_obd->obd_self_export,
886                                 sizeof(KEY_GRANT_SHRINK), KEY_GRANT_SHRINK,
887                                 sizeof(*body), body, NULL);
888         if (rc != 0)
889                 __osc_update_grant(cli, body->oa.o_grant);
890         kfree(body);
891         return rc;
892 }
893
894 static int osc_should_shrink_grant(struct client_obd *client)
895 {
896         unsigned long time = cfs_time_current();
897         unsigned long next_shrink = client->cl_next_shrink_grant;
898
899         if ((client->cl_import->imp_connect_data.ocd_connect_flags &
900              OBD_CONNECT_GRANT_SHRINK) == 0)
901                 return 0;
902
903         if (cfs_time_aftereq(time, next_shrink - 5 * CFS_TICK)) {
904                 /* Get the current RPC size directly, instead of going via:
905                  * cli_brw_size(obd->u.cli.cl_import->imp_obd->obd_self_export)
906                  * Keep comment here so that it can be found by searching.
907                  */
908                 int brw_size = client->cl_max_pages_per_rpc << PAGE_SHIFT;
909
910                 if (client->cl_import->imp_state == LUSTRE_IMP_FULL &&
911                     client->cl_avail_grant > brw_size)
912                         return 1;
913
914                 osc_update_next_shrink(client);
915         }
916         return 0;
917 }
918
919 static int osc_grant_shrink_grant_cb(struct timeout_item *item, void *data)
920 {
921         struct client_obd *client;
922
923         list_for_each_entry(client, &item->ti_obd_list, cl_grant_shrink_list) {
924                 if (osc_should_shrink_grant(client))
925                         osc_shrink_grant(client);
926         }
927         return 0;
928 }
929
930 static int osc_add_shrink_grant(struct client_obd *client)
931 {
932         int rc;
933
934         rc = ptlrpc_add_timeout_client(client->cl_grant_shrink_interval,
935                                        TIMEOUT_GRANT,
936                                        osc_grant_shrink_grant_cb, NULL,
937                                        &client->cl_grant_shrink_list);
938         if (rc) {
939                 CERROR("add grant client %s error %d\n",
940                        client->cl_import->imp_obd->obd_name, rc);
941                 return rc;
942         }
943         CDEBUG(D_CACHE, "add grant client %s\n",
944                client->cl_import->imp_obd->obd_name);
945         osc_update_next_shrink(client);
946         return 0;
947 }
948
949 static int osc_del_shrink_grant(struct client_obd *client)
950 {
951         return ptlrpc_del_timeout_client(&client->cl_grant_shrink_list,
952                                          TIMEOUT_GRANT);
953 }
954
955 static void osc_init_grant(struct client_obd *cli, struct obd_connect_data *ocd)
956 {
957         /*
958          * ocd_grant is the total grant amount we're expect to hold: if we've
959          * been evicted, it's the new avail_grant amount, cl_dirty_pages will
960          * drop to 0 as inflight RPCs fail out; otherwise, it's avail_grant +
961          * dirty.
962          *
963          * race is tolerable here: if we're evicted, but imp_state already
964          * left EVICTED state, then cl_dirty_pages must be 0 already.
965          */
966         spin_lock(&cli->cl_loi_list_lock);
967         if (cli->cl_import->imp_state == LUSTRE_IMP_EVICTED)
968                 cli->cl_avail_grant = ocd->ocd_grant;
969         else
970                 cli->cl_avail_grant = ocd->ocd_grant -
971                                       (cli->cl_dirty_pages << PAGE_SHIFT);
972
973         if (cli->cl_avail_grant < 0) {
974                 CWARN("%s: available grant < 0: avail/ocd/dirty %ld/%u/%ld\n",
975                       cli->cl_import->imp_obd->obd_name, cli->cl_avail_grant,
976                       ocd->ocd_grant, cli->cl_dirty_pages << PAGE_SHIFT);
977                 /* workaround for servers which do not have the patch from
978                  * LU-2679
979                  */
980                 cli->cl_avail_grant = ocd->ocd_grant;
981         }
982
983         /* determine the appropriate chunk size used by osc_extent. */
984         cli->cl_chunkbits = max_t(int, PAGE_SHIFT, ocd->ocd_blocksize);
985         spin_unlock(&cli->cl_loi_list_lock);
986
987         CDEBUG(D_CACHE, "%s, setting cl_avail_grant: %ld cl_lost_grant: %ld chunk bits: %d\n",
988                cli->cl_import->imp_obd->obd_name,
989                cli->cl_avail_grant, cli->cl_lost_grant, cli->cl_chunkbits);
990
991         if (ocd->ocd_connect_flags & OBD_CONNECT_GRANT_SHRINK &&
992             list_empty(&cli->cl_grant_shrink_list))
993                 osc_add_shrink_grant(cli);
994 }
995
996 /* We assume that the reason this OSC got a short read is because it read
997  * beyond the end of a stripe file; i.e. lustre is reading a sparse file
998  * via the LOV, and it _knows_ it's reading inside the file, it's just that
999  * this stripe never got written at or beyond this stripe offset yet.
1000  */
1001 static void handle_short_read(int nob_read, u32 page_count,
1002                               struct brw_page **pga)
1003 {
1004         char *ptr;
1005         int i = 0;
1006
1007         /* skip bytes read OK */
1008         while (nob_read > 0) {
1009                 LASSERT(page_count > 0);
1010
1011                 if (pga[i]->count > nob_read) {
1012                         /* EOF inside this page */
1013                         ptr = kmap(pga[i]->pg) +
1014                                 (pga[i]->off & ~PAGE_MASK);
1015                         memset(ptr + nob_read, 0, pga[i]->count - nob_read);
1016                         kunmap(pga[i]->pg);
1017                         page_count--;
1018                         i++;
1019                         break;
1020                 }
1021
1022                 nob_read -= pga[i]->count;
1023                 page_count--;
1024                 i++;
1025         }
1026
1027         /* zero remaining pages */
1028         while (page_count-- > 0) {
1029                 ptr = kmap(pga[i]->pg) + (pga[i]->off & ~PAGE_MASK);
1030                 memset(ptr, 0, pga[i]->count);
1031                 kunmap(pga[i]->pg);
1032                 i++;
1033         }
1034 }
1035
1036 static int check_write_rcs(struct ptlrpc_request *req,
1037                            int requested_nob, int niocount,
1038                            u32 page_count, struct brw_page **pga)
1039 {
1040         int i;
1041         __u32 *remote_rcs;
1042
1043         remote_rcs = req_capsule_server_sized_get(&req->rq_pill, &RMF_RCS,
1044                                                   sizeof(*remote_rcs) *
1045                                                   niocount);
1046         if (!remote_rcs) {
1047                 CDEBUG(D_INFO, "Missing/short RC vector on BRW_WRITE reply\n");
1048                 return -EPROTO;
1049         }
1050
1051         /* return error if any niobuf was in error */
1052         for (i = 0; i < niocount; i++) {
1053                 if ((int)remote_rcs[i] < 0)
1054                         return remote_rcs[i];
1055
1056                 if (remote_rcs[i] != 0) {
1057                         CDEBUG(D_INFO, "rc[%d] invalid (%d) req %p\n",
1058                                i, remote_rcs[i], req);
1059                         return -EPROTO;
1060                 }
1061         }
1062
1063         if (req->rq_bulk->bd_nob_transferred != requested_nob) {
1064                 CERROR("Unexpected # bytes transferred: %d (requested %d)\n",
1065                        req->rq_bulk->bd_nob_transferred, requested_nob);
1066                 return -EPROTO;
1067         }
1068
1069         return 0;
1070 }
1071
1072 static inline int can_merge_pages(struct brw_page *p1, struct brw_page *p2)
1073 {
1074         if (p1->flag != p2->flag) {
1075                 unsigned mask = ~(OBD_BRW_FROM_GRANT | OBD_BRW_NOCACHE |
1076                                   OBD_BRW_SYNC | OBD_BRW_ASYNC |
1077                                   OBD_BRW_NOQUOTA | OBD_BRW_SOFT_SYNC);
1078
1079                 /* warn if we try to combine flags that we don't know to be
1080                  * safe to combine
1081                  */
1082                 if (unlikely((p1->flag & mask) != (p2->flag & mask))) {
1083                         CWARN("Saw flags 0x%x and 0x%x in the same brw, please report this at http://bugs.whamcloud.com/\n",
1084                               p1->flag, p2->flag);
1085                 }
1086                 return 0;
1087         }
1088
1089         return (p1->off + p1->count == p2->off);
1090 }
1091
1092 static u32 osc_checksum_bulk(int nob, u32 pg_count,
1093                              struct brw_page **pga, int opc,
1094                              enum cksum_type cksum_type)
1095 {
1096         __u32 cksum;
1097         int i = 0;
1098         struct cfs_crypto_hash_desc *hdesc;
1099         unsigned int bufsize;
1100         int err;
1101         unsigned char cfs_alg = cksum_obd2cfs(cksum_type);
1102
1103         LASSERT(pg_count > 0);
1104
1105         hdesc = cfs_crypto_hash_init(cfs_alg, NULL, 0);
1106         if (IS_ERR(hdesc)) {
1107                 CERROR("Unable to initialize checksum hash %s\n",
1108                        cfs_crypto_hash_name(cfs_alg));
1109                 return PTR_ERR(hdesc);
1110         }
1111
1112         while (nob > 0 && pg_count > 0) {
1113                 unsigned int count = pga[i]->count > nob ? nob : pga[i]->count;
1114
1115                 /* corrupt the data before we compute the checksum, to
1116                  * simulate an OST->client data error
1117                  */
1118                 if (i == 0 && opc == OST_READ &&
1119                     OBD_FAIL_CHECK(OBD_FAIL_OSC_CHECKSUM_RECEIVE)) {
1120                         unsigned char *ptr = kmap(pga[i]->pg);
1121                         int off = pga[i]->off & ~PAGE_MASK;
1122
1123                         memcpy(ptr + off, "bad1", min_t(typeof(nob), 4, nob));
1124                         kunmap(pga[i]->pg);
1125                 }
1126                 cfs_crypto_hash_update_page(hdesc, pga[i]->pg,
1127                                             pga[i]->off & ~PAGE_MASK,
1128                                   count);
1129                 CDEBUG(D_PAGE,
1130                        "page %p map %p index %lu flags %lx count %u priv %0lx: off %d\n",
1131                        pga[i]->pg, pga[i]->pg->mapping, pga[i]->pg->index,
1132                        (long)pga[i]->pg->flags, page_count(pga[i]->pg),
1133                        page_private(pga[i]->pg),
1134                        (int)(pga[i]->off & ~PAGE_MASK));
1135
1136                 nob -= pga[i]->count;
1137                 pg_count--;
1138                 i++;
1139         }
1140
1141         bufsize = sizeof(cksum);
1142         err = cfs_crypto_hash_final(hdesc, (unsigned char *)&cksum, &bufsize);
1143
1144         /* For sending we only compute the wrong checksum instead
1145          * of corrupting the data so it is still correct on a redo
1146          */
1147         if (opc == OST_WRITE && OBD_FAIL_CHECK(OBD_FAIL_OSC_CHECKSUM_SEND))
1148                 cksum++;
1149
1150         return cksum;
1151 }
1152
1153 static int osc_brw_prep_request(int cmd, struct client_obd *cli,
1154                                 struct obdo *oa,
1155                                 struct lov_stripe_md *lsm, u32 page_count,
1156                                 struct brw_page **pga,
1157                                 struct ptlrpc_request **reqp,
1158                                 int reserve,
1159                                 int resend)
1160 {
1161         struct ptlrpc_request *req;
1162         struct ptlrpc_bulk_desc *desc;
1163         struct ost_body *body;
1164         struct obd_ioobj *ioobj;
1165         struct niobuf_remote *niobuf;
1166         int niocount, i, requested_nob, opc, rc;
1167         struct osc_brw_async_args *aa;
1168         struct req_capsule *pill;
1169         struct brw_page *pg_prev;
1170
1171         if (OBD_FAIL_CHECK(OBD_FAIL_OSC_BRW_PREP_REQ))
1172                 return -ENOMEM; /* Recoverable */
1173         if (OBD_FAIL_CHECK(OBD_FAIL_OSC_BRW_PREP_REQ2))
1174                 return -EINVAL; /* Fatal */
1175
1176         if ((cmd & OBD_BRW_WRITE) != 0) {
1177                 opc = OST_WRITE;
1178                 req = ptlrpc_request_alloc_pool(cli->cl_import,
1179                                                 osc_rq_pool,
1180                                                 &RQF_OST_BRW_WRITE);
1181         } else {
1182                 opc = OST_READ;
1183                 req = ptlrpc_request_alloc(cli->cl_import, &RQF_OST_BRW_READ);
1184         }
1185         if (!req)
1186                 return -ENOMEM;
1187
1188         for (niocount = i = 1; i < page_count; i++) {
1189                 if (!can_merge_pages(pga[i - 1], pga[i]))
1190                         niocount++;
1191         }
1192
1193         pill = &req->rq_pill;
1194         req_capsule_set_size(pill, &RMF_OBD_IOOBJ, RCL_CLIENT,
1195                              sizeof(*ioobj));
1196         req_capsule_set_size(pill, &RMF_NIOBUF_REMOTE, RCL_CLIENT,
1197                              niocount * sizeof(*niobuf));
1198
1199         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, opc);
1200         if (rc) {
1201                 ptlrpc_request_free(req);
1202                 return rc;
1203         }
1204         req->rq_request_portal = OST_IO_PORTAL; /* bug 7198 */
1205         ptlrpc_at_set_req_timeout(req);
1206         /* ask ptlrpc not to resend on EINPROGRESS since BRWs have their own
1207          * retry logic
1208          */
1209         req->rq_no_retry_einprogress = 1;
1210
1211         desc = ptlrpc_prep_bulk_imp(req, page_count,
1212                 cli->cl_import->imp_connect_data.ocd_brw_size >> LNET_MTU_BITS,
1213                 opc == OST_WRITE ? BULK_GET_SOURCE : BULK_PUT_SINK,
1214                 OST_BULK_PORTAL);
1215
1216         if (!desc) {
1217                 rc = -ENOMEM;
1218                 goto out;
1219         }
1220         /* NB request now owns desc and will free it when it gets freed */
1221
1222         body = req_capsule_client_get(pill, &RMF_OST_BODY);
1223         ioobj = req_capsule_client_get(pill, &RMF_OBD_IOOBJ);
1224         niobuf = req_capsule_client_get(pill, &RMF_NIOBUF_REMOTE);
1225         LASSERT(body && ioobj && niobuf);
1226
1227         lustre_set_wire_obdo(&req->rq_import->imp_connect_data, &body->oa, oa);
1228
1229         obdo_to_ioobj(oa, ioobj);
1230         ioobj->ioo_bufcnt = niocount;
1231         /* The high bits of ioo_max_brw tells server _maximum_ number of bulks
1232          * that might be send for this request.  The actual number is decided
1233          * when the RPC is finally sent in ptlrpc_register_bulk(). It sends
1234          * "max - 1" for old client compatibility sending "0", and also so the
1235          * the actual maximum is a power-of-two number, not one less. LU-1431
1236          */
1237         ioobj_max_brw_set(ioobj, desc->bd_md_max_brw);
1238         LASSERT(page_count > 0);
1239         pg_prev = pga[0];
1240         for (requested_nob = i = 0; i < page_count; i++, niobuf++) {
1241                 struct brw_page *pg = pga[i];
1242                 int poff = pg->off & ~PAGE_MASK;
1243
1244                 LASSERT(pg->count > 0);
1245                 /* make sure there is no gap in the middle of page array */
1246                 LASSERTF(page_count == 1 ||
1247                          (ergo(i == 0, poff + pg->count == PAGE_SIZE) &&
1248                           ergo(i > 0 && i < page_count - 1,
1249                                poff == 0 && pg->count == PAGE_SIZE)   &&
1250                           ergo(i == page_count - 1, poff == 0)),
1251                          "i: %d/%d pg: %p off: %llu, count: %u\n",
1252                          i, page_count, pg, pg->off, pg->count);
1253                 LASSERTF(i == 0 || pg->off > pg_prev->off,
1254                          "i %d p_c %u pg %p [pri %lu ind %lu] off %llu prev_pg %p [pri %lu ind %lu] off %llu\n",
1255                          i, page_count,
1256                          pg->pg, page_private(pg->pg), pg->pg->index, pg->off,
1257                          pg_prev->pg, page_private(pg_prev->pg),
1258                          pg_prev->pg->index, pg_prev->off);
1259                 LASSERT((pga[0]->flag & OBD_BRW_SRVLOCK) ==
1260                         (pg->flag & OBD_BRW_SRVLOCK));
1261
1262                 ptlrpc_prep_bulk_page_pin(desc, pg->pg, poff, pg->count);
1263                 requested_nob += pg->count;
1264
1265                 if (i > 0 && can_merge_pages(pg_prev, pg)) {
1266                         niobuf--;
1267                         niobuf->rnb_len += pg->count;
1268                 } else {
1269                         niobuf->rnb_offset = pg->off;
1270                         niobuf->rnb_len = pg->count;
1271                         niobuf->rnb_flags = pg->flag;
1272                 }
1273                 pg_prev = pg;
1274         }
1275
1276         LASSERTF((void *)(niobuf - niocount) ==
1277                 req_capsule_client_get(&req->rq_pill, &RMF_NIOBUF_REMOTE),
1278                 "want %p - real %p\n", req_capsule_client_get(&req->rq_pill,
1279                 &RMF_NIOBUF_REMOTE), (void *)(niobuf - niocount));
1280
1281         osc_announce_cached(cli, &body->oa, opc == OST_WRITE ? requested_nob:0);
1282         if (resend) {
1283                 if ((body->oa.o_valid & OBD_MD_FLFLAGS) == 0) {
1284                         body->oa.o_valid |= OBD_MD_FLFLAGS;
1285                         body->oa.o_flags = 0;
1286                 }
1287                 body->oa.o_flags |= OBD_FL_RECOV_RESEND;
1288         }
1289
1290         if (osc_should_shrink_grant(cli))
1291                 osc_shrink_grant_local(cli, &body->oa);
1292
1293         /* size[REQ_REC_OFF] still sizeof (*body) */
1294         if (opc == OST_WRITE) {
1295                 if (cli->cl_checksum &&
1296                     !sptlrpc_flavor_has_bulk(&req->rq_flvr)) {
1297                         /* store cl_cksum_type in a local variable since
1298                          * it can be changed via lprocfs
1299                          */
1300                         enum cksum_type cksum_type = cli->cl_cksum_type;
1301
1302                         if ((body->oa.o_valid & OBD_MD_FLFLAGS) == 0) {
1303                                 oa->o_flags &= OBD_FL_LOCAL_MASK;
1304                                 body->oa.o_flags = 0;
1305                         }
1306                         body->oa.o_flags |= cksum_type_pack(cksum_type);
1307                         body->oa.o_valid |= OBD_MD_FLCKSUM | OBD_MD_FLFLAGS;
1308                         body->oa.o_cksum = osc_checksum_bulk(requested_nob,
1309                                                              page_count, pga,
1310                                                              OST_WRITE,
1311                                                              cksum_type);
1312                         CDEBUG(D_PAGE, "checksum at write origin: %x\n",
1313                                body->oa.o_cksum);
1314                         /* save this in 'oa', too, for later checking */
1315                         oa->o_valid |= OBD_MD_FLCKSUM | OBD_MD_FLFLAGS;
1316                         oa->o_flags |= cksum_type_pack(cksum_type);
1317                 } else {
1318                         /* clear out the checksum flag, in case this is a
1319                          * resend but cl_checksum is no longer set. b=11238
1320                          */
1321                         oa->o_valid &= ~OBD_MD_FLCKSUM;
1322                 }
1323                 oa->o_cksum = body->oa.o_cksum;
1324                 /* 1 RC per niobuf */
1325                 req_capsule_set_size(pill, &RMF_RCS, RCL_SERVER,
1326                                      sizeof(__u32) * niocount);
1327         } else {
1328                 if (cli->cl_checksum &&
1329                     !sptlrpc_flavor_has_bulk(&req->rq_flvr)) {
1330                         if ((body->oa.o_valid & OBD_MD_FLFLAGS) == 0)
1331                                 body->oa.o_flags = 0;
1332                         body->oa.o_flags |= cksum_type_pack(cli->cl_cksum_type);
1333                         body->oa.o_valid |= OBD_MD_FLCKSUM | OBD_MD_FLFLAGS;
1334                 }
1335         }
1336         ptlrpc_request_set_replen(req);
1337
1338         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
1339         aa = ptlrpc_req_async_args(req);
1340         aa->aa_oa = oa;
1341         aa->aa_requested_nob = requested_nob;
1342         aa->aa_nio_count = niocount;
1343         aa->aa_page_count = page_count;
1344         aa->aa_resends = 0;
1345         aa->aa_ppga = pga;
1346         aa->aa_cli = cli;
1347         INIT_LIST_HEAD(&aa->aa_oaps);
1348
1349         *reqp = req;
1350         niobuf = req_capsule_client_get(pill, &RMF_NIOBUF_REMOTE);
1351         CDEBUG(D_RPCTRACE, "brw rpc %p - object " DOSTID " offset %lld<>%lld\n",
1352                req, POSTID(&oa->o_oi), niobuf[0].rnb_offset,
1353                niobuf[niocount - 1].rnb_offset + niobuf[niocount - 1].rnb_len);
1354
1355         return 0;
1356
1357  out:
1358         ptlrpc_req_finished(req);
1359         return rc;
1360 }
1361
1362 static int check_write_checksum(struct obdo *oa, const lnet_process_id_t *peer,
1363                                 __u32 client_cksum, __u32 server_cksum, int nob,
1364                                 u32 page_count, struct brw_page **pga,
1365                                 enum cksum_type client_cksum_type)
1366 {
1367         __u32 new_cksum;
1368         char *msg;
1369         enum cksum_type cksum_type;
1370
1371         if (server_cksum == client_cksum) {
1372                 CDEBUG(D_PAGE, "checksum %x confirmed\n", client_cksum);
1373                 return 0;
1374         }
1375
1376         cksum_type = cksum_type_unpack(oa->o_valid & OBD_MD_FLFLAGS ?
1377                                        oa->o_flags : 0);
1378         new_cksum = osc_checksum_bulk(nob, page_count, pga, OST_WRITE,
1379                                       cksum_type);
1380
1381         if (cksum_type != client_cksum_type)
1382                 msg = "the server did not use the checksum type specified in the original request - likely a protocol problem"
1383                         ;
1384         else if (new_cksum == server_cksum)
1385                 msg = "changed on the client after we checksummed it - likely false positive due to mmap IO (bug 11742)"
1386                         ;
1387         else if (new_cksum == client_cksum)
1388                 msg = "changed in transit before arrival at OST";
1389         else
1390                 msg = "changed in transit AND doesn't match the original - likely false positive due to mmap IO (bug 11742)"
1391                         ;
1392
1393         LCONSOLE_ERROR_MSG(0x132, "BAD WRITE CHECKSUM: %s: from %s inode "DFID
1394                            " object "DOSTID" extent [%llu-%llu]\n",
1395                            msg, libcfs_nid2str(peer->nid),
1396                            oa->o_valid & OBD_MD_FLFID ? oa->o_parent_seq : (__u64)0,
1397                            oa->o_valid & OBD_MD_FLFID ? oa->o_parent_oid : 0,
1398                            oa->o_valid & OBD_MD_FLFID ? oa->o_parent_ver : 0,
1399                            POSTID(&oa->o_oi), pga[0]->off,
1400                            pga[page_count - 1]->off +
1401                            pga[page_count - 1]->count - 1);
1402         CERROR("original client csum %x (type %x), server csum %x (type %x), client csum now %x\n",
1403                client_cksum, client_cksum_type,
1404                server_cksum, cksum_type, new_cksum);
1405         return 1;
1406 }
1407
1408 /* Note rc enters this function as number of bytes transferred */
1409 static int osc_brw_fini_request(struct ptlrpc_request *req, int rc)
1410 {
1411         struct osc_brw_async_args *aa = (void *)&req->rq_async_args;
1412         const lnet_process_id_t *peer =
1413                         &req->rq_import->imp_connection->c_peer;
1414         struct client_obd *cli = aa->aa_cli;
1415         struct ost_body *body;
1416         __u32 client_cksum = 0;
1417
1418         if (rc < 0 && rc != -EDQUOT) {
1419                 DEBUG_REQ(D_INFO, req, "Failed request with rc = %d\n", rc);
1420                 return rc;
1421         }
1422
1423         LASSERTF(req->rq_repmsg, "rc = %d\n", rc);
1424         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
1425         if (!body) {
1426                 DEBUG_REQ(D_INFO, req, "Can't unpack body\n");
1427                 return -EPROTO;
1428         }
1429
1430         /* set/clear over quota flag for a uid/gid */
1431         if (lustre_msg_get_opc(req->rq_reqmsg) == OST_WRITE &&
1432             body->oa.o_valid & (OBD_MD_FLUSRQUOTA | OBD_MD_FLGRPQUOTA)) {
1433                 unsigned int qid[MAXQUOTAS] = { body->oa.o_uid, body->oa.o_gid };
1434
1435                 CDEBUG(D_QUOTA, "setdq for [%u %u] with valid %#llx, flags %x\n",
1436                        body->oa.o_uid, body->oa.o_gid, body->oa.o_valid,
1437                        body->oa.o_flags);
1438                 osc_quota_setdq(cli, qid, body->oa.o_valid, body->oa.o_flags);
1439         }
1440
1441         osc_update_grant(cli, body);
1442
1443         if (rc < 0)
1444                 return rc;
1445
1446         if (aa->aa_oa->o_valid & OBD_MD_FLCKSUM)
1447                 client_cksum = aa->aa_oa->o_cksum; /* save for later */
1448
1449         if (lustre_msg_get_opc(req->rq_reqmsg) == OST_WRITE) {
1450                 if (rc > 0) {
1451                         CERROR("Unexpected +ve rc %d\n", rc);
1452                         return -EPROTO;
1453                 }
1454                 LASSERT(req->rq_bulk->bd_nob == aa->aa_requested_nob);
1455
1456                 if (sptlrpc_cli_unwrap_bulk_write(req, req->rq_bulk))
1457                         return -EAGAIN;
1458
1459                 if ((aa->aa_oa->o_valid & OBD_MD_FLCKSUM) && client_cksum &&
1460                     check_write_checksum(&body->oa, peer, client_cksum,
1461                                          body->oa.o_cksum, aa->aa_requested_nob,
1462                                          aa->aa_page_count, aa->aa_ppga,
1463                                          cksum_type_unpack(aa->aa_oa->o_flags)))
1464                         return -EAGAIN;
1465
1466                 rc = check_write_rcs(req, aa->aa_requested_nob,
1467                                      aa->aa_nio_count,
1468                                      aa->aa_page_count, aa->aa_ppga);
1469                 goto out;
1470         }
1471
1472         /* The rest of this function executes only for OST_READs */
1473
1474         /* if unwrap_bulk failed, return -EAGAIN to retry */
1475         rc = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk, rc);
1476         if (rc < 0) {
1477                 rc = -EAGAIN;
1478                 goto out;
1479         }
1480
1481         if (rc > aa->aa_requested_nob) {
1482                 CERROR("Unexpected rc %d (%d requested)\n", rc,
1483                        aa->aa_requested_nob);
1484                 return -EPROTO;
1485         }
1486
1487         if (rc != req->rq_bulk->bd_nob_transferred) {
1488                 CERROR("Unexpected rc %d (%d transferred)\n",
1489                        rc, req->rq_bulk->bd_nob_transferred);
1490                 return -EPROTO;
1491         }
1492
1493         if (rc < aa->aa_requested_nob)
1494                 handle_short_read(rc, aa->aa_page_count, aa->aa_ppga);
1495
1496         if (body->oa.o_valid & OBD_MD_FLCKSUM) {
1497                 static int cksum_counter;
1498                 __u32 server_cksum = body->oa.o_cksum;
1499                 char *via = "";
1500                 char *router = "";
1501                 enum cksum_type cksum_type;
1502
1503                 cksum_type = cksum_type_unpack(body->oa.o_valid &
1504                                                OBD_MD_FLFLAGS ?
1505                                                body->oa.o_flags : 0);
1506                 client_cksum = osc_checksum_bulk(rc, aa->aa_page_count,
1507                                                  aa->aa_ppga, OST_READ,
1508                                                  cksum_type);
1509
1510                 if (peer->nid != req->rq_bulk->bd_sender) {
1511                         via = " via ";
1512                         router = libcfs_nid2str(req->rq_bulk->bd_sender);
1513                 }
1514
1515                 if (server_cksum != client_cksum) {
1516                         LCONSOLE_ERROR_MSG(0x133, "%s: BAD READ CHECKSUM: from %s%s%s inode " DFID " object " DOSTID " extent [%llu-%llu]\n",
1517                                            req->rq_import->imp_obd->obd_name,
1518                                            libcfs_nid2str(peer->nid),
1519                                            via, router,
1520                                            body->oa.o_valid & OBD_MD_FLFID ?
1521                                            body->oa.o_parent_seq : (__u64)0,
1522                                            body->oa.o_valid & OBD_MD_FLFID ?
1523                                            body->oa.o_parent_oid : 0,
1524                                            body->oa.o_valid & OBD_MD_FLFID ?
1525                                            body->oa.o_parent_ver : 0,
1526                                            POSTID(&body->oa.o_oi),
1527                                            aa->aa_ppga[0]->off,
1528                                            aa->aa_ppga[aa->aa_page_count-1]->off +
1529                                            aa->aa_ppga[aa->aa_page_count-1]->count -
1530                                            1);
1531                         CERROR("client %x, server %x, cksum_type %x\n",
1532                                client_cksum, server_cksum, cksum_type);
1533                         cksum_counter = 0;
1534                         aa->aa_oa->o_cksum = client_cksum;
1535                         rc = -EAGAIN;
1536                 } else {
1537                         cksum_counter++;
1538                         CDEBUG(D_PAGE, "checksum %x confirmed\n", client_cksum);
1539                         rc = 0;
1540                 }
1541         } else if (unlikely(client_cksum)) {
1542                 static int cksum_missed;
1543
1544                 cksum_missed++;
1545                 if ((cksum_missed & (-cksum_missed)) == cksum_missed)
1546                         CERROR("Checksum %u requested from %s but not sent\n",
1547                                cksum_missed, libcfs_nid2str(peer->nid));
1548         } else {
1549                 rc = 0;
1550         }
1551 out:
1552         if (rc >= 0)
1553                 lustre_get_wire_obdo(&req->rq_import->imp_connect_data,
1554                                      aa->aa_oa, &body->oa);
1555
1556         return rc;
1557 }
1558
1559 static int osc_brw_redo_request(struct ptlrpc_request *request,
1560                                 struct osc_brw_async_args *aa, int rc)
1561 {
1562         struct ptlrpc_request *new_req;
1563         struct osc_brw_async_args *new_aa;
1564         struct osc_async_page *oap;
1565
1566         DEBUG_REQ(rc == -EINPROGRESS ? D_RPCTRACE : D_ERROR, request,
1567                   "redo for recoverable error %d", rc);
1568
1569         rc = osc_brw_prep_request(lustre_msg_get_opc(request->rq_reqmsg) ==
1570                                         OST_WRITE ? OBD_BRW_WRITE : OBD_BRW_READ,
1571                                   aa->aa_cli, aa->aa_oa,
1572                                   NULL /* lsm unused by osc currently */,
1573                                   aa->aa_page_count, aa->aa_ppga,
1574                                   &new_req, 0, 1);
1575         if (rc)
1576                 return rc;
1577
1578         list_for_each_entry(oap, &aa->aa_oaps, oap_rpc_item) {
1579                 if (oap->oap_request) {
1580                         LASSERTF(request == oap->oap_request,
1581                                  "request %p != oap_request %p\n",
1582                                  request, oap->oap_request);
1583                         if (oap->oap_interrupted) {
1584                                 ptlrpc_req_finished(new_req);
1585                                 return -EINTR;
1586                         }
1587                 }
1588         }
1589         /* New request takes over pga and oaps from old request.
1590          * Note that copying a list_head doesn't work, need to move it...
1591          */
1592         aa->aa_resends++;
1593         new_req->rq_interpret_reply = request->rq_interpret_reply;
1594         new_req->rq_async_args = request->rq_async_args;
1595         new_req->rq_commit_cb = request->rq_commit_cb;
1596         /* cap resend delay to the current request timeout, this is similar to
1597          * what ptlrpc does (see after_reply())
1598          */
1599         if (aa->aa_resends > new_req->rq_timeout)
1600                 new_req->rq_sent = ktime_get_real_seconds() + new_req->rq_timeout;
1601         else
1602                 new_req->rq_sent = ktime_get_real_seconds() + aa->aa_resends;
1603         new_req->rq_generation_set = 1;
1604         new_req->rq_import_generation = request->rq_import_generation;
1605
1606         new_aa = ptlrpc_req_async_args(new_req);
1607
1608         INIT_LIST_HEAD(&new_aa->aa_oaps);
1609         list_splice_init(&aa->aa_oaps, &new_aa->aa_oaps);
1610         INIT_LIST_HEAD(&new_aa->aa_exts);
1611         list_splice_init(&aa->aa_exts, &new_aa->aa_exts);
1612         new_aa->aa_resends = aa->aa_resends;
1613
1614         list_for_each_entry(oap, &new_aa->aa_oaps, oap_rpc_item) {
1615                 if (oap->oap_request) {
1616                         ptlrpc_req_finished(oap->oap_request);
1617                         oap->oap_request = ptlrpc_request_addref(new_req);
1618                 }
1619         }
1620
1621         /* XXX: This code will run into problem if we're going to support
1622          * to add a series of BRW RPCs into a self-defined ptlrpc_request_set
1623          * and wait for all of them to be finished. We should inherit request
1624          * set from old request.
1625          */
1626         ptlrpcd_add_req(new_req);
1627
1628         DEBUG_REQ(D_INFO, new_req, "new request");
1629         return 0;
1630 }
1631
1632 /*
1633  * ugh, we want disk allocation on the target to happen in offset order.  we'll
1634  * follow sedgewicks advice and stick to the dead simple shellsort -- it'll do
1635  * fine for our small page arrays and doesn't require allocation.  its an
1636  * insertion sort that swaps elements that are strides apart, shrinking the
1637  * stride down until its '1' and the array is sorted.
1638  */
1639 static void sort_brw_pages(struct brw_page **array, int num)
1640 {
1641         int stride, i, j;
1642         struct brw_page *tmp;
1643
1644         if (num == 1)
1645                 return;
1646         for (stride = 1; stride < num ; stride = (stride * 3) + 1)
1647                 ;
1648
1649         do {
1650                 stride /= 3;
1651                 for (i = stride ; i < num ; i++) {
1652                         tmp = array[i];
1653                         j = i;
1654                         while (j >= stride && array[j - stride]->off > tmp->off) {
1655                                 array[j] = array[j - stride];
1656                                 j -= stride;
1657                         }
1658                         array[j] = tmp;
1659                 }
1660         } while (stride > 1);
1661 }
1662
1663 static void osc_release_ppga(struct brw_page **ppga, u32 count)
1664 {
1665         LASSERT(ppga);
1666         kfree(ppga);
1667 }
1668
1669 static int brw_interpret(const struct lu_env *env,
1670                          struct ptlrpc_request *req, void *data, int rc)
1671 {
1672         struct osc_brw_async_args *aa = data;
1673         struct osc_extent *ext;
1674         struct osc_extent *tmp;
1675         struct client_obd *cli = aa->aa_cli;
1676
1677         rc = osc_brw_fini_request(req, rc);
1678         CDEBUG(D_INODE, "request %p aa %p rc %d\n", req, aa, rc);
1679         /* When server return -EINPROGRESS, client should always retry
1680          * regardless of the number of times the bulk was resent already.
1681          */
1682         if (osc_recoverable_error(rc)) {
1683                 if (req->rq_import_generation !=
1684                     req->rq_import->imp_generation) {
1685                         CDEBUG(D_HA, "%s: resend cross eviction for object: " DOSTID ", rc = %d.\n",
1686                                req->rq_import->imp_obd->obd_name,
1687                                POSTID(&aa->aa_oa->o_oi), rc);
1688                 } else if (rc == -EINPROGRESS ||
1689                     client_should_resend(aa->aa_resends, aa->aa_cli)) {
1690                         rc = osc_brw_redo_request(req, aa, rc);
1691                 } else {
1692                         CERROR("%s: too many resent retries for object: %llu:%llu, rc = %d.\n",
1693                                req->rq_import->imp_obd->obd_name,
1694                                POSTID(&aa->aa_oa->o_oi), rc);
1695                 }
1696
1697                 if (rc == 0)
1698                         return 0;
1699                 else if (rc == -EAGAIN || rc == -EINPROGRESS)
1700                         rc = -EIO;
1701         }
1702
1703         if (rc == 0) {
1704                 struct obdo *oa = aa->aa_oa;
1705                 struct cl_attr *attr  = &osc_env_info(env)->oti_attr;
1706                 unsigned long valid = 0;
1707                 struct cl_object *obj;
1708                 struct osc_async_page *last;
1709
1710                 last = brw_page2oap(aa->aa_ppga[aa->aa_page_count - 1]);
1711                 obj = osc2cl(last->oap_obj);
1712
1713                 cl_object_attr_lock(obj);
1714                 if (oa->o_valid & OBD_MD_FLBLOCKS) {
1715                         attr->cat_blocks = oa->o_blocks;
1716                         valid |= CAT_BLOCKS;
1717                 }
1718                 if (oa->o_valid & OBD_MD_FLMTIME) {
1719                         attr->cat_mtime = oa->o_mtime;
1720                         valid |= CAT_MTIME;
1721                 }
1722                 if (oa->o_valid & OBD_MD_FLATIME) {
1723                         attr->cat_atime = oa->o_atime;
1724                         valid |= CAT_ATIME;
1725                 }
1726                 if (oa->o_valid & OBD_MD_FLCTIME) {
1727                         attr->cat_ctime = oa->o_ctime;
1728                         valid |= CAT_CTIME;
1729                 }
1730
1731                 if (lustre_msg_get_opc(req->rq_reqmsg) == OST_WRITE) {
1732                         struct lov_oinfo *loi = cl2osc(obj)->oo_oinfo;
1733                         loff_t last_off = last->oap_count + last->oap_obj_off +
1734                                           last->oap_page_off;
1735
1736                         /* Change file size if this is an out of quota or
1737                          * direct IO write and it extends the file size
1738                          */
1739                         if (loi->loi_lvb.lvb_size < last_off) {
1740                                 attr->cat_size = last_off;
1741                                 valid |= CAT_SIZE;
1742                         }
1743                         /* Extend KMS if it's not a lockless write */
1744                         if (loi->loi_kms < last_off &&
1745                             oap2osc_page(last)->ops_srvlock == 0) {
1746                                 attr->cat_kms = last_off;
1747                                 valid |= CAT_KMS;
1748                         }
1749                 }
1750
1751                 if (valid != 0)
1752                         cl_object_attr_update(env, obj, attr, valid);
1753                 cl_object_attr_unlock(obj);
1754         }
1755         kmem_cache_free(obdo_cachep, aa->aa_oa);
1756
1757         if (lustre_msg_get_opc(req->rq_reqmsg) == OST_WRITE && rc == 0)
1758                 osc_inc_unstable_pages(req);
1759
1760         list_for_each_entry_safe(ext, tmp, &aa->aa_exts, oe_link) {
1761                 list_del_init(&ext->oe_link);
1762                 osc_extent_finish(env, ext, 1, rc);
1763         }
1764         LASSERT(list_empty(&aa->aa_exts));
1765         LASSERT(list_empty(&aa->aa_oaps));
1766
1767         cl_req_completion(env, aa->aa_clerq, rc < 0 ? rc :
1768                           req->rq_bulk->bd_nob_transferred);
1769         osc_release_ppga(aa->aa_ppga, aa->aa_page_count);
1770         ptlrpc_lprocfs_brw(req, req->rq_bulk->bd_nob_transferred);
1771
1772         spin_lock(&cli->cl_loi_list_lock);
1773         /* We need to decrement before osc_ap_completion->osc_wake_cache_waiters
1774          * is called so we know whether to go to sync BRWs or wait for more
1775          * RPCs to complete
1776          */
1777         if (lustre_msg_get_opc(req->rq_reqmsg) == OST_WRITE)
1778                 cli->cl_w_in_flight--;
1779         else
1780                 cli->cl_r_in_flight--;
1781         osc_wake_cache_waiters(cli);
1782         spin_unlock(&cli->cl_loi_list_lock);
1783
1784         osc_io_unplug(env, cli, NULL);
1785         return rc;
1786 }
1787
1788 static void brw_commit(struct ptlrpc_request *req)
1789 {
1790         /*
1791          * If osc_inc_unstable_pages (via osc_extent_finish) races with
1792          * this called via the rq_commit_cb, I need to ensure
1793          * osc_dec_unstable_pages is still called. Otherwise unstable
1794          * pages may be leaked.
1795          */
1796         spin_lock(&req->rq_lock);
1797         if (unlikely(req->rq_unstable)) {
1798                 req->rq_unstable = 0;
1799                 spin_unlock(&req->rq_lock);
1800                 osc_dec_unstable_pages(req);
1801         } else {
1802                 req->rq_committed = 1;
1803                 spin_unlock(&req->rq_lock);
1804         }
1805 }
1806
1807 /**
1808  * Build an RPC by the list of extent @ext_list. The caller must ensure
1809  * that the total pages in this list are NOT over max pages per RPC.
1810  * Extents in the list must be in OES_RPC state.
1811  */
1812 int osc_build_rpc(const struct lu_env *env, struct client_obd *cli,
1813                   struct list_head *ext_list, int cmd)
1814 {
1815         struct ptlrpc_request *req = NULL;
1816         struct osc_extent *ext;
1817         struct brw_page **pga = NULL;
1818         struct osc_brw_async_args *aa = NULL;
1819         struct obdo *oa = NULL;
1820         struct osc_async_page *oap;
1821         struct osc_async_page *tmp;
1822         struct cl_req *clerq = NULL;
1823         enum cl_req_type crt = (cmd & OBD_BRW_WRITE) ? CRT_WRITE : CRT_READ;
1824         struct cl_req_attr *crattr = NULL;
1825         u64 starting_offset = OBD_OBJECT_EOF;
1826         u64 ending_offset = 0;
1827         int mpflag = 0;
1828         int mem_tight = 0;
1829         int page_count = 0;
1830         bool soft_sync = false;
1831         int i;
1832         int rc;
1833         struct ost_body *body;
1834         LIST_HEAD(rpc_list);
1835
1836         LASSERT(!list_empty(ext_list));
1837
1838         /* add pages into rpc_list to build BRW rpc */
1839         list_for_each_entry(ext, ext_list, oe_link) {
1840                 LASSERT(ext->oe_state == OES_RPC);
1841                 mem_tight |= ext->oe_memalloc;
1842                 list_for_each_entry(oap, &ext->oe_pages, oap_pending_item) {
1843                         ++page_count;
1844                         list_add_tail(&oap->oap_rpc_item, &rpc_list);
1845                         if (starting_offset > oap->oap_obj_off)
1846                                 starting_offset = oap->oap_obj_off;
1847                         else
1848                                 LASSERT(oap->oap_page_off == 0);
1849                         if (ending_offset < oap->oap_obj_off + oap->oap_count)
1850                                 ending_offset = oap->oap_obj_off +
1851                                                 oap->oap_count;
1852                         else
1853                                 LASSERT(oap->oap_page_off + oap->oap_count ==
1854                                         PAGE_SIZE);
1855                 }
1856         }
1857
1858         soft_sync = osc_over_unstable_soft_limit(cli);
1859         if (mem_tight)
1860                 mpflag = cfs_memory_pressure_get_and_set();
1861
1862         crattr = kzalloc(sizeof(*crattr), GFP_NOFS);
1863         if (!crattr) {
1864                 rc = -ENOMEM;
1865                 goto out;
1866         }
1867
1868         pga = kcalloc(page_count, sizeof(*pga), GFP_NOFS);
1869         if (!pga) {
1870                 rc = -ENOMEM;
1871                 goto out;
1872         }
1873
1874         oa = kmem_cache_zalloc(obdo_cachep, GFP_NOFS);
1875         if (!oa) {
1876                 rc = -ENOMEM;
1877                 goto out;
1878         }
1879
1880         i = 0;
1881         list_for_each_entry(oap, &rpc_list, oap_rpc_item) {
1882                 struct cl_page *page = oap2cl_page(oap);
1883
1884                 if (!clerq) {
1885                         clerq = cl_req_alloc(env, page, crt,
1886                                              1 /* only 1-object rpcs for now */);
1887                         if (IS_ERR(clerq)) {
1888                                 rc = PTR_ERR(clerq);
1889                                 goto out;
1890                         }
1891                 }
1892                 if (mem_tight)
1893                         oap->oap_brw_flags |= OBD_BRW_MEMALLOC;
1894                 if (soft_sync)
1895                         oap->oap_brw_flags |= OBD_BRW_SOFT_SYNC;
1896                 pga[i] = &oap->oap_brw_page;
1897                 pga[i]->off = oap->oap_obj_off + oap->oap_page_off;
1898                 CDEBUG(0, "put page %p index %lu oap %p flg %x to pga\n",
1899                        pga[i]->pg, oap->oap_page->index, oap,
1900                        pga[i]->flag);
1901                 i++;
1902                 cl_req_page_add(env, clerq, page);
1903         }
1904
1905         /* always get the data for the obdo for the rpc */
1906         LASSERT(clerq);
1907         crattr->cra_oa = oa;
1908         cl_req_attr_set(env, clerq, crattr, ~0ULL);
1909
1910         rc = cl_req_prep(env, clerq);
1911         if (rc != 0) {
1912                 CERROR("cl_req_prep failed: %d\n", rc);
1913                 goto out;
1914         }
1915
1916         sort_brw_pages(pga, page_count);
1917         rc = osc_brw_prep_request(cmd, cli, oa, NULL, page_count,
1918                                   pga, &req, 1, 0);
1919         if (rc != 0) {
1920                 CERROR("prep_req failed: %d\n", rc);
1921                 goto out;
1922         }
1923
1924         req->rq_commit_cb = brw_commit;
1925         req->rq_interpret_reply = brw_interpret;
1926
1927         if (mem_tight != 0)
1928                 req->rq_memalloc = 1;
1929
1930         /* Need to update the timestamps after the request is built in case
1931          * we race with setattr (locally or in queue at OST).  If OST gets
1932          * later setattr before earlier BRW (as determined by the request xid),
1933          * the OST will not use BRW timestamps.  Sadly, there is no obvious
1934          * way to do this in a single call.  bug 10150
1935          */
1936         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
1937         crattr->cra_oa = &body->oa;
1938         cl_req_attr_set(env, clerq, crattr,
1939                         OBD_MD_FLMTIME | OBD_MD_FLCTIME | OBD_MD_FLATIME);
1940
1941         lustre_msg_set_jobid(req->rq_reqmsg, crattr->cra_jobid);
1942
1943         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
1944         aa = ptlrpc_req_async_args(req);
1945         INIT_LIST_HEAD(&aa->aa_oaps);
1946         list_splice_init(&rpc_list, &aa->aa_oaps);
1947         INIT_LIST_HEAD(&aa->aa_exts);
1948         list_splice_init(ext_list, &aa->aa_exts);
1949         aa->aa_clerq = clerq;
1950
1951         /* queued sync pages can be torn down while the pages
1952          * were between the pending list and the rpc
1953          */
1954         tmp = NULL;
1955         list_for_each_entry(oap, &aa->aa_oaps, oap_rpc_item) {
1956                 /* only one oap gets a request reference */
1957                 if (!tmp)
1958                         tmp = oap;
1959                 if (oap->oap_interrupted && !req->rq_intr) {
1960                         CDEBUG(D_INODE, "oap %p in req %p interrupted\n",
1961                                oap, req);
1962                         ptlrpc_mark_interrupted(req);
1963                 }
1964         }
1965         if (tmp)
1966                 tmp->oap_request = ptlrpc_request_addref(req);
1967
1968         spin_lock(&cli->cl_loi_list_lock);
1969         starting_offset >>= PAGE_SHIFT;
1970         if (cmd == OBD_BRW_READ) {
1971                 cli->cl_r_in_flight++;
1972                 lprocfs_oh_tally_log2(&cli->cl_read_page_hist, page_count);
1973                 lprocfs_oh_tally(&cli->cl_read_rpc_hist, cli->cl_r_in_flight);
1974                 lprocfs_oh_tally_log2(&cli->cl_read_offset_hist,
1975                                       starting_offset + 1);
1976         } else {
1977                 cli->cl_w_in_flight++;
1978                 lprocfs_oh_tally_log2(&cli->cl_write_page_hist, page_count);
1979                 lprocfs_oh_tally(&cli->cl_write_rpc_hist, cli->cl_w_in_flight);
1980                 lprocfs_oh_tally_log2(&cli->cl_write_offset_hist,
1981                                       starting_offset + 1);
1982         }
1983         spin_unlock(&cli->cl_loi_list_lock);
1984
1985         DEBUG_REQ(D_INODE, req, "%d pages, aa %p. now %ur/%dw in flight",
1986                   page_count, aa, cli->cl_r_in_flight,
1987                   cli->cl_w_in_flight);
1988
1989         ptlrpcd_add_req(req);
1990         rc = 0;
1991
1992 out:
1993         if (mem_tight != 0)
1994                 cfs_memory_pressure_restore(mpflag);
1995
1996         kfree(crattr);
1997
1998         if (rc != 0) {
1999                 LASSERT(!req);
2000
2001                 if (oa)
2002                         kmem_cache_free(obdo_cachep, oa);
2003                 kfree(pga);
2004                 /* this should happen rarely and is pretty bad, it makes the
2005                  * pending list not follow the dirty order
2006                  */
2007                 while (!list_empty(ext_list)) {
2008                         ext = list_entry(ext_list->next, struct osc_extent,
2009                                          oe_link);
2010                         list_del_init(&ext->oe_link);
2011                         osc_extent_finish(env, ext, 0, rc);
2012                 }
2013                 if (clerq && !IS_ERR(clerq))
2014                         cl_req_completion(env, clerq, rc);
2015         }
2016         return rc;
2017 }
2018
2019 static int osc_set_lock_data_with_check(struct ldlm_lock *lock,
2020                                         struct ldlm_enqueue_info *einfo)
2021 {
2022         void *data = einfo->ei_cbdata;
2023         int set = 0;
2024
2025         LASSERT(lock->l_blocking_ast == einfo->ei_cb_bl);
2026         LASSERT(lock->l_resource->lr_type == einfo->ei_type);
2027         LASSERT(lock->l_completion_ast == einfo->ei_cb_cp);
2028         LASSERT(lock->l_glimpse_ast == einfo->ei_cb_gl);
2029
2030         lock_res_and_lock(lock);
2031
2032         if (!lock->l_ast_data)
2033                 lock->l_ast_data = data;
2034         if (lock->l_ast_data == data)
2035                 set = 1;
2036
2037         unlock_res_and_lock(lock);
2038
2039         return set;
2040 }
2041
2042 static int osc_set_data_with_check(struct lustre_handle *lockh,
2043                                    struct ldlm_enqueue_info *einfo)
2044 {
2045         struct ldlm_lock *lock = ldlm_handle2lock(lockh);
2046         int set = 0;
2047
2048         if (lock) {
2049                 set = osc_set_lock_data_with_check(lock, einfo);
2050                 LDLM_LOCK_PUT(lock);
2051         } else
2052                 CERROR("lockh %p, data %p - client evicted?\n",
2053                        lockh, einfo->ei_cbdata);
2054         return set;
2055 }
2056
2057 static int osc_enqueue_fini(struct ptlrpc_request *req,
2058                             osc_enqueue_upcall_f upcall, void *cookie,
2059                             struct lustre_handle *lockh, enum ldlm_mode mode,
2060                             __u64 *flags, int agl, int errcode)
2061 {
2062         bool intent = *flags & LDLM_FL_HAS_INTENT;
2063         int rc;
2064
2065         /* The request was created before ldlm_cli_enqueue call. */
2066         if (intent && errcode == ELDLM_LOCK_ABORTED) {
2067                 struct ldlm_reply *rep;
2068
2069                 rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
2070
2071                 rep->lock_policy_res1 =
2072                         ptlrpc_status_ntoh(rep->lock_policy_res1);
2073                 if (rep->lock_policy_res1)
2074                         errcode = rep->lock_policy_res1;
2075                 if (!agl)
2076                         *flags |= LDLM_FL_LVB_READY;
2077         } else if (errcode == ELDLM_OK) {
2078                 *flags |= LDLM_FL_LVB_READY;
2079         }
2080
2081         /* Call the update callback. */
2082         rc = (*upcall)(cookie, lockh, errcode);
2083         /* release the reference taken in ldlm_cli_enqueue() */
2084         if (errcode == ELDLM_LOCK_MATCHED)
2085                 errcode = ELDLM_OK;
2086         if (errcode == ELDLM_OK && lustre_handle_is_used(lockh))
2087                 ldlm_lock_decref(lockh, mode);
2088
2089         return rc;
2090 }
2091
2092 static int osc_enqueue_interpret(const struct lu_env *env,
2093                                  struct ptlrpc_request *req,
2094                                  struct osc_enqueue_args *aa, int rc)
2095 {
2096         struct ldlm_lock *lock;
2097         struct lustre_handle *lockh = &aa->oa_lockh;
2098         enum ldlm_mode mode = aa->oa_mode;
2099         struct ost_lvb *lvb = aa->oa_lvb;
2100         __u32 lvb_len = sizeof(*lvb);
2101         __u64 flags = 0;
2102
2103
2104         /* ldlm_cli_enqueue is holding a reference on the lock, so it must
2105          * be valid.
2106          */
2107         lock = ldlm_handle2lock(lockh);
2108         LASSERTF(lock, "lockh %llx, req %p, aa %p - client evicted?\n",
2109                  lockh->cookie, req, aa);
2110
2111         /* Take an additional reference so that a blocking AST that
2112          * ldlm_cli_enqueue_fini() might post for a failed lock, is guaranteed
2113          * to arrive after an upcall has been executed by
2114          * osc_enqueue_fini().
2115          */
2116         ldlm_lock_addref(lockh, mode);
2117
2118         /* Let cl_lock_state_wait fail with -ERESTARTSYS to unuse sublocks. */
2119         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_HANG, 2);
2120
2121         /* Let CP AST to grant the lock first. */
2122         OBD_FAIL_TIMEOUT(OBD_FAIL_OSC_CP_ENQ_RACE, 1);
2123
2124         if (aa->oa_agl) {
2125                 LASSERT(!aa->oa_lvb);
2126                 LASSERT(!aa->oa_flags);
2127                 aa->oa_flags = &flags;
2128         }
2129
2130         /* Complete obtaining the lock procedure. */
2131         rc = ldlm_cli_enqueue_fini(aa->oa_exp, req, aa->oa_type, 1,
2132                                    aa->oa_mode, aa->oa_flags, lvb, lvb_len,
2133                                    lockh, rc);
2134         /* Complete osc stuff. */
2135         rc = osc_enqueue_fini(req, aa->oa_upcall, aa->oa_cookie, lockh, mode,
2136                               aa->oa_flags, aa->oa_agl, rc);
2137
2138         OBD_FAIL_TIMEOUT(OBD_FAIL_OSC_CP_CANCEL_RACE, 10);
2139
2140         ldlm_lock_decref(lockh, mode);
2141         LDLM_LOCK_PUT(lock);
2142         return rc;
2143 }
2144
2145 struct ptlrpc_request_set *PTLRPCD_SET = (void *)1;
2146
2147 /* When enqueuing asynchronously, locks are not ordered, we can obtain a lock
2148  * from the 2nd OSC before a lock from the 1st one. This does not deadlock with
2149  * other synchronous requests, however keeping some locks and trying to obtain
2150  * others may take a considerable amount of time in a case of ost failure; and
2151  * when other sync requests do not get released lock from a client, the client
2152  * is evicted from the cluster -- such scenaries make the life difficult, so
2153  * release locks just after they are obtained.
2154  */
2155 int osc_enqueue_base(struct obd_export *exp, struct ldlm_res_id *res_id,
2156                      __u64 *flags, ldlm_policy_data_t *policy,
2157                      struct ost_lvb *lvb, int kms_valid,
2158                      osc_enqueue_upcall_f upcall, void *cookie,
2159                      struct ldlm_enqueue_info *einfo,
2160                      struct ptlrpc_request_set *rqset, int async, int agl)
2161 {
2162         struct obd_device *obd = exp->exp_obd;
2163         struct lustre_handle lockh = { 0 };
2164         struct ptlrpc_request *req = NULL;
2165         int intent = *flags & LDLM_FL_HAS_INTENT;
2166         __u64 match_flags = *flags;
2167         enum ldlm_mode mode;
2168         int rc;
2169
2170         /* Filesystem lock extents are extended to page boundaries so that
2171          * dealing with the page cache is a little smoother.
2172          */
2173         policy->l_extent.start -= policy->l_extent.start & ~PAGE_MASK;
2174         policy->l_extent.end |= ~PAGE_MASK;
2175
2176         /*
2177          * kms is not valid when either object is completely fresh (so that no
2178          * locks are cached), or object was evicted. In the latter case cached
2179          * lock cannot be used, because it would prime inode state with
2180          * potentially stale LVB.
2181          */
2182         if (!kms_valid)
2183                 goto no_match;
2184
2185         /* Next, search for already existing extent locks that will cover us */
2186         /* If we're trying to read, we also search for an existing PW lock.  The
2187          * VFS and page cache already protect us locally, so lots of readers/
2188          * writers can share a single PW lock.
2189          *
2190          * There are problems with conversion deadlocks, so instead of
2191          * converting a read lock to a write lock, we'll just enqueue a new
2192          * one.
2193          *
2194          * At some point we should cancel the read lock instead of making them
2195          * send us a blocking callback, but there are problems with canceling
2196          * locks out from other users right now, too.
2197          */
2198         mode = einfo->ei_mode;
2199         if (einfo->ei_mode == LCK_PR)
2200                 mode |= LCK_PW;
2201         if (agl == 0)
2202                 match_flags |= LDLM_FL_LVB_READY;
2203         if (intent != 0)
2204                 match_flags |= LDLM_FL_BLOCK_GRANTED;
2205         mode = ldlm_lock_match(obd->obd_namespace, match_flags, res_id,
2206                                einfo->ei_type, policy, mode, &lockh, 0);
2207         if (mode) {
2208                 struct ldlm_lock *matched;
2209
2210                 if (*flags & LDLM_FL_TEST_LOCK)
2211                         return ELDLM_OK;
2212
2213                 matched = ldlm_handle2lock(&lockh);
2214                 if (agl) {
2215                         /* AGL enqueues DLM locks speculatively. Therefore if
2216                          * it already exists a DLM lock, it wll just inform the
2217                          * caller to cancel the AGL process for this stripe.
2218                          */
2219                         ldlm_lock_decref(&lockh, mode);
2220                         LDLM_LOCK_PUT(matched);
2221                         return -ECANCELED;
2222                 } else if (osc_set_lock_data_with_check(matched, einfo)) {
2223                         *flags |= LDLM_FL_LVB_READY;
2224                         /* We already have a lock, and it's referenced. */
2225                         (*upcall)(cookie, &lockh, ELDLM_LOCK_MATCHED);
2226
2227                         ldlm_lock_decref(&lockh, mode);
2228                         LDLM_LOCK_PUT(matched);
2229                         return ELDLM_OK;
2230                 } else {
2231                         ldlm_lock_decref(&lockh, mode);
2232                         LDLM_LOCK_PUT(matched);
2233                 }
2234         }
2235
2236 no_match:
2237         if (*flags & LDLM_FL_TEST_LOCK)
2238                 return -ENOLCK;
2239         if (intent) {
2240                 req = ptlrpc_request_alloc(class_exp2cliimp(exp),
2241                                            &RQF_LDLM_ENQUEUE_LVB);
2242                 if (!req)
2243                         return -ENOMEM;
2244
2245                 rc = ldlm_prep_enqueue_req(exp, req, NULL, 0);
2246                 if (rc) {
2247                         ptlrpc_request_free(req);
2248                         return rc;
2249                 }
2250
2251                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
2252                                      sizeof(*lvb));
2253                 ptlrpc_request_set_replen(req);
2254         }
2255
2256         /* users of osc_enqueue() can pass this flag for ldlm_lock_match() */
2257         *flags &= ~LDLM_FL_BLOCK_GRANTED;
2258
2259         rc = ldlm_cli_enqueue(exp, &req, einfo, res_id, policy, flags, lvb,
2260                               sizeof(*lvb), LVB_T_OST, &lockh, async);
2261         if (async) {
2262                 if (!rc) {
2263                         struct osc_enqueue_args *aa;
2264
2265                         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
2266                         aa = ptlrpc_req_async_args(req);
2267                         aa->oa_exp = exp;
2268                         aa->oa_mode = einfo->ei_mode;
2269                         aa->oa_type = einfo->ei_type;
2270                         lustre_handle_copy(&aa->oa_lockh, &lockh);
2271                         aa->oa_upcall = upcall;
2272                         aa->oa_cookie = cookie;
2273                         aa->oa_agl    = !!agl;
2274                         if (!agl) {
2275                                 aa->oa_flags = flags;
2276                                 aa->oa_lvb = lvb;
2277                         } else {
2278                                 /* AGL is essentially to enqueue an DLM lock
2279                                 * in advance, so we don't care about the
2280                                 * result of AGL enqueue.
2281                                 */
2282                                 aa->oa_lvb = NULL;
2283                                 aa->oa_flags = NULL;
2284                         }
2285
2286                         req->rq_interpret_reply =
2287                                 (ptlrpc_interpterer_t)osc_enqueue_interpret;
2288                         if (rqset == PTLRPCD_SET)
2289                                 ptlrpcd_add_req(req);
2290                         else
2291                                 ptlrpc_set_add_req(rqset, req);
2292                 } else if (intent) {
2293                         ptlrpc_req_finished(req);
2294                 }
2295                 return rc;
2296         }
2297
2298         rc = osc_enqueue_fini(req, upcall, cookie, &lockh, einfo->ei_mode,
2299                               flags, agl, rc);
2300         if (intent)
2301                 ptlrpc_req_finished(req);
2302
2303         return rc;
2304 }
2305
2306 int osc_match_base(struct obd_export *exp, struct ldlm_res_id *res_id,
2307                    __u32 type, ldlm_policy_data_t *policy, __u32 mode,
2308                    __u64 *flags, void *data, struct lustre_handle *lockh,
2309                    int unref)
2310 {
2311         struct obd_device *obd = exp->exp_obd;
2312         __u64 lflags = *flags;
2313         enum ldlm_mode rc;
2314
2315         if (OBD_FAIL_CHECK(OBD_FAIL_OSC_MATCH))
2316                 return -EIO;
2317
2318         /* Filesystem lock extents are extended to page boundaries so that
2319          * dealing with the page cache is a little smoother
2320          */
2321         policy->l_extent.start -= policy->l_extent.start & ~PAGE_MASK;
2322         policy->l_extent.end |= ~PAGE_MASK;
2323
2324         /* Next, search for already existing extent locks that will cover us */
2325         /* If we're trying to read, we also search for an existing PW lock.  The
2326          * VFS and page cache already protect us locally, so lots of readers/
2327          * writers can share a single PW lock.
2328          */
2329         rc = mode;
2330         if (mode == LCK_PR)
2331                 rc |= LCK_PW;
2332         rc = ldlm_lock_match(obd->obd_namespace, lflags,
2333                              res_id, type, policy, rc, lockh, unref);
2334         if (rc) {
2335                 if (data) {
2336                         if (!osc_set_data_with_check(lockh, data)) {
2337                                 if (!(lflags & LDLM_FL_TEST_LOCK))
2338                                         ldlm_lock_decref(lockh, rc);
2339                                 return 0;
2340                         }
2341                 }
2342                 if (!(lflags & LDLM_FL_TEST_LOCK) && mode != rc) {
2343                         ldlm_lock_addref(lockh, LCK_PR);
2344                         ldlm_lock_decref(lockh, LCK_PW);
2345                 }
2346                 return rc;
2347         }
2348         return rc;
2349 }
2350
2351 int osc_cancel_base(struct lustre_handle *lockh, __u32 mode)
2352 {
2353         if (unlikely(mode == LCK_GROUP))
2354                 ldlm_lock_decref_and_cancel(lockh, mode);
2355         else
2356                 ldlm_lock_decref(lockh, mode);
2357
2358         return 0;
2359 }
2360
2361 static int osc_statfs_interpret(const struct lu_env *env,
2362                                 struct ptlrpc_request *req,
2363                                 struct osc_async_args *aa, int rc)
2364 {
2365         struct obd_statfs *msfs;
2366
2367         if (rc == -EBADR)
2368                 /* The request has in fact never been sent
2369                  * due to issues at a higher level (LOV).
2370                  * Exit immediately since the caller is
2371                  * aware of the problem and takes care
2372                  * of the clean up
2373                  */
2374                 return rc;
2375
2376         if ((rc == -ENOTCONN || rc == -EAGAIN) &&
2377             (aa->aa_oi->oi_flags & OBD_STATFS_NODELAY)) {
2378                 rc = 0;
2379                 goto out;
2380         }
2381
2382         if (rc != 0)
2383                 goto out;
2384
2385         msfs = req_capsule_server_get(&req->rq_pill, &RMF_OBD_STATFS);
2386         if (!msfs) {
2387                 rc = -EPROTO;
2388                 goto out;
2389         }
2390
2391         *aa->aa_oi->oi_osfs = *msfs;
2392 out:
2393         rc = aa->aa_oi->oi_cb_up(aa->aa_oi, rc);
2394         return rc;
2395 }
2396
2397 static int osc_statfs_async(struct obd_export *exp,
2398                             struct obd_info *oinfo, __u64 max_age,
2399                             struct ptlrpc_request_set *rqset)
2400 {
2401         struct obd_device *obd = class_exp2obd(exp);
2402         struct ptlrpc_request *req;
2403         struct osc_async_args *aa;
2404         int rc;
2405
2406         /* We could possibly pass max_age in the request (as an absolute
2407          * timestamp or a "seconds.usec ago") so the target can avoid doing
2408          * extra calls into the filesystem if that isn't necessary (e.g.
2409          * during mount that would help a bit).  Having relative timestamps
2410          * is not so great if request processing is slow, while absolute
2411          * timestamps are not ideal because they need time synchronization.
2412          */
2413         req = ptlrpc_request_alloc(obd->u.cli.cl_import, &RQF_OST_STATFS);
2414         if (!req)
2415                 return -ENOMEM;
2416
2417         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_STATFS);
2418         if (rc) {
2419                 ptlrpc_request_free(req);
2420                 return rc;
2421         }
2422         ptlrpc_request_set_replen(req);
2423         req->rq_request_portal = OST_CREATE_PORTAL;
2424         ptlrpc_at_set_req_timeout(req);
2425
2426         if (oinfo->oi_flags & OBD_STATFS_NODELAY) {
2427                 /* procfs requests not want stat in wait for avoid deadlock */
2428                 req->rq_no_resend = 1;
2429                 req->rq_no_delay = 1;
2430         }
2431
2432         req->rq_interpret_reply = (ptlrpc_interpterer_t)osc_statfs_interpret;
2433         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
2434         aa = ptlrpc_req_async_args(req);
2435         aa->aa_oi = oinfo;
2436
2437         ptlrpc_set_add_req(rqset, req);
2438         return 0;
2439 }
2440
2441 static int osc_statfs(const struct lu_env *env, struct obd_export *exp,
2442                       struct obd_statfs *osfs, __u64 max_age, __u32 flags)
2443 {
2444         struct obd_device *obd = class_exp2obd(exp);
2445         struct obd_statfs *msfs;
2446         struct ptlrpc_request *req;
2447         struct obd_import *imp = NULL;
2448         int rc;
2449
2450         /* Since the request might also come from lprocfs, so we need
2451          * sync this with client_disconnect_export Bug15684
2452          */
2453         down_read(&obd->u.cli.cl_sem);
2454         if (obd->u.cli.cl_import)
2455                 imp = class_import_get(obd->u.cli.cl_import);
2456         up_read(&obd->u.cli.cl_sem);
2457         if (!imp)
2458                 return -ENODEV;
2459
2460         /* We could possibly pass max_age in the request (as an absolute
2461          * timestamp or a "seconds.usec ago") so the target can avoid doing
2462          * extra calls into the filesystem if that isn't necessary (e.g.
2463          * during mount that would help a bit).  Having relative timestamps
2464          * is not so great if request processing is slow, while absolute
2465          * timestamps are not ideal because they need time synchronization.
2466          */
2467         req = ptlrpc_request_alloc(imp, &RQF_OST_STATFS);
2468
2469         class_import_put(imp);
2470
2471         if (!req)
2472                 return -ENOMEM;
2473
2474         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_STATFS);
2475         if (rc) {
2476                 ptlrpc_request_free(req);
2477                 return rc;
2478         }
2479         ptlrpc_request_set_replen(req);
2480         req->rq_request_portal = OST_CREATE_PORTAL;
2481         ptlrpc_at_set_req_timeout(req);
2482
2483         if (flags & OBD_STATFS_NODELAY) {
2484                 /* procfs requests not want stat in wait for avoid deadlock */
2485                 req->rq_no_resend = 1;
2486                 req->rq_no_delay = 1;
2487         }
2488
2489         rc = ptlrpc_queue_wait(req);
2490         if (rc)
2491                 goto out;
2492
2493         msfs = req_capsule_server_get(&req->rq_pill, &RMF_OBD_STATFS);
2494         if (!msfs) {
2495                 rc = -EPROTO;
2496                 goto out;
2497         }
2498
2499         *osfs = *msfs;
2500
2501  out:
2502         ptlrpc_req_finished(req);
2503         return rc;
2504 }
2505
2506 static int osc_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
2507                          void *karg, void __user *uarg)
2508 {
2509         struct obd_device *obd = exp->exp_obd;
2510         struct obd_ioctl_data *data = karg;
2511         int err = 0;
2512
2513         if (!try_module_get(THIS_MODULE)) {
2514                 CERROR("%s: cannot get module '%s'\n", obd->obd_name,
2515                        module_name(THIS_MODULE));
2516                 return -EINVAL;
2517         }
2518         switch (cmd) {
2519         case OBD_IOC_CLIENT_RECOVER:
2520                 err = ptlrpc_recover_import(obd->u.cli.cl_import,
2521                                             data->ioc_inlbuf1, 0);
2522                 if (err > 0)
2523                         err = 0;
2524                 goto out;
2525         case IOC_OSC_SET_ACTIVE:
2526                 err = ptlrpc_set_import_active(obd->u.cli.cl_import,
2527                                                data->ioc_offset);
2528                 goto out;
2529         case OBD_IOC_POLL_QUOTACHECK:
2530                 err = osc_quota_poll_check(exp, karg);
2531                 goto out;
2532         case OBD_IOC_PING_TARGET:
2533                 err = ptlrpc_obd_ping(obd);
2534                 goto out;
2535         default:
2536                 CDEBUG(D_INODE, "unrecognised ioctl %#x by %s\n",
2537                        cmd, current_comm());
2538                 err = -ENOTTY;
2539                 goto out;
2540         }
2541 out:
2542         module_put(THIS_MODULE);
2543         return err;
2544 }
2545
2546 static int osc_get_info(const struct lu_env *env, struct obd_export *exp,
2547                         u32 keylen, void *key, __u32 *vallen, void *val,
2548                         struct lov_stripe_md *lsm)
2549 {
2550         if (!vallen || !val)
2551                 return -EFAULT;
2552
2553         if (KEY_IS(KEY_FIEMAP)) {
2554                 struct ll_fiemap_info_key *fm_key = key;
2555                 struct ldlm_res_id res_id;
2556                 ldlm_policy_data_t policy;
2557                 struct lustre_handle lockh;
2558                 enum ldlm_mode mode = 0;
2559                 struct ptlrpc_request *req;
2560                 struct ll_user_fiemap *reply;
2561                 char *tmp;
2562                 int rc;
2563
2564                 if (!(fm_key->fiemap.fm_flags & FIEMAP_FLAG_SYNC))
2565                         goto skip_locking;
2566
2567                 policy.l_extent.start = fm_key->fiemap.fm_start &
2568                                                 PAGE_MASK;
2569
2570                 if (OBD_OBJECT_EOF - fm_key->fiemap.fm_length <=
2571                     fm_key->fiemap.fm_start + PAGE_SIZE - 1)
2572                         policy.l_extent.end = OBD_OBJECT_EOF;
2573                 else
2574                         policy.l_extent.end = (fm_key->fiemap.fm_start +
2575                                 fm_key->fiemap.fm_length +
2576                                 PAGE_SIZE - 1) & PAGE_MASK;
2577
2578                 ostid_build_res_name(&fm_key->oa.o_oi, &res_id);
2579                 mode = ldlm_lock_match(exp->exp_obd->obd_namespace,
2580                                        LDLM_FL_BLOCK_GRANTED |
2581                                        LDLM_FL_LVB_READY,
2582                                        &res_id, LDLM_EXTENT, &policy,
2583                                        LCK_PR | LCK_PW, &lockh, 0);
2584                 if (mode) { /* lock is cached on client */
2585                         if (mode != LCK_PR) {
2586                                 ldlm_lock_addref(&lockh, LCK_PR);
2587                                 ldlm_lock_decref(&lockh, LCK_PW);
2588                         }
2589                 } else { /* no cached lock, needs acquire lock on server side */
2590                         fm_key->oa.o_valid |= OBD_MD_FLFLAGS;
2591                         fm_key->oa.o_flags |= OBD_FL_SRVLOCK;
2592                 }
2593
2594 skip_locking:
2595                 req = ptlrpc_request_alloc(class_exp2cliimp(exp),
2596                                            &RQF_OST_GET_INFO_FIEMAP);
2597                 if (!req) {
2598                         rc = -ENOMEM;
2599                         goto drop_lock;
2600                 }
2601
2602                 req_capsule_set_size(&req->rq_pill, &RMF_FIEMAP_KEY,
2603                                      RCL_CLIENT, keylen);
2604                 req_capsule_set_size(&req->rq_pill, &RMF_FIEMAP_VAL,
2605                                      RCL_CLIENT, *vallen);
2606                 req_capsule_set_size(&req->rq_pill, &RMF_FIEMAP_VAL,
2607                                      RCL_SERVER, *vallen);
2608
2609                 rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_GET_INFO);
2610                 if (rc) {
2611                         ptlrpc_request_free(req);
2612                         goto drop_lock;
2613                 }
2614
2615                 tmp = req_capsule_client_get(&req->rq_pill, &RMF_FIEMAP_KEY);
2616                 memcpy(tmp, key, keylen);
2617                 tmp = req_capsule_client_get(&req->rq_pill, &RMF_FIEMAP_VAL);
2618                 memcpy(tmp, val, *vallen);
2619
2620                 ptlrpc_request_set_replen(req);
2621                 rc = ptlrpc_queue_wait(req);
2622                 if (rc)
2623                         goto fini_req;
2624
2625                 reply = req_capsule_server_get(&req->rq_pill, &RMF_FIEMAP_VAL);
2626                 if (!reply) {
2627                         rc = -EPROTO;
2628                         goto fini_req;
2629                 }
2630
2631                 memcpy(val, reply, *vallen);
2632 fini_req:
2633                 ptlrpc_req_finished(req);
2634 drop_lock:
2635                 if (mode)
2636                         ldlm_lock_decref(&lockh, LCK_PR);
2637                 return rc;
2638         }
2639
2640         return -EINVAL;
2641 }
2642
2643 static int osc_set_info_async(const struct lu_env *env, struct obd_export *exp,
2644                               u32 keylen, void *key, u32 vallen,
2645                               void *val, struct ptlrpc_request_set *set)
2646 {
2647         struct ptlrpc_request *req;
2648         struct obd_device *obd = exp->exp_obd;
2649         struct obd_import *imp = class_exp2cliimp(exp);
2650         char *tmp;
2651         int rc;
2652
2653         OBD_FAIL_TIMEOUT(OBD_FAIL_OSC_SHUTDOWN, 10);
2654
2655         if (KEY_IS(KEY_CHECKSUM)) {
2656                 if (vallen != sizeof(int))
2657                         return -EINVAL;
2658                 exp->exp_obd->u.cli.cl_checksum = (*(int *)val) ? 1 : 0;
2659                 return 0;
2660         }
2661
2662         if (KEY_IS(KEY_SPTLRPC_CONF)) {
2663                 sptlrpc_conf_client_adapt(obd);
2664                 return 0;
2665         }
2666
2667         if (KEY_IS(KEY_FLUSH_CTX)) {
2668                 sptlrpc_import_flush_my_ctx(imp);
2669                 return 0;
2670         }
2671
2672         if (KEY_IS(KEY_CACHE_SET)) {
2673                 struct client_obd *cli = &obd->u.cli;
2674
2675                 LASSERT(!cli->cl_cache); /* only once */
2676                 cli->cl_cache = val;
2677                 cl_cache_incref(cli->cl_cache);
2678                 cli->cl_lru_left = &cli->cl_cache->ccc_lru_left;
2679
2680                 /* add this osc into entity list */
2681                 LASSERT(list_empty(&cli->cl_lru_osc));
2682                 spin_lock(&cli->cl_cache->ccc_lru_lock);
2683                 list_add(&cli->cl_lru_osc, &cli->cl_cache->ccc_lru);
2684                 spin_unlock(&cli->cl_cache->ccc_lru_lock);
2685
2686                 return 0;
2687         }
2688
2689         if (KEY_IS(KEY_CACHE_LRU_SHRINK)) {
2690                 struct client_obd *cli = &obd->u.cli;
2691                 long nr = atomic_long_read(&cli->cl_lru_in_list) >> 1;
2692                 long target = *(long *)val;
2693
2694                 nr = osc_lru_shrink(env, cli, min(nr, target), true);
2695                 *(long *)val -= nr;
2696                 return 0;
2697         }
2698
2699         if (!set && !KEY_IS(KEY_GRANT_SHRINK))
2700                 return -EINVAL;
2701
2702         /* We pass all other commands directly to OST. Since nobody calls osc
2703          * methods directly and everybody is supposed to go through LOV, we
2704          * assume lov checked invalid values for us.
2705          * The only recognised values so far are evict_by_nid and mds_conn.
2706          * Even if something bad goes through, we'd get a -EINVAL from OST
2707          * anyway.
2708          */
2709
2710         req = ptlrpc_request_alloc(imp, KEY_IS(KEY_GRANT_SHRINK) ?
2711                                                 &RQF_OST_SET_GRANT_INFO :
2712                                                 &RQF_OBD_SET_INFO);
2713         if (!req)
2714                 return -ENOMEM;
2715
2716         req_capsule_set_size(&req->rq_pill, &RMF_SETINFO_KEY,
2717                              RCL_CLIENT, keylen);
2718         if (!KEY_IS(KEY_GRANT_SHRINK))
2719                 req_capsule_set_size(&req->rq_pill, &RMF_SETINFO_VAL,
2720                                      RCL_CLIENT, vallen);
2721         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_SET_INFO);
2722         if (rc) {
2723                 ptlrpc_request_free(req);
2724                 return rc;
2725         }
2726
2727         tmp = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_KEY);
2728         memcpy(tmp, key, keylen);
2729         tmp = req_capsule_client_get(&req->rq_pill, KEY_IS(KEY_GRANT_SHRINK) ?
2730                                                         &RMF_OST_BODY :
2731                                                         &RMF_SETINFO_VAL);
2732         memcpy(tmp, val, vallen);
2733
2734         if (KEY_IS(KEY_GRANT_SHRINK)) {
2735                 struct osc_brw_async_args *aa;
2736                 struct obdo *oa;
2737
2738                 CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
2739                 aa = ptlrpc_req_async_args(req);
2740                 oa = kmem_cache_zalloc(obdo_cachep, GFP_NOFS);
2741                 if (!oa) {
2742                         ptlrpc_req_finished(req);
2743                         return -ENOMEM;
2744                 }
2745                 *oa = ((struct ost_body *)val)->oa;
2746                 aa->aa_oa = oa;
2747                 req->rq_interpret_reply = osc_shrink_grant_interpret;
2748         }
2749
2750         ptlrpc_request_set_replen(req);
2751         if (!KEY_IS(KEY_GRANT_SHRINK)) {
2752                 LASSERT(set);
2753                 ptlrpc_set_add_req(set, req);
2754                 ptlrpc_check_set(NULL, set);
2755         } else {
2756                 ptlrpcd_add_req(req);
2757         }
2758
2759         return 0;
2760 }
2761
2762 static int osc_reconnect(const struct lu_env *env,
2763                          struct obd_export *exp, struct obd_device *obd,
2764                          struct obd_uuid *cluuid,
2765                          struct obd_connect_data *data,
2766                          void *localdata)
2767 {
2768         struct client_obd *cli = &obd->u.cli;
2769
2770         if (data && (data->ocd_connect_flags & OBD_CONNECT_GRANT)) {
2771                 long lost_grant;
2772
2773                 spin_lock(&cli->cl_loi_list_lock);
2774                 data->ocd_grant = (cli->cl_avail_grant +
2775                                    (cli->cl_dirty_pages << PAGE_SHIFT)) ?:
2776                                    2 * cli_brw_size(obd);
2777                 lost_grant = cli->cl_lost_grant;
2778                 cli->cl_lost_grant = 0;
2779                 spin_unlock(&cli->cl_loi_list_lock);
2780
2781                 CDEBUG(D_RPCTRACE, "ocd_connect_flags: %#llx ocd_version: %d ocd_grant: %d, lost: %ld.\n",
2782                        data->ocd_connect_flags,
2783                        data->ocd_version, data->ocd_grant, lost_grant);
2784         }
2785
2786         return 0;
2787 }
2788
2789 static int osc_disconnect(struct obd_export *exp)
2790 {
2791         struct obd_device *obd = class_exp2obd(exp);
2792         int rc;
2793
2794         rc = client_disconnect_export(exp);
2795         /**
2796          * Initially we put del_shrink_grant before disconnect_export, but it
2797          * causes the following problem if setup (connect) and cleanup
2798          * (disconnect) are tangled together.
2799          *      connect p1                   disconnect p2
2800          *   ptlrpc_connect_import
2801          *     ...............         class_manual_cleanup
2802          *                                   osc_disconnect
2803          *                                   del_shrink_grant
2804          *   ptlrpc_connect_interrupt
2805          *     init_grant_shrink
2806          *   add this client to shrink list
2807          *                                    cleanup_osc
2808          * Bang! pinger trigger the shrink.
2809          * So the osc should be disconnected from the shrink list, after we
2810          * are sure the import has been destroyed. BUG18662
2811          */
2812         if (!obd->u.cli.cl_import)
2813                 osc_del_shrink_grant(&obd->u.cli);
2814         return rc;
2815 }
2816
2817 static int osc_import_event(struct obd_device *obd,
2818                             struct obd_import *imp,
2819                             enum obd_import_event event)
2820 {
2821         struct client_obd *cli;
2822         int rc = 0;
2823
2824         LASSERT(imp->imp_obd == obd);
2825
2826         switch (event) {
2827         case IMP_EVENT_DISCON: {
2828                 cli = &obd->u.cli;
2829                 spin_lock(&cli->cl_loi_list_lock);
2830                 cli->cl_avail_grant = 0;
2831                 cli->cl_lost_grant = 0;
2832                 spin_unlock(&cli->cl_loi_list_lock);
2833                 break;
2834         }
2835         case IMP_EVENT_INACTIVE: {
2836                 rc = obd_notify_observer(obd, obd, OBD_NOTIFY_INACTIVE, NULL);
2837                 break;
2838         }
2839         case IMP_EVENT_INVALIDATE: {
2840                 struct ldlm_namespace *ns = obd->obd_namespace;
2841                 struct lu_env *env;
2842                 int refcheck;
2843
2844                 env = cl_env_get(&refcheck);
2845                 if (!IS_ERR(env)) {
2846                         /* Reset grants */
2847                         cli = &obd->u.cli;
2848                         /* all pages go to failing rpcs due to the invalid
2849                          * import
2850                          */
2851                         osc_io_unplug(env, cli, NULL);
2852
2853                         ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
2854                         cl_env_put(env, &refcheck);
2855                 } else {
2856                         rc = PTR_ERR(env);
2857                 }
2858                 break;
2859         }
2860         case IMP_EVENT_ACTIVE: {
2861                 rc = obd_notify_observer(obd, obd, OBD_NOTIFY_ACTIVE, NULL);
2862                 break;
2863         }
2864         case IMP_EVENT_OCD: {
2865                 struct obd_connect_data *ocd = &imp->imp_connect_data;
2866
2867                 if (ocd->ocd_connect_flags & OBD_CONNECT_GRANT)
2868                         osc_init_grant(&obd->u.cli, ocd);
2869
2870                 /* See bug 7198 */
2871                 if (ocd->ocd_connect_flags & OBD_CONNECT_REQPORTAL)
2872                         imp->imp_client->cli_request_portal = OST_REQUEST_PORTAL;
2873
2874                 rc = obd_notify_observer(obd, obd, OBD_NOTIFY_OCD, NULL);
2875                 break;
2876         }
2877         case IMP_EVENT_DEACTIVATE: {
2878                 rc = obd_notify_observer(obd, obd, OBD_NOTIFY_DEACTIVATE, NULL);
2879                 break;
2880         }
2881         case IMP_EVENT_ACTIVATE: {
2882                 rc = obd_notify_observer(obd, obd, OBD_NOTIFY_ACTIVATE, NULL);
2883                 break;
2884         }
2885         default:
2886                 CERROR("Unknown import event %d\n", event);
2887                 LBUG();
2888         }
2889         return rc;
2890 }
2891
2892 /**
2893  * Determine whether the lock can be canceled before replaying the lock
2894  * during recovery, see bug16774 for detailed information.
2895  *
2896  * \retval zero the lock can't be canceled
2897  * \retval other ok to cancel
2898  */
2899 static int osc_cancel_weight(struct ldlm_lock *lock)
2900 {
2901         /*
2902          * Cancel all unused and granted extent lock.
2903          */
2904         if (lock->l_resource->lr_type == LDLM_EXTENT &&
2905             lock->l_granted_mode == lock->l_req_mode &&
2906             osc_ldlm_weigh_ast(lock) == 0)
2907                 return 1;
2908
2909         return 0;
2910 }
2911
2912 static int brw_queue_work(const struct lu_env *env, void *data)
2913 {
2914         struct client_obd *cli = data;
2915
2916         CDEBUG(D_CACHE, "Run writeback work for client obd %p.\n", cli);
2917
2918         osc_io_unplug(env, cli, NULL);
2919         return 0;
2920 }
2921
2922 int osc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
2923 {
2924         struct lprocfs_static_vars lvars = { NULL };
2925         struct client_obd *cli = &obd->u.cli;
2926         void *handler;
2927         int rc;
2928         int adding;
2929         int added;
2930         int req_count;
2931
2932         rc = ptlrpcd_addref();
2933         if (rc)
2934                 return rc;
2935
2936         rc = client_obd_setup(obd, lcfg);
2937         if (rc)
2938                 goto out_ptlrpcd;
2939
2940         handler = ptlrpcd_alloc_work(cli->cl_import, brw_queue_work, cli);
2941         if (IS_ERR(handler)) {
2942                 rc = PTR_ERR(handler);
2943                 goto out_client_setup;
2944         }
2945         cli->cl_writeback_work = handler;
2946
2947         handler = ptlrpcd_alloc_work(cli->cl_import, lru_queue_work, cli);
2948         if (IS_ERR(handler)) {
2949                 rc = PTR_ERR(handler);
2950                 goto out_ptlrpcd_work;
2951         }
2952
2953         cli->cl_lru_work = handler;
2954
2955         rc = osc_quota_setup(obd);
2956         if (rc)
2957                 goto out_ptlrpcd_work;
2958
2959         cli->cl_grant_shrink_interval = GRANT_SHRINK_INTERVAL;
2960         lprocfs_osc_init_vars(&lvars);
2961         if (lprocfs_obd_setup(obd, lvars.obd_vars, lvars.sysfs_vars) == 0) {
2962                 lproc_osc_attach_seqstat(obd);
2963                 sptlrpc_lprocfs_cliobd_attach(obd);
2964                 ptlrpc_lprocfs_register_obd(obd);
2965         }
2966
2967         /*
2968          * We try to control the total number of requests with a upper limit
2969          * osc_reqpool_maxreqcount. There might be some race which will cause
2970          * over-limit allocation, but it is fine.
2971          */
2972         req_count = atomic_read(&osc_pool_req_count);
2973         if (req_count < osc_reqpool_maxreqcount) {
2974                 adding = cli->cl_max_rpcs_in_flight + 2;
2975                 if (req_count + adding > osc_reqpool_maxreqcount)
2976                         adding = osc_reqpool_maxreqcount - req_count;
2977
2978                 added = ptlrpc_add_rqs_to_pool(osc_rq_pool, adding);
2979                 atomic_add(added, &osc_pool_req_count);
2980         }
2981
2982         INIT_LIST_HEAD(&cli->cl_grant_shrink_list);
2983         ns_register_cancel(obd->obd_namespace, osc_cancel_weight);
2984         return rc;
2985
2986 out_ptlrpcd_work:
2987         if (cli->cl_writeback_work) {
2988                 ptlrpcd_destroy_work(cli->cl_writeback_work);
2989                 cli->cl_writeback_work = NULL;
2990         }
2991         if (cli->cl_lru_work) {
2992                 ptlrpcd_destroy_work(cli->cl_lru_work);
2993                 cli->cl_lru_work = NULL;
2994         }
2995 out_client_setup:
2996         client_obd_cleanup(obd);
2997 out_ptlrpcd:
2998         ptlrpcd_decref();
2999         return rc;
3000 }
3001
3002 static int osc_precleanup(struct obd_device *obd, enum obd_cleanup_stage stage)
3003 {
3004         switch (stage) {
3005         case OBD_CLEANUP_EARLY: {
3006                 struct obd_import *imp;
3007
3008                 imp = obd->u.cli.cl_import;
3009                 CDEBUG(D_HA, "Deactivating import %s\n", obd->obd_name);
3010                 /* ptlrpc_abort_inflight to stop an mds_lov_synchronize */
3011                 ptlrpc_deactivate_import(imp);
3012                 spin_lock(&imp->imp_lock);
3013                 imp->imp_pingable = 0;
3014                 spin_unlock(&imp->imp_lock);
3015                 break;
3016         }
3017         case OBD_CLEANUP_EXPORTS: {
3018                 struct client_obd *cli = &obd->u.cli;
3019                 /* LU-464
3020                  * for echo client, export may be on zombie list, wait for
3021                  * zombie thread to cull it, because cli.cl_import will be
3022                  * cleared in client_disconnect_export():
3023                  *   class_export_destroy() -> obd_cleanup() ->
3024                  *   echo_device_free() -> echo_client_cleanup() ->
3025                  *   obd_disconnect() -> osc_disconnect() ->
3026                  *   client_disconnect_export()
3027                  */
3028                 obd_zombie_barrier();
3029                 if (cli->cl_writeback_work) {
3030                         ptlrpcd_destroy_work(cli->cl_writeback_work);
3031                         cli->cl_writeback_work = NULL;
3032                 }
3033                 if (cli->cl_lru_work) {
3034                         ptlrpcd_destroy_work(cli->cl_lru_work);
3035                         cli->cl_lru_work = NULL;
3036                 }
3037                 obd_cleanup_client_import(obd);
3038                 ptlrpc_lprocfs_unregister_obd(obd);
3039                 lprocfs_obd_cleanup(obd);
3040                 break;
3041                 }
3042         }
3043         return 0;
3044 }
3045
3046 static int osc_cleanup(struct obd_device *obd)
3047 {
3048         struct client_obd *cli = &obd->u.cli;
3049         int rc;
3050
3051         /* lru cleanup */
3052         if (cli->cl_cache) {
3053                 LASSERT(atomic_read(&cli->cl_cache->ccc_users) > 0);
3054                 spin_lock(&cli->cl_cache->ccc_lru_lock);
3055                 list_del_init(&cli->cl_lru_osc);
3056                 spin_unlock(&cli->cl_cache->ccc_lru_lock);
3057                 cli->cl_lru_left = NULL;
3058                 cl_cache_decref(cli->cl_cache);
3059                 cli->cl_cache = NULL;
3060         }
3061
3062         /* free memory of osc quota cache */
3063         osc_quota_cleanup(obd);
3064
3065         rc = client_obd_cleanup(obd);
3066
3067         ptlrpcd_decref();
3068         return rc;
3069 }
3070
3071 int osc_process_config_base(struct obd_device *obd, struct lustre_cfg *lcfg)
3072 {
3073         struct lprocfs_static_vars lvars = { NULL };
3074         int rc = 0;
3075
3076         lprocfs_osc_init_vars(&lvars);
3077
3078         switch (lcfg->lcfg_command) {
3079         default:
3080                 rc = class_process_proc_param(PARAM_OSC, lvars.obd_vars,
3081                                               lcfg, obd);
3082                 if (rc > 0)
3083                         rc = 0;
3084                 break;
3085         }
3086
3087         return rc;
3088 }
3089
3090 static int osc_process_config(struct obd_device *obd, u32 len, void *buf)
3091 {
3092         return osc_process_config_base(obd, buf);
3093 }
3094
3095 static struct obd_ops osc_obd_ops = {
3096         .owner          = THIS_MODULE,
3097         .setup          = osc_setup,
3098         .precleanup     = osc_precleanup,
3099         .cleanup        = osc_cleanup,
3100         .add_conn       = client_import_add_conn,
3101         .del_conn       = client_import_del_conn,
3102         .connect        = client_connect_import,
3103         .reconnect      = osc_reconnect,
3104         .disconnect     = osc_disconnect,
3105         .statfs         = osc_statfs,
3106         .statfs_async   = osc_statfs_async,
3107         .unpackmd       = osc_unpackmd,
3108         .create         = osc_create,
3109         .destroy        = osc_destroy,
3110         .getattr        = osc_getattr,
3111         .getattr_async  = osc_getattr_async,
3112         .setattr        = osc_setattr,
3113         .setattr_async  = osc_setattr_async,
3114         .iocontrol      = osc_iocontrol,
3115         .get_info       = osc_get_info,
3116         .set_info_async = osc_set_info_async,
3117         .import_event   = osc_import_event,
3118         .process_config = osc_process_config,
3119         .quotactl       = osc_quotactl,
3120         .quotacheck     = osc_quotacheck,
3121 };
3122
3123 extern struct lu_kmem_descr osc_caches[];
3124 extern struct lock_class_key osc_ast_guard_class;
3125
3126 static int __init osc_init(void)
3127 {
3128         struct lprocfs_static_vars lvars = { NULL };
3129         unsigned int reqpool_size;
3130         unsigned int reqsize;
3131         int rc;
3132
3133         /* print an address of _any_ initialized kernel symbol from this
3134          * module, to allow debugging with gdb that doesn't support data
3135          * symbols from modules.
3136          */
3137         CDEBUG(D_INFO, "Lustre OSC module (%p).\n", &osc_caches);
3138
3139         rc = lu_kmem_init(osc_caches);
3140         if (rc)
3141                 return rc;
3142
3143         lprocfs_osc_init_vars(&lvars);
3144
3145         rc = class_register_type(&osc_obd_ops, NULL,
3146                                  LUSTRE_OSC_NAME, &osc_device_type);
3147         if (rc)
3148                 goto out_kmem;
3149
3150         /* This is obviously too much memory, only prevent overflow here */
3151         if (osc_reqpool_mem_max >= 1 << 12 || osc_reqpool_mem_max == 0) {
3152                 rc = -EINVAL;
3153                 goto out_type;
3154         }
3155
3156         reqpool_size = osc_reqpool_mem_max << 20;
3157
3158         reqsize = 1;
3159         while (reqsize < OST_MAXREQSIZE)
3160                 reqsize = reqsize << 1;
3161
3162         /*
3163          * We don't enlarge the request count in OSC pool according to
3164          * cl_max_rpcs_in_flight. The allocation from the pool will only be
3165          * tried after normal allocation failed. So a small OSC pool won't
3166          * cause much performance degression in most of cases.
3167          */
3168         osc_reqpool_maxreqcount = reqpool_size / reqsize;
3169
3170         atomic_set(&osc_pool_req_count, 0);
3171         osc_rq_pool = ptlrpc_init_rq_pool(0, OST_MAXREQSIZE,
3172                                           ptlrpc_add_rqs_to_pool);
3173
3174         if (osc_rq_pool)
3175                 return 0;
3176
3177         rc = -ENOMEM;
3178
3179 out_type:
3180         class_unregister_type(LUSTRE_OSC_NAME);
3181 out_kmem:
3182         lu_kmem_fini(osc_caches);
3183         return rc;
3184 }
3185
3186 static void /*__exit*/ osc_exit(void)
3187 {
3188         class_unregister_type(LUSTRE_OSC_NAME);
3189         lu_kmem_fini(osc_caches);
3190         ptlrpc_free_rq_pool(osc_rq_pool);
3191 }
3192
3193 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
3194 MODULE_DESCRIPTION("Lustre Object Storage Client (OSC)");
3195 MODULE_LICENSE("GPL");
3196 MODULE_VERSION(LUSTRE_VERSION_STRING);
3197
3198 module_init(osc_init);
3199 module_exit(osc_exit);