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