Whamcloud - gitweb
4c1b930f0227e52e61a5571c93dc7a866c8faf11
[fs/lustre-release.git] / lustre / target / tgt_handler.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, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 021110-1307, USA
20  *
21  * GPL HEADER END
22  */
23 /*
24  * Copyright (c) 2013, 2017, Intel Corporation.
25  */
26 /*
27  * lustre/target/tgt_handler.c
28  *
29  * Lustre Unified Target request handler code
30  *
31  * Author: Brian Behlendorf <behlendorf1@llnl.gov>
32  * Author: Mikhail Pershin <mike.pershin@intel.com>
33  */
34
35 #define DEBUG_SUBSYSTEM S_CLASS
36
37 #include <linux/user_namespace.h>
38 #ifdef HAVE_UIDGID_HEADER
39 # include <linux/uidgid.h>
40 #endif
41
42 #include <obd.h>
43 #include <obd_class.h>
44 #include <obd_cksum.h>
45 #include <lustre_lfsck.h>
46 #include <lustre_nodemap.h>
47 #include <lustre_acl.h>
48
49 #include "tgt_internal.h"
50
51 char *tgt_name(struct lu_target *tgt)
52 {
53         LASSERT(tgt->lut_obd != NULL);
54         return tgt->lut_obd->obd_name;
55 }
56 EXPORT_SYMBOL(tgt_name);
57
58 /*
59  * Generic code handling requests that have struct mdt_body passed in:
60  *
61  *  - extract mdt_body from request and save it in @tsi, if present;
62  *
63  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
64  *  @tsi;
65  *
66  *  - if HABEO_CORPUS flag is set for this request type check whether object
67  *  actually exists on storage (lu_object_exists()).
68  *
69  */
70 static int tgt_mdt_body_unpack(struct tgt_session_info *tsi, __u32 flags)
71 {
72         const struct mdt_body   *body;
73         struct lu_object        *obj;
74         struct req_capsule      *pill = tsi->tsi_pill;
75         int                      rc;
76
77         ENTRY;
78
79         body = req_capsule_client_get(pill, &RMF_MDT_BODY);
80         if (body == NULL)
81                 RETURN(-EFAULT);
82
83         tsi->tsi_mdt_body = body;
84
85         if (!(body->mbo_valid & OBD_MD_FLID))
86                 RETURN(0);
87
88         /* mdc_pack_body() doesn't check if fid is zero and set OBD_ML_FID
89          * in any case in pre-2.5 clients. Fix that here if needed */
90         if (unlikely(fid_is_zero(&body->mbo_fid1)))
91                 RETURN(0);
92
93         if (!fid_is_sane(&body->mbo_fid1)) {
94                 CERROR("%s: invalid FID: "DFID"\n", tgt_name(tsi->tsi_tgt),
95                        PFID(&body->mbo_fid1));
96                 RETURN(-EINVAL);
97         }
98
99         obj = lu_object_find(tsi->tsi_env,
100                              &tsi->tsi_tgt->lut_bottom->dd_lu_dev,
101                              &body->mbo_fid1, NULL);
102         if (!IS_ERR(obj)) {
103                 if ((flags & HABEO_CORPUS) && !lu_object_exists(obj)) {
104                         lu_object_put(tsi->tsi_env, obj);
105                         rc = -ENOENT;
106                 } else {
107                         tsi->tsi_corpus = obj;
108                         rc = 0;
109                 }
110         } else {
111                 rc = PTR_ERR(obj);
112         }
113
114         tsi->tsi_fid = body->mbo_fid1;
115
116         RETURN(rc);
117 }
118
119 /**
120  * Validate oa from client.
121  * If the request comes from 2.0 clients, currently only RSVD seq and IDIF
122  * req are valid.
123  *    a. objects in Single MDT FS  seq = FID_SEQ_OST_MDT0, oi_id != 0
124  *    b. Echo objects(seq = 2), old echo client still use oi_id/oi_seq to
125  *       pack ost_id. Because non-zero oi_seq will make it diffcult to tell
126  *       whether this is oi_fid or real ostid. So it will check
127  *       OBD_CONNECT_FID, then convert the ostid to FID for old client.
128  *    c. Old FID-disable osc will send IDIF.
129  *    d. new FID-enable osc/osp will send normal FID.
130  *
131  * And also oi_id/f_oid should always start from 1. oi_id/f_oid = 0 will
132  * be used for LAST_ID file, and only being accessed inside OST now.
133  */
134 int tgt_validate_obdo(struct tgt_session_info *tsi, struct obdo *oa)
135 {
136         struct ost_id   *oi     = &oa->o_oi;
137         u64              seq    = ostid_seq(oi);
138         u64              id     = ostid_id(oi);
139         int              rc;
140         ENTRY;
141
142         if (unlikely(!(exp_connect_flags(tsi->tsi_exp) & OBD_CONNECT_FID) &&
143                      fid_seq_is_echo(seq))) {
144                 /* Sigh 2.[123] client still sends echo req with oi_id = 0
145                  * during create, and we will reset this to 1, since this
146                  * oi_id is basically useless in the following create process,
147                  * but oi_id == 0 will make it difficult to tell whether it is
148                  * real FID or ost_id. */
149                 oi->oi_fid.f_seq = FID_SEQ_ECHO;
150                 oi->oi_fid.f_oid = id ?: 1;
151                 oi->oi_fid.f_ver = 0;
152         } else {
153                 struct tgt_thread_info *tti = tgt_th_info(tsi->tsi_env);
154
155                 if (unlikely((oa->o_valid & OBD_MD_FLID) && id == 0))
156                         GOTO(out, rc = -EPROTO);
157
158                 /* Note: this check might be forced in 2.5 or 2.6, i.e.
159                  * all of the requests are required to setup FLGROUP */
160                 if (unlikely(!(oa->o_valid & OBD_MD_FLGROUP))) {
161                         ostid_set_seq_mdt0(oi);
162                         oa->o_valid |= OBD_MD_FLGROUP;
163                         seq = ostid_seq(oi);
164                 }
165
166                 if (unlikely(!(fid_seq_is_idif(seq) || fid_seq_is_mdt0(seq) ||
167                                fid_seq_is_norm(seq) || fid_seq_is_echo(seq))))
168                         GOTO(out, rc = -EPROTO);
169
170                 rc = ostid_to_fid(&tti->tti_fid1, oi,
171                                   tsi->tsi_tgt->lut_lsd.lsd_osd_index);
172                 if (unlikely(rc != 0))
173                         GOTO(out, rc);
174
175                 oi->oi_fid = tti->tti_fid1;
176         }
177
178         RETURN(0);
179
180 out:
181         CERROR("%s: client %s sent bad object "DOSTID": rc = %d\n",
182                tgt_name(tsi->tsi_tgt), obd_export_nid2str(tsi->tsi_exp),
183                seq, id, rc);
184         return rc;
185 }
186 EXPORT_SYMBOL(tgt_validate_obdo);
187
188 static int tgt_io_data_unpack(struct tgt_session_info *tsi, struct ost_id *oi)
189 {
190         unsigned                 max_brw;
191         struct niobuf_remote    *rnb;
192         struct obd_ioobj        *ioo;
193         int                      obj_count;
194
195         ENTRY;
196
197         ioo = req_capsule_client_get(tsi->tsi_pill, &RMF_OBD_IOOBJ);
198         if (ioo == NULL)
199                 RETURN(-EPROTO);
200
201         rnb = req_capsule_client_get(tsi->tsi_pill, &RMF_NIOBUF_REMOTE);
202         if (rnb == NULL)
203                 RETURN(-EPROTO);
204
205         max_brw = ioobj_max_brw_get(ioo);
206         if (unlikely((max_brw & (max_brw - 1)) != 0)) {
207                 CERROR("%s: client %s sent bad ioobj max %u for "DOSTID
208                        ": rc = %d\n", tgt_name(tsi->tsi_tgt),
209                        obd_export_nid2str(tsi->tsi_exp), max_brw,
210                        POSTID(oi), -EPROTO);
211                 RETURN(-EPROTO);
212         }
213         ioo->ioo_oid = *oi;
214
215         obj_count = req_capsule_get_size(tsi->tsi_pill, &RMF_OBD_IOOBJ,
216                                         RCL_CLIENT) / sizeof(*ioo);
217         if (obj_count == 0) {
218                 CERROR("%s: short ioobj\n", tgt_name(tsi->tsi_tgt));
219                 RETURN(-EPROTO);
220         } else if (obj_count > 1) {
221                 CERROR("%s: too many ioobjs (%d)\n", tgt_name(tsi->tsi_tgt),
222                        obj_count);
223                 RETURN(-EPROTO);
224         }
225
226         if (ioo->ioo_bufcnt == 0) {
227                 CERROR("%s: ioo has zero bufcnt\n", tgt_name(tsi->tsi_tgt));
228                 RETURN(-EPROTO);
229         }
230
231         if (ioo->ioo_bufcnt > PTLRPC_MAX_BRW_PAGES) {
232                 DEBUG_REQ(D_RPCTRACE, tgt_ses_req(tsi),
233                           "bulk has too many pages (%d)",
234                           ioo->ioo_bufcnt);
235                 RETURN(-EPROTO);
236         }
237
238         RETURN(0);
239 }
240
241 static int tgt_ost_body_unpack(struct tgt_session_info *tsi, __u32 flags)
242 {
243         struct ost_body         *body;
244         struct req_capsule      *pill = tsi->tsi_pill;
245         struct lu_nodemap       *nodemap;
246         int                      rc;
247
248         ENTRY;
249
250         body = req_capsule_client_get(pill, &RMF_OST_BODY);
251         if (body == NULL)
252                 RETURN(-EFAULT);
253
254         rc = tgt_validate_obdo(tsi, &body->oa);
255         if (rc)
256                 RETURN(rc);
257
258         nodemap = nodemap_get_from_exp(tsi->tsi_exp);
259         if (IS_ERR(nodemap))
260                 RETURN(PTR_ERR(nodemap));
261
262         body->oa.o_uid = nodemap_map_id(nodemap, NODEMAP_UID,
263                                         NODEMAP_CLIENT_TO_FS,
264                                         body->oa.o_uid);
265         body->oa.o_gid = nodemap_map_id(nodemap, NODEMAP_GID,
266                                         NODEMAP_CLIENT_TO_FS,
267                                         body->oa.o_gid);
268         nodemap_putref(nodemap);
269
270         tsi->tsi_ost_body = body;
271         tsi->tsi_fid = body->oa.o_oi.oi_fid;
272
273         if (req_capsule_has_field(pill, &RMF_OBD_IOOBJ, RCL_CLIENT)) {
274                 rc = tgt_io_data_unpack(tsi, &body->oa.o_oi);
275                 if (rc < 0)
276                         RETURN(rc);
277         }
278
279         if (!(body->oa.o_valid & OBD_MD_FLID)) {
280                 if (flags & HABEO_CORPUS) {
281                         CERROR("%s: OBD_MD_FLID flag is not set in ost_body "
282                                "but OID/FID is mandatory with HABEO_CORPUS\n",
283                                tgt_name(tsi->tsi_tgt));
284                         RETURN(-EPROTO);
285                 } else {
286                         RETURN(0);
287                 }
288         }
289
290         ost_fid_build_resid(&tsi->tsi_fid, &tsi->tsi_resid);
291
292         /*
293          * OST doesn't get object in advance for further use to prevent
294          * situations with nested object_find which is potential deadlock.
295          */
296         tsi->tsi_corpus = NULL;
297         RETURN(rc);
298 }
299
300 /*
301  * Do necessary preprocessing according to handler ->th_flags.
302  */
303 static int tgt_request_preprocess(struct tgt_session_info *tsi,
304                                   struct tgt_handler *h,
305                                   struct ptlrpc_request *req)
306 {
307         struct req_capsule      *pill = tsi->tsi_pill;
308         __u32                    flags = h->th_flags;
309         int                      rc = 0;
310
311         ENTRY;
312
313         if (tsi->tsi_preprocessed)
314                 RETURN(0);
315
316         LASSERT(h->th_act != NULL);
317         LASSERT(h->th_opc == lustre_msg_get_opc(req->rq_reqmsg));
318         LASSERT(current->journal_info == NULL);
319
320         LASSERT(ergo(flags & (HABEO_CORPUS | HABEO_REFERO),
321                      h->th_fmt != NULL));
322         if (h->th_fmt != NULL) {
323                 req_capsule_set(pill, h->th_fmt);
324                 if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT)) {
325                         rc = tgt_mdt_body_unpack(tsi, flags);
326                         if (rc < 0)
327                                 RETURN(rc);
328                 } else if (req_capsule_has_field(pill, &RMF_OST_BODY,
329                                                  RCL_CLIENT)) {
330                         rc = tgt_ost_body_unpack(tsi, flags);
331                         if (rc < 0)
332                                 RETURN(rc);
333                 }
334         }
335
336         if (flags & MUTABOR && tgt_conn_flags(tsi) & OBD_CONNECT_RDONLY)
337                 RETURN(-EROFS);
338
339         if (flags & HABEO_CLAVIS) {
340                 struct ldlm_request *dlm_req;
341
342                 LASSERT(h->th_fmt != NULL);
343
344                 dlm_req = req_capsule_client_get(pill, &RMF_DLM_REQ);
345                 if (dlm_req != NULL) {
346                         union ldlm_wire_policy_data *policy =
347                                         &dlm_req->lock_desc.l_policy_data;
348
349                         if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
350                                      LDLM_IBITS &&
351                                      (policy->l_inodebits.bits |
352                                       policy->l_inodebits.try_bits) == 0)) {
353                                 /*
354                                  * Lock without inodebits makes no sense and
355                                  * will oops later in ldlm. If client miss to
356                                  * set such bits, do not trigger ASSERTION.
357                                  *
358                                  * For liblustre flock case, it maybe zero.
359                                  */
360                                 rc = -EPROTO;
361                         } else {
362                                 tsi->tsi_dlm_req = dlm_req;
363                         }
364                 } else {
365                         rc = -EFAULT;
366                 }
367         }
368         tsi->tsi_preprocessed = 1;
369         RETURN(rc);
370 }
371
372 /*
373  * Invoke handler for this request opc. Also do necessary preprocessing
374  * (according to handler ->th_flags), and post-processing (setting of
375  * ->last_{xid,committed}).
376  */
377 static int tgt_handle_request0(struct tgt_session_info *tsi,
378                                struct tgt_handler *h,
379                                struct ptlrpc_request *req)
380 {
381         int      serious = 0;
382         int      rc;
383         __u32    opc = lustre_msg_get_opc(req->rq_reqmsg);
384
385         ENTRY;
386
387
388         /* When dealing with sec context requests, no export is associated yet,
389          * because these requests are sent before *_CONNECT requests.
390          * A NULL req->rq_export means the normal *_common_slice handlers will
391          * not be called, because there is no reference to the target.
392          * So deal with them by hand and jump directly to target_send_reply().
393          */
394         switch (opc) {
395         case SEC_CTX_INIT:
396         case SEC_CTX_INIT_CONT:
397         case SEC_CTX_FINI:
398                 CFS_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, cfs_fail_val);
399                 GOTO(out, rc = 0);
400         }
401
402         /*
403          * Checking for various OBD_FAIL_$PREF_$OPC_NET codes. _Do_ not try
404          * to put same checks into handlers like mdt_close(), mdt_reint(),
405          * etc., without talking to mdt authors first. Checking same thing
406          * there again is useless and returning 0 error without packing reply
407          * is buggy! Handlers either pack reply or return error.
408          *
409          * We return 0 here and do not send any reply in order to emulate
410          * network failure. Do not send any reply in case any of NET related
411          * fail_id has occured.
412          */
413         if (OBD_FAIL_CHECK_ORSET(h->th_fail_id, OBD_FAIL_ONCE))
414                 RETURN(0);
415         if (unlikely(lustre_msg_get_opc(req->rq_reqmsg) == MDS_REINT &&
416                      OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_MULTI_NET)))
417                 RETURN(0);
418
419         rc = tgt_request_preprocess(tsi, h, req);
420         /* pack reply if reply format is fixed */
421         if (rc == 0 && h->th_flags & HABEO_REFERO) {
422                 /* Pack reply */
423                 if (req_capsule_has_field(tsi->tsi_pill, &RMF_MDT_MD,
424                                           RCL_SERVER))
425                         req_capsule_set_size(tsi->tsi_pill, &RMF_MDT_MD,
426                                              RCL_SERVER,
427                                              tsi->tsi_mdt_body->mbo_eadatasize);
428                 if (req_capsule_has_field(tsi->tsi_pill, &RMF_LOGCOOKIES,
429                                           RCL_SERVER))
430                         req_capsule_set_size(tsi->tsi_pill, &RMF_LOGCOOKIES,
431                                              RCL_SERVER, 0);
432                 if (req_capsule_has_field(tsi->tsi_pill, &RMF_ACL, RCL_SERVER))
433                         req_capsule_set_size(tsi->tsi_pill,
434                                              &RMF_ACL, RCL_SERVER,
435                                              LUSTRE_POSIX_ACL_MAX_SIZE_OLD);
436
437                 if (req_capsule_has_field(tsi->tsi_pill, &RMF_SHORT_IO,
438                                           RCL_SERVER)) {
439                         struct niobuf_remote *remote_nb =
440                                 req_capsule_client_get(tsi->tsi_pill,
441                                                        &RMF_NIOBUF_REMOTE);
442                         struct ost_body *body = tsi->tsi_ost_body;
443
444                         req_capsule_set_size(tsi->tsi_pill, &RMF_SHORT_IO,
445                                          RCL_SERVER,
446                                          (body->oa.o_valid & OBD_MD_FLFLAGS &&
447                                           body->oa.o_flags & OBD_FL_SHORT_IO) ?
448                                          remote_nb[0].rnb_len : 0);
449                 }
450
451                 rc = req_capsule_server_pack(tsi->tsi_pill);
452         }
453
454         if (likely(rc == 0)) {
455                 /*
456                  * Process request, there can be two types of rc:
457                  * 1) errors with msg unpack/pack, other failures outside the
458                  * operation itself. This is counted as serious errors;
459                  * 2) errors during fs operation, should be placed in rq_status
460                  * only
461                  */
462                 rc = h->th_act(tsi);
463                 if (!is_serious(rc) &&
464                     !req->rq_no_reply && req->rq_reply_state == NULL) {
465                         DEBUG_REQ(D_ERROR, req, "%s \"handler\" %s did not "
466                                   "pack reply and returned 0 error\n",
467                                   tgt_name(tsi->tsi_tgt), h->th_name);
468                         LBUG();
469                 }
470                 serious = is_serious(rc);
471                 rc = clear_serious(rc);
472         } else {
473                 serious = 1;
474         }
475
476         req->rq_status = rc;
477
478         /*
479          * ELDLM_* codes which > 0 should be in rq_status only as well as
480          * all non-serious errors.
481          */
482         if (rc > 0 || !serious)
483                 rc = 0;
484
485         LASSERT(current->journal_info == NULL);
486
487         if (likely(rc == 0 && req->rq_export))
488                 target_committed_to_req(req);
489
490 out:
491         target_send_reply(req, rc, tsi->tsi_reply_fail_id);
492         RETURN(0);
493 }
494
495 static int tgt_filter_recovery_request(struct ptlrpc_request *req,
496                                        struct obd_device *obd, int *process)
497 {
498         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
499         case MDS_DISCONNECT:
500         case OST_DISCONNECT:
501         case OBD_IDX_READ:
502                 *process = 1;
503                 RETURN(0);
504         case MDS_CLOSE:
505         case MDS_SYNC: /* used in unmounting */
506         case OBD_PING:
507         case MDS_REINT:
508         case OUT_UPDATE:
509         case SEQ_QUERY:
510         case FLD_QUERY:
511         case FLD_READ:
512         case LDLM_ENQUEUE:
513         case OST_CREATE:
514         case OST_DESTROY:
515         case OST_PUNCH:
516         case OST_SETATTR:
517         case OST_SYNC:
518         case OST_WRITE:
519         case MDS_HSM_PROGRESS:
520         case MDS_HSM_STATE_SET:
521         case MDS_HSM_REQUEST:
522                 *process = target_queue_recovery_request(req, obd);
523                 RETURN(0);
524
525         default:
526                 DEBUG_REQ(D_ERROR, req, "not permitted during recovery");
527                 *process = -EAGAIN;
528                 RETURN(0);
529         }
530 }
531
532 /*
533  * Handle recovery. Return:
534  *        +1: continue request processing;
535  *       -ve: abort immediately with the given error code;
536  *         0: send reply with error code in req->rq_status;
537  */
538 static int tgt_handle_recovery(struct ptlrpc_request *req, int reply_fail_id)
539 {
540         ENTRY;
541
542         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
543         case MDS_CONNECT:
544         case OST_CONNECT:
545         case MGS_CONNECT:
546         case SEC_CTX_INIT:
547         case SEC_CTX_INIT_CONT:
548         case SEC_CTX_FINI:
549                 RETURN(+1);
550         }
551
552         if (!req->rq_export->exp_obd->obd_replayable)
553                 RETURN(+1);
554
555         /* sanity check: if the xid matches, the request must be marked as a
556          * resent or replayed */
557         if (req_can_reconstruct(req, NULL)) {
558                 if (!(lustre_msg_get_flags(req->rq_reqmsg) &
559                       (MSG_RESENT | MSG_REPLAY))) {
560                         DEBUG_REQ(D_WARNING, req, "rq_xid %llu matches "
561                                   "saved xid, expected REPLAY or RESENT flag "
562                                   "(%x)", req->rq_xid,
563                                   lustre_msg_get_flags(req->rq_reqmsg));
564                         req->rq_status = -ENOTCONN;
565                         RETURN(-ENOTCONN);
566                 }
567         }
568         /* else: note the opposite is not always true; a RESENT req after a
569          * failover will usually not match the last_xid, since it was likely
570          * never committed. A REPLAYed request will almost never match the
571          * last xid, however it could for a committed, but still retained,
572          * open. */
573
574         /* Check for aborted recovery... */
575         if (unlikely(req->rq_export->exp_obd->obd_recovering)) {
576                 int rc;
577                 int should_process;
578
579                 DEBUG_REQ(D_INFO, req, "Got new replay");
580                 rc = tgt_filter_recovery_request(req, req->rq_export->exp_obd,
581                                                  &should_process);
582                 if (rc != 0 || !should_process)
583                         RETURN(rc);
584                 else if (should_process < 0) {
585                         req->rq_status = should_process;
586                         rc = ptlrpc_error(req);
587                         RETURN(rc);
588                 }
589         }
590         RETURN(+1);
591 }
592
593 /* Initial check for request, it is validation mostly */
594 static struct tgt_handler *tgt_handler_find_check(struct ptlrpc_request *req)
595 {
596         struct tgt_handler      *h;
597         struct tgt_opc_slice    *s;
598         struct lu_target        *tgt;
599         __u32                    opc = lustre_msg_get_opc(req->rq_reqmsg);
600
601         ENTRY;
602
603         tgt = class_exp2tgt(req->rq_export);
604         if (unlikely(tgt == NULL)) {
605                 DEBUG_REQ(D_ERROR, req, "%s: No target for connected export\n",
606                           class_exp2obd(req->rq_export)->obd_name);
607                 RETURN(ERR_PTR(-EINVAL));
608         }
609
610         for (s = tgt->lut_slice; s->tos_hs != NULL; s++)
611                 if (s->tos_opc_start <= opc && opc < s->tos_opc_end)
612                         break;
613
614         /* opcode was not found in slice */
615         if (unlikely(s->tos_hs == NULL)) {
616                 CERROR("%s: no handlers for opcode 0x%x\n", tgt_name(tgt),
617                        opc);
618                 RETURN(ERR_PTR(-ENOTSUPP));
619         }
620
621         LASSERT(opc >= s->tos_opc_start && opc < s->tos_opc_end);
622         h = s->tos_hs + (opc - s->tos_opc_start);
623         if (unlikely(h->th_opc == 0)) {
624                 CERROR("%s: unsupported opcode 0x%x\n", tgt_name(tgt), opc);
625                 RETURN(ERR_PTR(-ENOTSUPP));
626         }
627
628         RETURN(h);
629 }
630
631 static int process_req_last_xid(struct ptlrpc_request *req)
632 {
633         __u64   last_xid;
634         ENTRY;
635
636         /* check request's xid is consistent with export's last_xid */
637         last_xid = lustre_msg_get_last_xid(req->rq_reqmsg);
638         if (last_xid > req->rq_export->exp_last_xid)
639                 req->rq_export->exp_last_xid = last_xid;
640
641         if (req->rq_xid == 0 ||
642             (req->rq_xid <= req->rq_export->exp_last_xid)) {
643                 DEBUG_REQ(D_ERROR, req, "Unexpected xid %llx vs. "
644                           "last_xid %llx\n", req->rq_xid,
645                           req->rq_export->exp_last_xid);
646                 /* Some request is allowed to be sent during replay,
647                  * such as OUT update requests, FLD requests, so it
648                  * is possible that replay requests has smaller XID
649                  * than the exp_last_xid.
650                  *
651                  * Some non-replay requests may have smaller XID as
652                  * well:
653                  *
654                  * - Client send a no_resend RPC, like statfs;
655                  * - The RPC timedout (or some other error) on client,
656                  *   then it's removed from the unreplied list;
657                  * - Client send some other request to bump the
658                  *   exp_last_xid on server;
659                  * - The former RPC got chance to be processed;
660                  */
661                 if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY))
662                         RETURN(-EPROTO);
663         }
664
665         /* The "last_xid" is the minimum xid among unreplied requests,
666          * if the request is from the previous connection, its xid can
667          * still be larger than "exp_last_xid", then the above check of
668          * xid is not enough to determine whether the request is delayed.
669          *
670          * For example, if some replay request was delayed and caused
671          * timeout at client and the replay is restarted, the delayed
672          * replay request will have the larger xid than "exp_last_xid"
673          */
674         if (req->rq_export->exp_conn_cnt >
675             lustre_msg_get_conn_cnt(req->rq_reqmsg))
676                 RETURN(-ESTALE);
677
678         /* try to release in-memory reply data */
679         if (tgt_is_multimodrpcs_client(req->rq_export)) {
680                 tgt_handle_received_xid(req->rq_export,
681                                 lustre_msg_get_last_xid(req->rq_reqmsg));
682                 if (!(lustre_msg_get_flags(req->rq_reqmsg) &
683                       (MSG_RESENT | MSG_REPLAY)))
684                         tgt_handle_tag(req->rq_export,
685                                        lustre_msg_get_tag(req->rq_reqmsg));
686         }
687         RETURN(0);
688 }
689
690 int tgt_request_handle(struct ptlrpc_request *req)
691 {
692         struct tgt_session_info *tsi = tgt_ses_info(req->rq_svc_thread->t_env);
693
694         struct lustre_msg       *msg = req->rq_reqmsg;
695         struct tgt_handler      *h;
696         struct lu_target        *tgt;
697         int                      request_fail_id = 0;
698         __u32                    opc = lustre_msg_get_opc(msg);
699         struct obd_device       *obd;
700         int                      rc;
701         bool                     is_connect = false;
702         ENTRY;
703
704         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_TGT_RECOVERY_REQ_RACE))) {
705                 if (cfs_fail_val == 0 &&
706                     lustre_msg_get_opc(msg) != OBD_PING &&
707                     lustre_msg_get_flags(msg) & MSG_REQ_REPLAY_DONE) {
708                         struct l_wait_info lwi =  { 0 };
709
710                         cfs_fail_val = 1;
711                         cfs_race_state = 0;
712                         l_wait_event(cfs_race_waitq, (cfs_race_state == 1),
713                                      &lwi);
714                 }
715         }
716
717         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
718         tsi->tsi_pill = &req->rq_pill;
719         tsi->tsi_env = req->rq_svc_thread->t_env;
720
721         /* if request has export then get handlers slice from corresponding
722          * target, otherwise that should be connect operation */
723         if (opc == MDS_CONNECT || opc == OST_CONNECT ||
724             opc == MGS_CONNECT) {
725                 is_connect = true;
726                 req_capsule_set(&req->rq_pill, &RQF_CONNECT);
727                 rc = target_handle_connect(req);
728                 if (rc != 0) {
729                         rc = ptlrpc_error(req);
730                         GOTO(out, rc);
731                 }
732                 /* recovery-small test 18c asks to drop connect reply */
733                 if (unlikely(opc == OST_CONNECT &&
734                              OBD_FAIL_CHECK(OBD_FAIL_OST_CONNECT_NET2)))
735                         GOTO(out, rc = 0);
736         }
737
738         if (unlikely(!class_connected_export(req->rq_export))) {
739                 if (opc == SEC_CTX_INIT || opc == SEC_CTX_INIT_CONT ||
740                     opc == SEC_CTX_FINI) {
741                         /* sec context initialization has to be handled
742                          * by hand in tgt_handle_request0() */
743                         tsi->tsi_reply_fail_id = OBD_FAIL_SEC_CTX_INIT_NET;
744                         h = NULL;
745                         GOTO(handle_recov, rc = 0);
746                 }
747                 CDEBUG(D_HA, "operation %d on unconnected OST from %s\n",
748                        opc, libcfs_id2str(req->rq_peer));
749                 req->rq_status = -ENOTCONN;
750                 rc = ptlrpc_error(req);
751                 GOTO(out, rc);
752         }
753
754         tsi->tsi_tgt = tgt = class_exp2tgt(req->rq_export);
755         tsi->tsi_exp = req->rq_export;
756         if (exp_connect_flags(req->rq_export) & OBD_CONNECT_JOBSTATS)
757                 tsi->tsi_jobid = lustre_msg_get_jobid(req->rq_reqmsg);
758         else
759                 tsi->tsi_jobid = NULL;
760
761         if (tgt == NULL) {
762                 DEBUG_REQ(D_ERROR, req, "%s: No target for connected export\n",
763                           class_exp2obd(req->rq_export)->obd_name);
764                 req->rq_status = -EINVAL;
765                 rc = ptlrpc_error(req);
766                 GOTO(out, rc);
767         }
768
769         /* Skip last_xid processing for the recovery thread, otherwise, the
770          * last_xid on same request could be processed twice: first time when
771          * processing the incoming request, second time when the request is
772          * being processed by recovery thread. */
773         obd = class_exp2obd(req->rq_export);
774         if (is_connect) {
775                 /* reset the exp_last_xid on each connection. */
776                 req->rq_export->exp_last_xid = 0;
777         } else if (obd->obd_recovery_data.trd_processing_task !=
778                    current_pid()) {
779                 rc = process_req_last_xid(req);
780                 if (rc) {
781                         req->rq_status = rc;
782                         rc = ptlrpc_error(req);
783                         GOTO(out, rc);
784                 }
785         }
786
787         request_fail_id = tgt->lut_request_fail_id;
788         tsi->tsi_reply_fail_id = tgt->lut_reply_fail_id;
789
790         h = tgt_handler_find_check(req);
791         if (IS_ERR(h)) {
792                 req->rq_status = PTR_ERR(h);
793                 rc = ptlrpc_error(req);
794                 GOTO(out, rc);
795         }
796
797         LASSERTF(h->th_opc == opc, "opcode mismatch %d != %d\n",
798                  h->th_opc, opc);
799
800         if (CFS_FAIL_CHECK_ORSET(request_fail_id, CFS_FAIL_ONCE))
801                 GOTO(out, rc = 0);
802
803         rc = lustre_msg_check_version(msg, h->th_version);
804         if (unlikely(rc)) {
805                 DEBUG_REQ(D_ERROR, req, "%s: drop mal-formed request, version"
806                           " %08x, expecting %08x\n", tgt_name(tgt),
807                           lustre_msg_get_version(msg), h->th_version);
808                 req->rq_status = -EINVAL;
809                 rc = ptlrpc_error(req);
810                 GOTO(out, rc);
811         }
812
813 handle_recov:
814         rc = tgt_handle_recovery(req, tsi->tsi_reply_fail_id);
815         if (likely(rc == 1)) {
816                 rc = tgt_handle_request0(tsi, h, req);
817                 if (rc)
818                         GOTO(out, rc);
819         }
820         EXIT;
821 out:
822         req_capsule_fini(tsi->tsi_pill);
823         if (tsi->tsi_corpus != NULL) {
824                 lu_object_put(tsi->tsi_env, tsi->tsi_corpus);
825                 tsi->tsi_corpus = NULL;
826         }
827         return rc;
828 }
829 EXPORT_SYMBOL(tgt_request_handle);
830
831 /** Assign high priority operations to the request if needed. */
832 int tgt_hpreq_handler(struct ptlrpc_request *req)
833 {
834         struct tgt_session_info *tsi = tgt_ses_info(req->rq_svc_thread->t_env);
835         struct tgt_handler      *h;
836         int                      rc;
837
838         ENTRY;
839
840         if (req->rq_export == NULL)
841                 RETURN(0);
842
843         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
844         tsi->tsi_pill = &req->rq_pill;
845         tsi->tsi_env = req->rq_svc_thread->t_env;
846         tsi->tsi_tgt = class_exp2tgt(req->rq_export);
847         tsi->tsi_exp = req->rq_export;
848
849         h = tgt_handler_find_check(req);
850         if (IS_ERR(h)) {
851                 rc = PTR_ERR(h);
852                 RETURN(rc);
853         }
854
855         rc = tgt_request_preprocess(tsi, h, req);
856         if (unlikely(rc != 0))
857                 RETURN(rc);
858
859         if (h->th_hp != NULL)
860                 h->th_hp(tsi);
861         RETURN(0);
862 }
863 EXPORT_SYMBOL(tgt_hpreq_handler);
864
865 void tgt_counter_incr(struct obd_export *exp, int opcode)
866 {
867         lprocfs_counter_incr(exp->exp_obd->obd_stats, opcode);
868         if (exp->exp_nid_stats && exp->exp_nid_stats->nid_stats != NULL)
869                 lprocfs_counter_incr(exp->exp_nid_stats->nid_stats, opcode);
870 }
871 EXPORT_SYMBOL(tgt_counter_incr);
872
873 /*
874  * Unified target generic handlers.
875  */
876
877 int tgt_connect_check_sptlrpc(struct ptlrpc_request *req, struct obd_export *exp)
878 {
879         struct lu_target        *tgt = class_exp2tgt(exp);
880         struct sptlrpc_flavor    flvr;
881         int                      rc = 0;
882
883         LASSERT(tgt);
884         LASSERT(tgt->lut_obd);
885         LASSERT(tgt->lut_slice);
886
887         /* always allow ECHO client */
888         if (unlikely(strcmp(exp->exp_obd->obd_type->typ_name,
889                             LUSTRE_ECHO_NAME) == 0)) {
890                 exp->exp_flvr.sf_rpc = SPTLRPC_FLVR_ANY;
891                 return 0;
892         }
893
894         if (exp->exp_flvr.sf_rpc == SPTLRPC_FLVR_INVALID) {
895                 read_lock(&tgt->lut_sptlrpc_lock);
896                 sptlrpc_target_choose_flavor(&tgt->lut_sptlrpc_rset,
897                                              req->rq_sp_from,
898                                              req->rq_peer.nid,
899                                              &flvr);
900                 read_unlock(&tgt->lut_sptlrpc_lock);
901
902                 spin_lock(&exp->exp_lock);
903                 exp->exp_sp_peer = req->rq_sp_from;
904                 exp->exp_flvr = flvr;
905
906                 /* when on mgs, if no restriction is set, or if client
907                  * is loopback, allow any flavor */
908                 if ((strcmp(exp->exp_obd->obd_type->typ_name,
909                            LUSTRE_MGS_NAME) == 0) &&
910                      (exp->exp_flvr.sf_rpc == SPTLRPC_FLVR_NULL ||
911                       LNET_NETTYP(LNET_NIDNET(exp->exp_connection->c_peer.nid))
912                       == LOLND))
913                         exp->exp_flvr.sf_rpc = SPTLRPC_FLVR_ANY;
914
915                 if (exp->exp_flvr.sf_rpc != SPTLRPC_FLVR_ANY &&
916                     exp->exp_flvr.sf_rpc != req->rq_flvr.sf_rpc) {
917                         CERROR("%s: unauthorized rpc flavor %x from %s, "
918                                "expect %x\n", tgt_name(tgt),
919                                req->rq_flvr.sf_rpc,
920                                libcfs_nid2str(req->rq_peer.nid),
921                                exp->exp_flvr.sf_rpc);
922                         rc = -EACCES;
923                 }
924                 spin_unlock(&exp->exp_lock);
925         } else {
926                 if (exp->exp_sp_peer != req->rq_sp_from) {
927                         CERROR("%s: RPC source %s doesn't match %s\n",
928                                tgt_name(tgt),
929                                sptlrpc_part2name(req->rq_sp_from),
930                                sptlrpc_part2name(exp->exp_sp_peer));
931                         rc = -EACCES;
932                 } else {
933                         rc = sptlrpc_target_export_check(exp, req);
934                 }
935         }
936
937         return rc;
938 }
939
940 int tgt_adapt_sptlrpc_conf(struct lu_target *tgt)
941 {
942         struct sptlrpc_rule_set  tmp_rset;
943         int                      rc;
944
945         if (unlikely(tgt == NULL)) {
946                 CERROR("No target passed");
947                 return -EINVAL;
948         }
949
950         sptlrpc_rule_set_init(&tmp_rset);
951         rc = sptlrpc_conf_target_get_rules(tgt->lut_obd, &tmp_rset);
952         if (rc) {
953                 CERROR("%s: failed get sptlrpc rules: rc = %d\n",
954                        tgt_name(tgt), rc);
955                 return rc;
956         }
957
958         sptlrpc_target_update_exp_flavor(tgt->lut_obd, &tmp_rset);
959
960         write_lock(&tgt->lut_sptlrpc_lock);
961         sptlrpc_rule_set_free(&tgt->lut_sptlrpc_rset);
962         tgt->lut_sptlrpc_rset = tmp_rset;
963         write_unlock(&tgt->lut_sptlrpc_lock);
964
965         return 0;
966 }
967 EXPORT_SYMBOL(tgt_adapt_sptlrpc_conf);
968
969 int tgt_connect(struct tgt_session_info *tsi)
970 {
971         struct ptlrpc_request   *req = tgt_ses_req(tsi);
972         struct obd_connect_data *reply;
973         int                      rc;
974
975         ENTRY;
976
977         /* XXX: better to call this check right after getting new export but
978          * before last_rcvd slot allocation to avoid server load upon insecure
979          * connects. This is to be fixed after unifiyng all targets.
980          */
981         rc = tgt_connect_check_sptlrpc(req, tsi->tsi_exp);
982         if (rc)
983                 GOTO(out, rc);
984
985         /* To avoid exposing partially initialized connection flags, changes up
986          * to this point have been staged in reply->ocd_connect_flags. Now that
987          * connection handling has completed successfully, atomically update
988          * the connect flags in the shared export data structure. LU-1623 */
989         reply = req_capsule_server_get(tsi->tsi_pill, &RMF_CONNECT_DATA);
990         spin_lock(&tsi->tsi_exp->exp_lock);
991         *exp_connect_flags_ptr(tsi->tsi_exp) = reply->ocd_connect_flags;
992         if (reply->ocd_connect_flags & OBD_CONNECT_FLAGS2)
993                 *exp_connect_flags2_ptr(tsi->tsi_exp) =
994                         reply->ocd_connect_flags2;
995         tsi->tsi_exp->exp_connect_data.ocd_brw_size = reply->ocd_brw_size;
996         spin_unlock(&tsi->tsi_exp->exp_lock);
997
998         if (strcmp(tsi->tsi_exp->exp_obd->obd_type->typ_name,
999                    LUSTRE_MDT_NAME) == 0) {
1000                 rc = req_check_sepol(tsi->tsi_pill);
1001                 if (rc)
1002                         GOTO(out, rc);
1003         }
1004
1005         RETURN(0);
1006 out:
1007         obd_disconnect(class_export_get(tsi->tsi_exp));
1008         return rc;
1009 }
1010 EXPORT_SYMBOL(tgt_connect);
1011
1012 int tgt_disconnect(struct tgt_session_info *tsi)
1013 {
1014         int rc;
1015
1016         ENTRY;
1017
1018         OBD_FAIL_TIMEOUT(OBD_FAIL_OST_DISCONNECT_DELAY, cfs_fail_val);
1019
1020         rc = target_handle_disconnect(tgt_ses_req(tsi));
1021         if (rc)
1022                 RETURN(err_serious(rc));
1023
1024         RETURN(rc);
1025 }
1026 EXPORT_SYMBOL(tgt_disconnect);
1027
1028 /*
1029  * Unified target OBD handlers
1030  */
1031 int tgt_obd_ping(struct tgt_session_info *tsi)
1032 {
1033         int rc;
1034
1035         ENTRY;
1036
1037         /* The target-specific part of OBD_PING request handling.
1038          * It controls Filter Modification Data (FMD) expiration each time
1039          * PING is received.
1040          *
1041          * Valid only for replayable targets, e.g. MDT and OFD
1042          */
1043         if (tsi->tsi_exp->exp_obd->obd_replayable)
1044                 tgt_fmd_expire(tsi->tsi_exp);
1045
1046         rc = req_capsule_server_pack(tsi->tsi_pill);
1047         if (rc)
1048                 RETURN(err_serious(rc));
1049
1050         RETURN(rc);
1051 }
1052 EXPORT_SYMBOL(tgt_obd_ping);
1053
1054 int tgt_obd_log_cancel(struct tgt_session_info *tsi)
1055 {
1056         return err_serious(-EOPNOTSUPP);
1057 }
1058
1059 int tgt_send_buffer(struct tgt_session_info *tsi, struct lu_rdbuf *rdbuf)
1060 {
1061         struct tgt_thread_info  *tti = tgt_th_info(tsi->tsi_env);
1062         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1063         struct obd_export       *exp = req->rq_export;
1064         struct ptlrpc_bulk_desc *desc;
1065         struct l_wait_info      *lwi = &tti->tti_u.update.tti_wait_info;
1066         int                      i;
1067         int                      rc;
1068
1069         ENTRY;
1070
1071         desc = ptlrpc_prep_bulk_exp(req, rdbuf->rb_nbufs, 1,
1072                                   PTLRPC_BULK_PUT_SOURCE | PTLRPC_BULK_BUF_KVEC,
1073                                     MDS_BULK_PORTAL, &ptlrpc_bulk_kvec_ops);
1074         if (desc == NULL)
1075                 RETURN(-ENOMEM);
1076
1077         for (i = 0; i < rdbuf->rb_nbufs; i++)
1078                 desc->bd_frag_ops->add_iov_frag(desc,
1079                                         rdbuf->rb_bufs[i].lb_buf,
1080                                         rdbuf->rb_bufs[i].lb_len);
1081
1082         rc = target_bulk_io(exp, desc, lwi);
1083         ptlrpc_free_bulk(desc);
1084         RETURN(rc);
1085 }
1086 EXPORT_SYMBOL(tgt_send_buffer);
1087
1088 int tgt_sendpage(struct tgt_session_info *tsi, struct lu_rdpg *rdpg, int nob)
1089 {
1090         struct tgt_thread_info  *tti = tgt_th_info(tsi->tsi_env);
1091         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1092         struct obd_export       *exp = req->rq_export;
1093         struct ptlrpc_bulk_desc *desc;
1094         struct l_wait_info      *lwi = &tti->tti_u.rdpg.tti_wait_info;
1095         int                      tmpcount;
1096         int                      tmpsize;
1097         int                      i;
1098         int                      rc;
1099
1100         ENTRY;
1101
1102         desc = ptlrpc_prep_bulk_exp(req, rdpg->rp_npages, 1,
1103                                     PTLRPC_BULK_PUT_SOURCE |
1104                                         PTLRPC_BULK_BUF_KIOV,
1105                                     MDS_BULK_PORTAL,
1106                                     &ptlrpc_bulk_kiov_pin_ops);
1107         if (desc == NULL)
1108                 RETURN(-ENOMEM);
1109
1110         if (!(exp_connect_flags(exp) & OBD_CONNECT_BRW_SIZE))
1111                 /* old client requires reply size in it's PAGE_SIZE,
1112                  * which is rdpg->rp_count */
1113                 nob = rdpg->rp_count;
1114
1115         for (i = 0, tmpcount = nob; i < rdpg->rp_npages && tmpcount > 0;
1116              i++, tmpcount -= tmpsize) {
1117                 tmpsize = min_t(int, tmpcount, PAGE_SIZE);
1118                 desc->bd_frag_ops->add_kiov_frag(desc, rdpg->rp_pages[i], 0,
1119                                                  tmpsize);
1120         }
1121
1122         LASSERT(desc->bd_nob == nob);
1123         rc = target_bulk_io(exp, desc, lwi);
1124         ptlrpc_free_bulk(desc);
1125         RETURN(rc);
1126 }
1127 EXPORT_SYMBOL(tgt_sendpage);
1128
1129 /*
1130  * OBD_IDX_READ handler
1131  */
1132 static int tgt_obd_idx_read(struct tgt_session_info *tsi)
1133 {
1134         struct tgt_thread_info  *tti = tgt_th_info(tsi->tsi_env);
1135         struct lu_rdpg          *rdpg = &tti->tti_u.rdpg.tti_rdpg;
1136         struct idx_info         *req_ii, *rep_ii;
1137         int                      rc, i;
1138
1139         ENTRY;
1140
1141         memset(rdpg, 0, sizeof(*rdpg));
1142         req_capsule_set(tsi->tsi_pill, &RQF_OBD_IDX_READ);
1143
1144         /* extract idx_info buffer from request & reply */
1145         req_ii = req_capsule_client_get(tsi->tsi_pill, &RMF_IDX_INFO);
1146         if (req_ii == NULL || req_ii->ii_magic != IDX_INFO_MAGIC)
1147                 RETURN(err_serious(-EPROTO));
1148
1149         rc = req_capsule_server_pack(tsi->tsi_pill);
1150         if (rc)
1151                 RETURN(err_serious(rc));
1152
1153         rep_ii = req_capsule_server_get(tsi->tsi_pill, &RMF_IDX_INFO);
1154         if (rep_ii == NULL)
1155                 RETURN(err_serious(-EFAULT));
1156         rep_ii->ii_magic = IDX_INFO_MAGIC;
1157
1158         /* extract hash to start with */
1159         rdpg->rp_hash = req_ii->ii_hash_start;
1160
1161         /* extract requested attributes */
1162         rdpg->rp_attrs = req_ii->ii_attrs;
1163
1164         /* check that fid packed in request is valid and supported */
1165         if (!fid_is_sane(&req_ii->ii_fid))
1166                 RETURN(-EINVAL);
1167         rep_ii->ii_fid = req_ii->ii_fid;
1168
1169         /* copy flags */
1170         rep_ii->ii_flags = req_ii->ii_flags;
1171
1172         /* compute number of pages to allocate, ii_count is the number of 4KB
1173          * containers */
1174         if (req_ii->ii_count <= 0)
1175                 GOTO(out, rc = -EFAULT);
1176         rdpg->rp_count = min_t(unsigned int, req_ii->ii_count << LU_PAGE_SHIFT,
1177                                exp_max_brw_size(tsi->tsi_exp));
1178         rdpg->rp_npages = (rdpg->rp_count + PAGE_SIZE - 1) >> PAGE_SHIFT;
1179
1180         /* allocate pages to store the containers */
1181         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof(rdpg->rp_pages[0]));
1182         if (rdpg->rp_pages == NULL)
1183                 GOTO(out, rc = -ENOMEM);
1184         for (i = 0; i < rdpg->rp_npages; i++) {
1185                 rdpg->rp_pages[i] = alloc_page(GFP_NOFS);
1186                 if (rdpg->rp_pages[i] == NULL)
1187                         GOTO(out, rc = -ENOMEM);
1188         }
1189
1190         /* populate pages with key/record pairs */
1191         rc = dt_index_read(tsi->tsi_env, tsi->tsi_tgt->lut_bottom, rep_ii, rdpg);
1192         if (rc < 0)
1193                 GOTO(out, rc);
1194
1195         LASSERTF(rc <= rdpg->rp_count, "dt_index_read() returned more than "
1196                  "asked %d > %d\n", rc, rdpg->rp_count);
1197
1198         /* send pages to client */
1199         rc = tgt_sendpage(tsi, rdpg, rc);
1200         if (rc)
1201                 GOTO(out, rc);
1202         EXIT;
1203 out:
1204         if (rdpg->rp_pages) {
1205                 for (i = 0; i < rdpg->rp_npages; i++)
1206                         if (rdpg->rp_pages[i])
1207                                 __free_page(rdpg->rp_pages[i]);
1208                 OBD_FREE(rdpg->rp_pages,
1209                          rdpg->rp_npages * sizeof(rdpg->rp_pages[0]));
1210         }
1211         return rc;
1212 }
1213
1214 struct tgt_handler tgt_obd_handlers[] = {
1215 TGT_OBD_HDL    (0,      OBD_PING,               tgt_obd_ping),
1216 TGT_OBD_HDL    (0,      OBD_IDX_READ,           tgt_obd_idx_read)
1217 };
1218 EXPORT_SYMBOL(tgt_obd_handlers);
1219
1220 int tgt_sync(const struct lu_env *env, struct lu_target *tgt,
1221              struct dt_object *obj, __u64 start, __u64 end)
1222 {
1223         int rc = 0;
1224
1225         ENTRY;
1226
1227         /* if no objid is specified, it means "sync whole filesystem" */
1228         if (obj == NULL) {
1229                 rc = dt_sync(env, tgt->lut_bottom);
1230         } else if (dt_version_get(env, obj) >
1231                    tgt->lut_obd->obd_last_committed) {
1232                 rc = dt_object_sync(env, obj, start, end);
1233         }
1234         atomic_inc(&tgt->lut_sync_count);
1235
1236         RETURN(rc);
1237 }
1238 EXPORT_SYMBOL(tgt_sync);
1239 /*
1240  * Unified target DLM handlers.
1241  */
1242
1243 /**
1244  * Unified target BAST
1245  *
1246  * Ensure data and metadata are synced to disk when lock is canceled if Sync on
1247  * Cancel (SOC) is enabled. If it's extent lock, normally sync obj is enough,
1248  * but if it's cross-MDT lock, because remote object version is not set, a
1249  * filesystem sync is needed.
1250  *
1251  * \param lock server side lock
1252  * \param desc lock desc
1253  * \param data ldlm_cb_set_arg
1254  * \param flag  indicates whether this cancelling or blocking callback
1255  * \retval      0 on success
1256  * \retval      negative number on error
1257  */
1258 static int tgt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
1259                             void *data, int flag)
1260 {
1261         struct lu_env            env;
1262         struct lu_target        *tgt;
1263         struct dt_object        *obj = NULL;
1264         struct lu_fid            fid;
1265         int                      rc = 0;
1266
1267         ENTRY;
1268
1269         tgt = class_exp2tgt(lock->l_export);
1270
1271         if (unlikely(tgt == NULL)) {
1272                 CDEBUG(D_ERROR, "%s: No target for connected export\n",
1273                        class_exp2obd(lock->l_export)->obd_name);
1274                 RETURN(-EINVAL);
1275         }
1276
1277         if (flag == LDLM_CB_CANCELING &&
1278             (lock->l_granted_mode & (LCK_EX | LCK_PW | LCK_GROUP)) &&
1279             (tgt->lut_sync_lock_cancel == SYNC_LOCK_CANCEL_ALWAYS ||
1280              (tgt->lut_sync_lock_cancel == SYNC_LOCK_CANCEL_BLOCKING &&
1281               ldlm_is_cbpending(lock))) &&
1282             ((exp_connect_flags(lock->l_export) & OBD_CONNECT_MDS_MDS) ||
1283              lock->l_resource->lr_type == LDLM_EXTENT)) {
1284                 __u64 start = 0;
1285                 __u64 end = OBD_OBJECT_EOF;
1286
1287                 rc = lu_env_init(&env, LCT_DT_THREAD);
1288                 if (unlikely(rc != 0))
1289                         GOTO(err, rc);
1290
1291                 ost_fid_from_resid(&fid, &lock->l_resource->lr_name,
1292                                    tgt->lut_lsd.lsd_osd_index);
1293
1294                 if (lock->l_resource->lr_type == LDLM_EXTENT) {
1295                         obj = dt_locate(&env, tgt->lut_bottom, &fid);
1296                         if (IS_ERR(obj))
1297                                 GOTO(err_env, rc = PTR_ERR(obj));
1298
1299                         if (!dt_object_exists(obj))
1300                                 GOTO(err_put, rc = -ENOENT);
1301
1302                         start = lock->l_policy_data.l_extent.start;
1303                         end = lock->l_policy_data.l_extent.end;
1304                 }
1305
1306                 rc = tgt_sync(&env, tgt, obj, start, end);
1307                 if (rc < 0) {
1308                         CERROR("%s: syncing "DFID" (%llu-%llu) on lock "
1309                                "cancel: rc = %d\n",
1310                                tgt_name(tgt), PFID(&fid),
1311                                lock->l_policy_data.l_extent.start,
1312                                lock->l_policy_data.l_extent.end, rc);
1313                 }
1314 err_put:
1315                 if (obj != NULL)
1316                         dt_object_put(&env, obj);
1317 err_env:
1318                 lu_env_fini(&env);
1319         }
1320 err:
1321         rc = ldlm_server_blocking_ast(lock, desc, data, flag);
1322         RETURN(rc);
1323 }
1324
1325 static struct ldlm_callback_suite tgt_dlm_cbs = {
1326         .lcs_completion = ldlm_server_completion_ast,
1327         .lcs_blocking   = tgt_blocking_ast,
1328         .lcs_glimpse    = ldlm_server_glimpse_ast
1329 };
1330
1331 int tgt_enqueue(struct tgt_session_info *tsi)
1332 {
1333         struct ptlrpc_request *req = tgt_ses_req(tsi);
1334         int rc;
1335
1336         ENTRY;
1337         /*
1338          * tsi->tsi_dlm_req was already swapped and (if necessary) converted,
1339          * tsi->tsi_dlm_cbs was set by the *_req_handle() function.
1340          */
1341         LASSERT(tsi->tsi_dlm_req != NULL);
1342         rc = ldlm_handle_enqueue0(tsi->tsi_exp->exp_obd->obd_namespace, req,
1343                                   tsi->tsi_dlm_req, &tgt_dlm_cbs);
1344         if (rc)
1345                 RETURN(err_serious(rc));
1346
1347         switch (LUT_FAIL_CLASS(tsi->tsi_reply_fail_id)) {
1348         case LUT_FAIL_MDT:
1349                 tsi->tsi_reply_fail_id = OBD_FAIL_MDS_LDLM_REPLY_NET;
1350                 break;
1351         case LUT_FAIL_OST:
1352                 tsi->tsi_reply_fail_id = OBD_FAIL_OST_LDLM_REPLY_NET;
1353                 break;
1354         case LUT_FAIL_MGT:
1355                 tsi->tsi_reply_fail_id = OBD_FAIL_MGS_LDLM_REPLY_NET;
1356                 break;
1357         default:
1358                 tsi->tsi_reply_fail_id = OBD_FAIL_LDLM_REPLY;
1359                 break;
1360         }
1361         RETURN(req->rq_status);
1362 }
1363 EXPORT_SYMBOL(tgt_enqueue);
1364
1365 int tgt_convert(struct tgt_session_info *tsi)
1366 {
1367         struct ptlrpc_request *req = tgt_ses_req(tsi);
1368         int rc;
1369
1370         ENTRY;
1371         LASSERT(tsi->tsi_dlm_req);
1372         rc = ldlm_handle_convert0(req, tsi->tsi_dlm_req);
1373         if (rc)
1374                 RETURN(err_serious(rc));
1375
1376         RETURN(req->rq_status);
1377 }
1378
1379 int tgt_bl_callback(struct tgt_session_info *tsi)
1380 {
1381         return err_serious(-EOPNOTSUPP);
1382 }
1383
1384 int tgt_cp_callback(struct tgt_session_info *tsi)
1385 {
1386         return err_serious(-EOPNOTSUPP);
1387 }
1388
1389 /* generic LDLM target handler */
1390 struct tgt_handler tgt_dlm_handlers[] = {
1391 TGT_DLM_HDL    (HABEO_CLAVIS,   LDLM_ENQUEUE,           tgt_enqueue),
1392 TGT_DLM_HDL    (HABEO_CLAVIS,   LDLM_CONVERT,           tgt_convert),
1393 TGT_DLM_HDL_VAR(0,              LDLM_BL_CALLBACK,       tgt_bl_callback),
1394 TGT_DLM_HDL_VAR(0,              LDLM_CP_CALLBACK,       tgt_cp_callback)
1395 };
1396 EXPORT_SYMBOL(tgt_dlm_handlers);
1397
1398 /*
1399  * Unified target LLOG handlers.
1400  */
1401 int tgt_llog_open(struct tgt_session_info *tsi)
1402 {
1403         int rc;
1404
1405         ENTRY;
1406
1407         rc = llog_origin_handle_open(tgt_ses_req(tsi));
1408
1409         RETURN(rc);
1410 }
1411 EXPORT_SYMBOL(tgt_llog_open);
1412
1413 int tgt_llog_read_header(struct tgt_session_info *tsi)
1414 {
1415         int rc;
1416
1417         ENTRY;
1418
1419         rc = llog_origin_handle_read_header(tgt_ses_req(tsi));
1420
1421         RETURN(rc);
1422 }
1423 EXPORT_SYMBOL(tgt_llog_read_header);
1424
1425 int tgt_llog_next_block(struct tgt_session_info *tsi)
1426 {
1427         int rc;
1428
1429         ENTRY;
1430
1431         rc = llog_origin_handle_next_block(tgt_ses_req(tsi));
1432
1433         RETURN(rc);
1434 }
1435 EXPORT_SYMBOL(tgt_llog_next_block);
1436
1437 int tgt_llog_prev_block(struct tgt_session_info *tsi)
1438 {
1439         int rc;
1440
1441         ENTRY;
1442
1443         rc = llog_origin_handle_prev_block(tgt_ses_req(tsi));
1444
1445         RETURN(rc);
1446 }
1447 EXPORT_SYMBOL(tgt_llog_prev_block);
1448
1449 /* generic llog target handler */
1450 struct tgt_handler tgt_llog_handlers[] = {
1451 TGT_LLOG_HDL    (0,     LLOG_ORIGIN_HANDLE_CREATE,      tgt_llog_open),
1452 TGT_LLOG_HDL    (0,     LLOG_ORIGIN_HANDLE_NEXT_BLOCK,  tgt_llog_next_block),
1453 TGT_LLOG_HDL    (0,     LLOG_ORIGIN_HANDLE_READ_HEADER, tgt_llog_read_header),
1454 TGT_LLOG_HDL    (0,     LLOG_ORIGIN_HANDLE_PREV_BLOCK,  tgt_llog_prev_block),
1455 };
1456 EXPORT_SYMBOL(tgt_llog_handlers);
1457
1458 /*
1459  * sec context handlers
1460  */
1461 /* XXX: Implement based on mdt_sec_ctx_handle()? */
1462 static int tgt_sec_ctx_handle(struct tgt_session_info *tsi)
1463 {
1464         return 0;
1465 }
1466
1467 struct tgt_handler tgt_sec_ctx_handlers[] = {
1468 TGT_SEC_HDL_VAR(0,      SEC_CTX_INIT,           tgt_sec_ctx_handle),
1469 TGT_SEC_HDL_VAR(0,      SEC_CTX_INIT_CONT,      tgt_sec_ctx_handle),
1470 TGT_SEC_HDL_VAR(0,      SEC_CTX_FINI,           tgt_sec_ctx_handle),
1471 };
1472 EXPORT_SYMBOL(tgt_sec_ctx_handlers);
1473
1474 int (*tgt_lfsck_in_notify_local)(const struct lu_env *env,
1475                                  struct dt_device *key,
1476                                  struct lfsck_req_local *lrl,
1477                                  struct thandle *th) = NULL;
1478
1479 void tgt_register_lfsck_in_notify_local(int (*notify)(const struct lu_env *,
1480                                                       struct dt_device *,
1481                                                       struct lfsck_req_local *,
1482                                                       struct thandle *))
1483 {
1484         tgt_lfsck_in_notify_local = notify;
1485 }
1486 EXPORT_SYMBOL(tgt_register_lfsck_in_notify_local);
1487
1488 int (*tgt_lfsck_in_notify)(const struct lu_env *env,
1489                            struct dt_device *key,
1490                            struct lfsck_request *lr) = NULL;
1491
1492 void tgt_register_lfsck_in_notify(int (*notify)(const struct lu_env *,
1493                                                 struct dt_device *,
1494                                                 struct lfsck_request *))
1495 {
1496         tgt_lfsck_in_notify = notify;
1497 }
1498 EXPORT_SYMBOL(tgt_register_lfsck_in_notify);
1499
1500 static int (*tgt_lfsck_query)(const struct lu_env *env,
1501                               struct dt_device *key,
1502                               struct lfsck_request *req,
1503                               struct lfsck_reply *rep,
1504                               struct lfsck_query *que) = NULL;
1505
1506 void tgt_register_lfsck_query(int (*query)(const struct lu_env *,
1507                                            struct dt_device *,
1508                                            struct lfsck_request *,
1509                                            struct lfsck_reply *,
1510                                            struct lfsck_query *))
1511 {
1512         tgt_lfsck_query = query;
1513 }
1514 EXPORT_SYMBOL(tgt_register_lfsck_query);
1515
1516 /* LFSCK request handlers */
1517 static int tgt_handle_lfsck_notify(struct tgt_session_info *tsi)
1518 {
1519         const struct lu_env     *env = tsi->tsi_env;
1520         struct dt_device        *key = tsi->tsi_tgt->lut_bottom;
1521         struct lfsck_request    *lr;
1522         int                      rc;
1523         ENTRY;
1524
1525         lr = req_capsule_client_get(tsi->tsi_pill, &RMF_LFSCK_REQUEST);
1526         if (lr == NULL)
1527                 RETURN(-EPROTO);
1528
1529         rc = tgt_lfsck_in_notify(env, key, lr);
1530
1531         RETURN(rc);
1532 }
1533
1534 static int tgt_handle_lfsck_query(struct tgt_session_info *tsi)
1535 {
1536         struct lfsck_request    *request;
1537         struct lfsck_reply      *reply;
1538         int                      rc;
1539         ENTRY;
1540
1541         request = req_capsule_client_get(tsi->tsi_pill, &RMF_LFSCK_REQUEST);
1542         if (request == NULL)
1543                 RETURN(-EPROTO);
1544
1545         reply = req_capsule_server_get(tsi->tsi_pill, &RMF_LFSCK_REPLY);
1546         if (reply == NULL)
1547                 RETURN(-ENOMEM);
1548
1549         rc = tgt_lfsck_query(tsi->tsi_env, tsi->tsi_tgt->lut_bottom,
1550                              request, reply, NULL);
1551
1552         RETURN(rc < 0 ? rc : 0);
1553 }
1554
1555 struct tgt_handler tgt_lfsck_handlers[] = {
1556 TGT_LFSCK_HDL(HABEO_REFERO,     LFSCK_NOTIFY,   tgt_handle_lfsck_notify),
1557 TGT_LFSCK_HDL(HABEO_REFERO,     LFSCK_QUERY,    tgt_handle_lfsck_query),
1558 };
1559 EXPORT_SYMBOL(tgt_lfsck_handlers);
1560
1561 /*
1562  * initialize per-thread page pool (bug 5137).
1563  */
1564 int tgt_io_thread_init(struct ptlrpc_thread *thread)
1565 {
1566         struct tgt_thread_big_cache *tbc;
1567
1568         ENTRY;
1569
1570         LASSERT(thread != NULL);
1571         LASSERT(thread->t_data == NULL);
1572
1573         OBD_ALLOC_LARGE(tbc, sizeof(*tbc));
1574         if (tbc == NULL)
1575                 RETURN(-ENOMEM);
1576         thread->t_data = tbc;
1577         RETURN(0);
1578 }
1579 EXPORT_SYMBOL(tgt_io_thread_init);
1580
1581 /*
1582  * free per-thread pool created by tgt_thread_init().
1583  */
1584 void tgt_io_thread_done(struct ptlrpc_thread *thread)
1585 {
1586         struct tgt_thread_big_cache *tbc;
1587
1588         ENTRY;
1589
1590         LASSERT(thread != NULL);
1591
1592         /*
1593          * be prepared to handle partially-initialized pools (because this is
1594          * called from ost_io_thread_init() for cleanup.
1595          */
1596         tbc = thread->t_data;
1597         if (tbc != NULL) {
1598                 OBD_FREE_LARGE(tbc, sizeof(*tbc));
1599                 thread->t_data = NULL;
1600         }
1601         EXIT;
1602 }
1603 EXPORT_SYMBOL(tgt_io_thread_done);
1604
1605 /**
1606  * Helper function for getting Data-on-MDT file server DLM lock
1607  * if asked by client.
1608  */
1609 int tgt_mdt_data_lock(struct ldlm_namespace *ns, struct ldlm_res_id *res_id,
1610                       struct lustre_handle *lh, int mode, __u64 *flags)
1611 {
1612         union ldlm_policy_data policy = {
1613                 .l_inodebits.bits = MDS_INODELOCK_DOM,
1614         };
1615         int rc;
1616
1617         ENTRY;
1618
1619         LASSERT(lh != NULL);
1620         LASSERT(ns != NULL);
1621         LASSERT(!lustre_handle_is_used(lh));
1622
1623         rc = ldlm_cli_enqueue_local(NULL, ns, res_id, LDLM_IBITS, &policy, mode,
1624                                     flags, ldlm_blocking_ast,
1625                                     ldlm_completion_ast, ldlm_glimpse_ast,
1626                                     NULL, 0, LVB_T_NONE, NULL, lh);
1627
1628         RETURN(rc == ELDLM_OK ? 0 : -EIO);
1629 }
1630 EXPORT_SYMBOL(tgt_mdt_data_lock);
1631
1632 void tgt_mdt_data_unlock(struct lustre_handle *lh, enum ldlm_mode mode)
1633 {
1634         LASSERT(lustre_handle_is_used(lh));
1635         ldlm_lock_decref(lh, mode);
1636 }
1637 EXPORT_SYMBOL(tgt_mdt_data_unlock);
1638
1639 /**
1640  * Helper function for getting server side [start, start+count] DLM lock
1641  * if asked by client.
1642  */
1643 int tgt_extent_lock(const struct lu_env *env, struct ldlm_namespace *ns,
1644                     struct ldlm_res_id *res_id, __u64 start, __u64 end,
1645                     struct lustre_handle *lh, int mode, __u64 *flags)
1646 {
1647         union ldlm_policy_data policy;
1648         int rc;
1649
1650         ENTRY;
1651
1652         LASSERT(lh != NULL);
1653         LASSERT(ns != NULL);
1654         LASSERT(!lustre_handle_is_used(lh));
1655
1656         policy.l_extent.gid = 0;
1657         policy.l_extent.start = start & PAGE_MASK;
1658
1659         /*
1660          * If ->o_blocks is EOF it means "lock till the end of the file".
1661          * Otherwise, it's size of an extent or hole being punched (in bytes).
1662          */
1663         if (end == OBD_OBJECT_EOF || end < start)
1664                 policy.l_extent.end = OBD_OBJECT_EOF;
1665         else
1666                 policy.l_extent.end = end | ~PAGE_MASK;
1667
1668         rc = ldlm_cli_enqueue_local(env, ns, res_id, LDLM_EXTENT, &policy,
1669                                     mode, flags, ldlm_blocking_ast,
1670                                     ldlm_completion_ast, ldlm_glimpse_ast,
1671                                     NULL, 0, LVB_T_NONE, NULL, lh);
1672         RETURN(rc == ELDLM_OK ? 0 : -EIO);
1673 }
1674 EXPORT_SYMBOL(tgt_extent_lock);
1675
1676 void tgt_extent_unlock(struct lustre_handle *lh, enum ldlm_mode mode)
1677 {
1678         LASSERT(lustre_handle_is_used(lh));
1679         ldlm_lock_decref(lh, mode);
1680 }
1681 EXPORT_SYMBOL(tgt_extent_unlock);
1682
1683 static int tgt_brw_lock(const struct lu_env *env, struct obd_export *exp,
1684                         struct ldlm_res_id *res_id, struct obd_ioobj *obj,
1685                         struct niobuf_remote *nb, struct lustre_handle *lh,
1686                         enum ldlm_mode mode)
1687 {
1688         struct ldlm_namespace   *ns = exp->exp_obd->obd_namespace;
1689         __u64                    flags = 0;
1690         int                      nrbufs = obj->ioo_bufcnt;
1691         int                      i;
1692         int                      rc;
1693
1694         ENTRY;
1695
1696         LASSERT(mode == LCK_PR || mode == LCK_PW);
1697         LASSERT(!lustre_handle_is_used(lh));
1698
1699         if (ns->ns_obd->obd_recovering)
1700                 RETURN(0);
1701
1702         if (nrbufs == 0 || !(nb[0].rnb_flags & OBD_BRW_SRVLOCK))
1703                 RETURN(0);
1704
1705         for (i = 1; i < nrbufs; i++)
1706                 if (!(nb[i].rnb_flags & OBD_BRW_SRVLOCK))
1707                         RETURN(-EFAULT);
1708
1709         /* MDT IO for data-on-mdt */
1710         if (exp->exp_connect_data.ocd_connect_flags & OBD_CONNECT_IBITS)
1711                 rc = tgt_mdt_data_lock(ns, res_id, lh, mode, &flags);
1712         else
1713                 rc = tgt_extent_lock(env, ns, res_id, nb[0].rnb_offset,
1714                                      nb[nrbufs - 1].rnb_offset +
1715                                      nb[nrbufs - 1].rnb_len - 1,
1716                                      lh, mode, &flags);
1717         RETURN(rc);
1718 }
1719
1720 static void tgt_brw_unlock(struct obd_ioobj *obj, struct niobuf_remote *niob,
1721                            struct lustre_handle *lh, enum ldlm_mode mode)
1722 {
1723         ENTRY;
1724
1725         LASSERT(mode == LCK_PR || mode == LCK_PW);
1726         LASSERT((obj->ioo_bufcnt > 0 &&
1727                  (niob[0].rnb_flags & OBD_BRW_SRVLOCK)) ==
1728                 lustre_handle_is_used(lh));
1729
1730         if (lustre_handle_is_used(lh))
1731                 tgt_extent_unlock(lh, mode);
1732         EXIT;
1733 }
1734 static int tgt_checksum_niobuf(struct lu_target *tgt,
1735                                  struct niobuf_local *local_nb, int npages,
1736                                  int opc, enum cksum_types cksum_type,
1737                                  __u32 *cksum)
1738 {
1739         struct ahash_request           *req;
1740         unsigned int                    bufsize;
1741         int                             i, err;
1742         unsigned char                   cfs_alg = cksum_obd2cfs(cksum_type);
1743
1744         req = cfs_crypto_hash_init(cfs_alg, NULL, 0);
1745         if (IS_ERR(req)) {
1746                 CERROR("%s: unable to initialize checksum hash %s\n",
1747                        tgt_name(tgt), cfs_crypto_hash_name(cfs_alg));
1748                 return PTR_ERR(req);
1749         }
1750
1751         CDEBUG(D_INFO, "Checksum for algo %s\n", cfs_crypto_hash_name(cfs_alg));
1752         for (i = 0; i < npages; i++) {
1753                 /* corrupt the data before we compute the checksum, to
1754                  * simulate a client->OST data error */
1755                 if (i == 0 && opc == OST_WRITE &&
1756                     OBD_FAIL_CHECK(OBD_FAIL_OST_CHECKSUM_RECEIVE)) {
1757                         int off = local_nb[i].lnb_page_offset & ~PAGE_MASK;
1758                         int len = local_nb[i].lnb_len;
1759                         struct page *np = tgt_page_to_corrupt;
1760
1761                         if (np) {
1762                                 char *ptr = ll_kmap_atomic(local_nb[i].lnb_page,
1763                                                         KM_USER0);
1764                                 char *ptr2 = page_address(np);
1765
1766                                 memcpy(ptr2 + off, ptr + off, len);
1767                                 memcpy(ptr2 + off, "bad3", min(4, len));
1768                                 ll_kunmap_atomic(ptr, KM_USER0);
1769
1770                                 /* LU-8376 to preserve original index for
1771                                  * display in dump_all_bulk_pages() */
1772                                 np->index = i;
1773
1774                                 cfs_crypto_hash_update_page(req, np, off,
1775                                                             len);
1776                                 continue;
1777                         } else {
1778                                 CERROR("%s: can't alloc page for corruption\n",
1779                                        tgt_name(tgt));
1780                         }
1781                 }
1782                 cfs_crypto_hash_update_page(req, local_nb[i].lnb_page,
1783                                   local_nb[i].lnb_page_offset & ~PAGE_MASK,
1784                                   local_nb[i].lnb_len);
1785
1786                  /* corrupt the data after we compute the checksum, to
1787                  * simulate an OST->client data error */
1788                 if (i == 0 && opc == OST_READ &&
1789                     OBD_FAIL_CHECK(OBD_FAIL_OST_CHECKSUM_SEND)) {
1790                         int off = local_nb[i].lnb_page_offset & ~PAGE_MASK;
1791                         int len = local_nb[i].lnb_len;
1792                         struct page *np = tgt_page_to_corrupt;
1793
1794                         if (np) {
1795                                 char *ptr = ll_kmap_atomic(local_nb[i].lnb_page,
1796                                                         KM_USER0);
1797                                 char *ptr2 = page_address(np);
1798
1799                                 memcpy(ptr2 + off, ptr + off, len);
1800                                 memcpy(ptr2 + off, "bad4", min(4, len));
1801                                 ll_kunmap_atomic(ptr, KM_USER0);
1802
1803                                 /* LU-8376 to preserve original index for
1804                                  * display in dump_all_bulk_pages() */
1805                                 np->index = i;
1806
1807                                 cfs_crypto_hash_update_page(req, np, off,
1808                                                             len);
1809                                 continue;
1810                         } else {
1811                                 CERROR("%s: can't alloc page for corruption\n",
1812                                        tgt_name(tgt));
1813                         }
1814                 }
1815         }
1816
1817         bufsize = sizeof(*cksum);
1818         err = cfs_crypto_hash_final(req, (unsigned char *)cksum, &bufsize);
1819
1820         return 0;
1821 }
1822
1823 char dbgcksum_file_name[PATH_MAX];
1824
1825 static void dump_all_bulk_pages(struct obdo *oa, int count,
1826                                 struct niobuf_local *local_nb,
1827                                 __u32 server_cksum, __u32 client_cksum)
1828 {
1829         struct file *filp;
1830         int rc, i;
1831         unsigned int len;
1832         char *buf;
1833
1834         /* will only keep dump of pages on first error for the same range in
1835          * file/fid, not during the resends/retries. */
1836         snprintf(dbgcksum_file_name, sizeof(dbgcksum_file_name),
1837                  "%s-checksum_dump-ost-"DFID":[%llu-%llu]-%x-%x",
1838                  (strncmp(libcfs_debug_file_path_arr, "NONE", 4) != 0 ?
1839                   libcfs_debug_file_path_arr :
1840                   LIBCFS_DEBUG_FILE_PATH_DEFAULT),
1841                  oa->o_valid & OBD_MD_FLFID ? oa->o_parent_seq : (__u64)0,
1842                  oa->o_valid & OBD_MD_FLFID ? oa->o_parent_oid : 0,
1843                  oa->o_valid & OBD_MD_FLFID ? oa->o_parent_ver : 0,
1844                  local_nb[0].lnb_file_offset,
1845                  local_nb[count-1].lnb_file_offset +
1846                  local_nb[count-1].lnb_len - 1, client_cksum, server_cksum);
1847         filp = filp_open(dbgcksum_file_name,
1848                          O_CREAT | O_EXCL | O_WRONLY | O_LARGEFILE, 0600);
1849         if (IS_ERR(filp)) {
1850                 rc = PTR_ERR(filp);
1851                 if (rc == -EEXIST)
1852                         CDEBUG(D_INFO, "%s: can't open to dump pages with "
1853                                "checksum error: rc = %d\n", dbgcksum_file_name,
1854                                rc);
1855                 else
1856                         CERROR("%s: can't open to dump pages with checksum "
1857                                "error: rc = %d\n", dbgcksum_file_name, rc);
1858                 return;
1859         }
1860
1861         for (i = 0; i < count; i++) {
1862                 len = local_nb[i].lnb_len;
1863                 buf = kmap(local_nb[i].lnb_page);
1864                 while (len != 0) {
1865                         rc = cfs_kernel_write(filp, buf, len, &filp->f_pos);
1866                         if (rc < 0) {
1867                                 CERROR("%s: wanted to write %u but got %d "
1868                                        "error\n", dbgcksum_file_name, len, rc);
1869                                 break;
1870                         }
1871                         len -= rc;
1872                         buf += rc;
1873                         CDEBUG(D_INFO, "%s: wrote %d bytes\n",
1874                                dbgcksum_file_name, rc);
1875                 }
1876                 kunmap(local_nb[i].lnb_page);
1877         }
1878
1879         rc = ll_vfs_fsync_range(filp, 0, LLONG_MAX, 1);
1880         if (rc)
1881                 CERROR("%s: sync returns %d\n", dbgcksum_file_name, rc);
1882         filp_close(filp, NULL);
1883         return;
1884 }
1885
1886 static int check_read_checksum(struct niobuf_local *local_nb, int npages,
1887                                struct obd_export *exp, struct obdo *oa,
1888                                const struct lnet_process_id *peer,
1889                                __u32 client_cksum, __u32 server_cksum,
1890                                enum cksum_types server_cksum_type)
1891 {
1892         char *msg;
1893         enum cksum_types cksum_type;
1894         loff_t start, end;
1895
1896         /* unlikely to happen and only if resend does not occur due to cksum
1897          * control failure on Client */
1898         if (unlikely(server_cksum == client_cksum)) {
1899                 CDEBUG(D_PAGE, "checksum %x confirmed upon retry\n",
1900                        client_cksum);
1901                 return 0;
1902         }
1903
1904         if (exp->exp_obd->obd_checksum_dump)
1905                 dump_all_bulk_pages(oa, npages, local_nb, server_cksum,
1906                                     client_cksum);
1907
1908         cksum_type = obd_cksum_type_unpack(oa->o_valid & OBD_MD_FLFLAGS ?
1909                                            oa->o_flags : 0);
1910
1911         if (cksum_type != server_cksum_type)
1912                 msg = "the server may have not used the checksum type specified"
1913                       " in the original request - likely a protocol problem";
1914         else
1915                 msg = "should have changed on the client or in transit";
1916
1917         start = local_nb[0].lnb_file_offset;
1918         end = local_nb[npages-1].lnb_file_offset +
1919                                         local_nb[npages-1].lnb_len - 1;
1920
1921         LCONSOLE_ERROR_MSG(0x132, "%s: BAD READ CHECKSUM: %s: from %s inode "
1922                 DFID " object "DOSTID" extent [%llu-%llu], client returned csum"
1923                 " %x (type %x), server csum %x (type %x)\n",
1924                 exp->exp_obd->obd_name,
1925                 msg, libcfs_nid2str(peer->nid),
1926                 oa->o_valid & OBD_MD_FLFID ? oa->o_parent_seq : 0ULL,
1927                 oa->o_valid & OBD_MD_FLFID ? oa->o_parent_oid : 0,
1928                 oa->o_valid & OBD_MD_FLFID ? oa->o_parent_ver : 0,
1929                 POSTID(&oa->o_oi),
1930                 start, end, client_cksum, cksum_type, server_cksum,
1931                 server_cksum_type);
1932
1933         return 1;
1934 }
1935
1936 static int tgt_pages2shortio(struct niobuf_local *local, int npages,
1937                              unsigned char *buf, int size)
1938 {
1939         int     i, off, len, copied = size;
1940         char    *ptr;
1941
1942         for (i = 0; i < npages; i++) {
1943                 off = local[i].lnb_page_offset & ~PAGE_MASK;
1944                 len = local[i].lnb_len;
1945
1946                 CDEBUG(D_PAGE, "index %d offset = %d len = %d left = %d\n",
1947                        i, off, len, size);
1948                 if (len > size)
1949                         return -EINVAL;
1950
1951                 ptr = ll_kmap_atomic(local[i].lnb_page, KM_USER0);
1952                 memcpy(buf + off, ptr, len);
1953                 ll_kunmap_atomic(ptr, KM_USER0);
1954                 buf += len;
1955                 size -= len;
1956         }
1957         return copied - size;
1958 }
1959
1960 static int tgt_checksum_niobuf_t10pi(struct lu_target *tgt,
1961                                      struct niobuf_local *local_nb,
1962                                      int npages, int opc,
1963                                      obd_dif_csum_fn *fn,
1964                                      int sector_size,
1965                                      u32 *check_sum)
1966 {
1967         enum cksum_types t10_cksum_type = tgt->lut_dt_conf.ddp_t10_cksum_type;
1968         unsigned char cfs_alg = cksum_obd2cfs(OBD_CKSUM_T10_TOP);
1969         const char *obd_name = tgt->lut_obd->obd_name;
1970         struct ahash_request *req;
1971         unsigned int bufsize;
1972         unsigned char *buffer;
1973         struct page *__page;
1974         __u16 *guard_start;
1975         int guard_number;
1976         int used_number = 0;
1977         __u32 cksum;
1978         int rc = 0;
1979         int used;
1980         int i;
1981
1982         __page = alloc_page(GFP_KERNEL);
1983         if (__page == NULL)
1984                 return -ENOMEM;
1985
1986         req = cfs_crypto_hash_init(cfs_alg, NULL, 0);
1987         if (IS_ERR(req)) {
1988                 CERROR("%s: unable to initialize checksum hash %s\n",
1989                        tgt_name(tgt), cfs_crypto_hash_name(cfs_alg));
1990                 return PTR_ERR(req);
1991         }
1992
1993         buffer = kmap(__page);
1994         guard_start = (__u16 *)buffer;
1995         guard_number = PAGE_SIZE / sizeof(*guard_start);
1996         for (i = 0; i < npages; i++) {
1997                 /* corrupt the data before we compute the checksum, to
1998                  * simulate a client->OST data error */
1999                 if (i == 0 && opc == OST_WRITE &&
2000                     OBD_FAIL_CHECK(OBD_FAIL_OST_CHECKSUM_RECEIVE)) {
2001                         int off = local_nb[i].lnb_page_offset & ~PAGE_MASK;
2002                         int len = local_nb[i].lnb_len;
2003                         struct page *np = tgt_page_to_corrupt;
2004
2005                         if (np) {
2006                                 char *ptr = ll_kmap_atomic(local_nb[i].lnb_page,
2007                                                         KM_USER0);
2008                                 char *ptr2 = page_address(np);
2009
2010                                 memcpy(ptr2 + off, ptr + off, len);
2011                                 memcpy(ptr2 + off, "bad3", min(4, len));
2012                                 ll_kunmap_atomic(ptr, KM_USER0);
2013
2014                                 /* LU-8376 to preserve original index for
2015                                  * display in dump_all_bulk_pages() */
2016                                 np->index = i;
2017
2018                                 cfs_crypto_hash_update_page(req, np, off,
2019                                                             len);
2020                                 continue;
2021                         } else {
2022                                 CERROR("%s: can't alloc page for corruption\n",
2023                                        tgt_name(tgt));
2024                         }
2025                 }
2026
2027                 /*
2028                  * The left guard number should be able to hold checksums of a
2029                  * whole page
2030                  */
2031                 if (t10_cksum_type && opc == OST_READ &&
2032                     local_nb[i].lnb_guard_disk) {
2033                         used = DIV_ROUND_UP(local_nb[i].lnb_len, sector_size);
2034                         if (used > (guard_number - used_number)) {
2035                                 rc = -E2BIG;
2036                                 break;
2037                         }
2038                         memcpy(guard_start + used_number,
2039                                local_nb[i].lnb_guards,
2040                                used * sizeof(*local_nb[i].lnb_guards));
2041                 } else {
2042                         rc = obd_page_dif_generate_buffer(obd_name,
2043                                 local_nb[i].lnb_page,
2044                                 local_nb[i].lnb_page_offset & ~PAGE_MASK,
2045                                 local_nb[i].lnb_len, guard_start + used_number,
2046                                 guard_number - used_number, &used, sector_size,
2047                                 fn);
2048                         if (rc)
2049                                 break;
2050                 }
2051
2052                 LASSERT(used <= MAX_GUARD_NUMBER);
2053                 /*
2054                  * If disk support T10PI checksum, copy guards to local_nb.
2055                  * If the write is partial page, do not use the guards for bio
2056                  * submission since the data might not be full-sector. The bio
2057                  * guards will be generated later based on the full sectors. If
2058                  * the sector size is 512B rather than 4 KB, or the page size
2059                  * is larger than 4KB, this might drop some useful guards for
2060                  * partial page write, but it will only add minimal extra time
2061                  * of checksum calculation.
2062                  */
2063                 if (t10_cksum_type && opc == OST_WRITE &&
2064                     local_nb[i].lnb_len == PAGE_SIZE) {
2065                         local_nb[i].lnb_guard_rpc = 1;
2066                         memcpy(local_nb[i].lnb_guards,
2067                                guard_start + used_number,
2068                                used * sizeof(*local_nb[i].lnb_guards));
2069                 }
2070
2071                 used_number += used;
2072                 if (used_number == guard_number) {
2073                         cfs_crypto_hash_update_page(req, __page, 0,
2074                                 used_number * sizeof(*guard_start));
2075                         used_number = 0;
2076                 }
2077
2078                  /* corrupt the data after we compute the checksum, to
2079                  * simulate an OST->client data error */
2080                 if (unlikely(i == 0 && opc == OST_READ &&
2081                              OBD_FAIL_CHECK(OBD_FAIL_OST_CHECKSUM_SEND))) {
2082                         int off = local_nb[i].lnb_page_offset & ~PAGE_MASK;
2083                         int len = local_nb[i].lnb_len;
2084                         struct page *np = tgt_page_to_corrupt;
2085
2086                         if (np) {
2087                                 char *ptr = ll_kmap_atomic(local_nb[i].lnb_page,
2088                                                         KM_USER0);
2089                                 char *ptr2 = page_address(np);
2090
2091                                 memcpy(ptr2 + off, ptr + off, len);
2092                                 memcpy(ptr2 + off, "bad4", min(4, len));
2093                                 ll_kunmap_atomic(ptr, KM_USER0);
2094
2095                                 /* LU-8376 to preserve original index for
2096                                  * display in dump_all_bulk_pages() */
2097                                 np->index = i;
2098
2099                                 cfs_crypto_hash_update_page(req, np, off,
2100                                                             len);
2101                                 continue;
2102                         } else {
2103                                 CERROR("%s: can't alloc page for corruption\n",
2104                                        tgt_name(tgt));
2105                         }
2106                 }
2107         }
2108         kunmap(__page);
2109         if (rc)
2110                 GOTO(out, rc);
2111
2112         if (used_number != 0)
2113                 cfs_crypto_hash_update_page(req, __page, 0,
2114                         used_number * sizeof(*guard_start));
2115
2116         bufsize = sizeof(cksum);
2117         rc = cfs_crypto_hash_final(req, (unsigned char *)&cksum, &bufsize);
2118
2119         if (rc == 0)
2120                 *check_sum = cksum;
2121 out:
2122         __free_page(__page);
2123         return rc;
2124 }
2125
2126 static int tgt_checksum_niobuf_rw(struct lu_target *tgt,
2127                                   enum cksum_types cksum_type,
2128                                   struct niobuf_local *local_nb,
2129                                   int npages, int opc, u32 *check_sum)
2130 {
2131         obd_dif_csum_fn *fn = NULL;
2132         int sector_size = 0;
2133         int rc;
2134
2135         ENTRY;
2136         obd_t10_cksum2dif(cksum_type, &fn, &sector_size);
2137
2138         if (fn)
2139                 rc = tgt_checksum_niobuf_t10pi(tgt, local_nb, npages,
2140                                                opc, fn, sector_size,
2141                                                check_sum);
2142         else
2143                 rc = tgt_checksum_niobuf(tgt, local_nb, npages, opc,
2144                                          cksum_type, check_sum);
2145         RETURN(rc);
2146 }
2147
2148 int tgt_brw_read(struct tgt_session_info *tsi)
2149 {
2150         struct ptlrpc_request   *req = tgt_ses_req(tsi);
2151         struct ptlrpc_bulk_desc *desc = NULL;
2152         struct obd_export       *exp = tsi->tsi_exp;
2153         struct niobuf_remote    *remote_nb;
2154         struct niobuf_local     *local_nb;
2155         struct obd_ioobj        *ioo;
2156         struct ost_body         *body, *repbody;
2157         struct l_wait_info       lwi;
2158         struct lustre_handle     lockh = { 0 };
2159         int                      npages, nob = 0, rc, i, no_reply = 0,
2160                                  npages_read;
2161         struct tgt_thread_big_cache *tbc = req->rq_svc_thread->t_data;
2162         const char *obd_name = exp->exp_obd->obd_name;
2163
2164         ENTRY;
2165
2166         if (ptlrpc_req2svc(req)->srv_req_portal != OST_IO_PORTAL &&
2167             ptlrpc_req2svc(req)->srv_req_portal != MDS_IO_PORTAL) {
2168                 CERROR("%s: deny read request from %s to portal %u\n",
2169                        tgt_name(tsi->tsi_tgt),
2170                        obd_export_nid2str(req->rq_export),
2171                        ptlrpc_req2svc(req)->srv_req_portal);
2172                 RETURN(-EPROTO);
2173         }
2174
2175         req->rq_bulk_read = 1;
2176
2177         if (OBD_FAIL_CHECK(OBD_FAIL_OST_BRW_READ_BULK))
2178                 RETURN(-EIO);
2179
2180         OBD_FAIL_TIMEOUT(OBD_FAIL_OST_BRW_PAUSE_BULK, cfs_fail_val > 0 ?
2181                          cfs_fail_val : (obd_timeout + 1) / 4);
2182
2183         /* Check if there is eviction in progress, and if so, wait for it to
2184          * finish */
2185         if (unlikely(atomic_read(&exp->exp_obd->obd_evict_inprogress))) {
2186                 /* We do not care how long it takes */
2187                 lwi = LWI_INTR(NULL, NULL);
2188                 rc = l_wait_event(exp->exp_obd->obd_evict_inprogress_waitq,
2189                          !atomic_read(&exp->exp_obd->obd_evict_inprogress),
2190                          &lwi);
2191         }
2192
2193         /* There must be big cache in current thread to process this request
2194          * if it is NULL then something went wrong and it wasn't allocated,
2195          * report -ENOMEM in that case */
2196         if (tbc == NULL)
2197                 RETURN(-ENOMEM);
2198
2199         body = tsi->tsi_ost_body;
2200         LASSERT(body != NULL);
2201
2202         ioo = req_capsule_client_get(tsi->tsi_pill, &RMF_OBD_IOOBJ);
2203         LASSERT(ioo != NULL); /* must exists after tgt_ost_body_unpack */
2204
2205         remote_nb = req_capsule_client_get(&req->rq_pill, &RMF_NIOBUF_REMOTE);
2206         LASSERT(remote_nb != NULL); /* must exists after tgt_ost_body_unpack */
2207
2208         local_nb = tbc->local;
2209
2210         rc = tgt_brw_lock(tsi->tsi_env, exp, &tsi->tsi_resid, ioo, remote_nb,
2211                           &lockh, LCK_PR);
2212         if (rc != 0)
2213                 RETURN(rc);
2214
2215         /*
2216          * If getting the lock took more time than
2217          * client was willing to wait, drop it. b=11330
2218          */
2219         if (ktime_get_real_seconds() > req->rq_deadline ||
2220             OBD_FAIL_CHECK(OBD_FAIL_OST_DROP_REQ)) {
2221                 no_reply = 1;
2222                 CERROR("Dropping timed-out read from %s because locking object " DOSTID " took %lld seconds (limit was %lld).\n",
2223                        libcfs_id2str(req->rq_peer), POSTID(&ioo->ioo_oid),
2224                        ktime_get_real_seconds() - req->rq_arrival_time.tv_sec,
2225                        req->rq_deadline - req->rq_arrival_time.tv_sec);
2226                 GOTO(out_lock, rc = -ETIMEDOUT);
2227         }
2228
2229         repbody = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
2230         repbody->oa = body->oa;
2231
2232         npages = PTLRPC_MAX_BRW_PAGES;
2233         rc = obd_preprw(tsi->tsi_env, OBD_BRW_READ, exp, &repbody->oa, 1,
2234                         ioo, remote_nb, &npages, local_nb);
2235         if (rc != 0)
2236                 GOTO(out_lock, rc);
2237
2238         if (body->oa.o_valid & OBD_MD_FLFLAGS &&
2239             body->oa.o_flags & OBD_FL_SHORT_IO) {
2240                 desc = NULL;
2241         } else {
2242                 desc = ptlrpc_prep_bulk_exp(req, npages, ioobj_max_brw_get(ioo),
2243                                             PTLRPC_BULK_PUT_SOURCE |
2244                                                 PTLRPC_BULK_BUF_KIOV,
2245                                             OST_BULK_PORTAL,
2246                                             &ptlrpc_bulk_kiov_nopin_ops);
2247                 if (desc == NULL)
2248                         GOTO(out_commitrw, rc = -ENOMEM);
2249         }
2250
2251         nob = 0;
2252         npages_read = npages;
2253         for (i = 0; i < npages; i++) {
2254                 int page_rc = local_nb[i].lnb_rc;
2255
2256                 if (page_rc < 0) {
2257                         rc = page_rc;
2258                         npages_read = i;
2259                         break;
2260                 }
2261
2262                 nob += page_rc;
2263                 if (page_rc != 0 && desc != NULL) { /* some data! */
2264                         LASSERT(local_nb[i].lnb_page != NULL);
2265                         desc->bd_frag_ops->add_kiov_frag
2266                           (desc, local_nb[i].lnb_page,
2267                            local_nb[i].lnb_page_offset & ~PAGE_MASK,
2268                            page_rc);
2269                 }
2270
2271                 if (page_rc != local_nb[i].lnb_len) { /* short read */
2272                         local_nb[i].lnb_len = page_rc;
2273                         npages_read = i + (page_rc != 0 ? 1 : 0);
2274                         /* All subsequent pages should be 0 */
2275                         while (++i < npages)
2276                                 LASSERT(local_nb[i].lnb_rc == 0);
2277                         break;
2278                 }
2279         }
2280         if (OBD_FAIL_CHECK(OBD_FAIL_OST_READ_SIZE) &&
2281             nob != cfs_fail_val)
2282                 rc = -E2BIG;
2283
2284         if (body->oa.o_valid & OBD_MD_FLCKSUM) {
2285                 u32 flag = body->oa.o_valid & OBD_MD_FLFLAGS ?
2286                            body->oa.o_flags : 0;
2287                 enum cksum_types cksum_type = obd_cksum_type_unpack(flag);
2288
2289                 repbody->oa.o_flags = obd_cksum_type_pack(obd_name,
2290                                                           cksum_type);
2291                 repbody->oa.o_valid = OBD_MD_FLCKSUM | OBD_MD_FLFLAGS;
2292
2293                 rc = tgt_checksum_niobuf_rw(tsi->tsi_tgt, cksum_type,
2294                                             local_nb, npages_read, OST_READ,
2295                                             &repbody->oa.o_cksum);
2296                 if (rc < 0)
2297                         GOTO(out_commitrw, rc);
2298                 CDEBUG(D_PAGE, "checksum at read origin: %x\n",
2299                        repbody->oa.o_cksum);
2300
2301                 /* if a resend it could be for a cksum error, so check Server
2302                  * cksum with returned Client cksum (this should even cover
2303                  * zero-cksum case) */
2304                 if ((body->oa.o_valid & OBD_MD_FLFLAGS) &&
2305                     (body->oa.o_flags & OBD_FL_RECOV_RESEND))
2306                         check_read_checksum(local_nb, npages_read, exp,
2307                                             &body->oa, &req->rq_peer,
2308                                             body->oa.o_cksum,
2309                                             repbody->oa.o_cksum, cksum_type);
2310         } else {
2311                 repbody->oa.o_valid = 0;
2312         }
2313         /* We're finishing using body->oa as an input variable */
2314
2315         /* Check if client was evicted while we were doing i/o before touching
2316          * network */
2317         if (rc == 0) {
2318                 if (body->oa.o_valid & OBD_MD_FLFLAGS &&
2319                     body->oa.o_flags & OBD_FL_SHORT_IO) {
2320                         unsigned char *short_io_buf;
2321                         int short_io_size;
2322
2323                         short_io_buf = req_capsule_server_get(&req->rq_pill,
2324                                                               &RMF_SHORT_IO);
2325                         short_io_size = req_capsule_get_size(&req->rq_pill,
2326                                                              &RMF_SHORT_IO,
2327                                                              RCL_SERVER);
2328                         rc = tgt_pages2shortio(local_nb, npages_read,
2329                                                short_io_buf, short_io_size);
2330                         if (rc >= 0)
2331                                 req_capsule_shrink(&req->rq_pill,
2332                                                    &RMF_SHORT_IO, rc,
2333                                                    RCL_SERVER);
2334                         rc = rc > 0 ? 0 : rc;
2335                 } else if (!CFS_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CLIENT_BULK_CB2)) {
2336                         rc = target_bulk_io(exp, desc, &lwi);
2337                 }
2338                 no_reply = rc != 0;
2339         } else {
2340                 if (body->oa.o_valid & OBD_MD_FLFLAGS &&
2341                     body->oa.o_flags & OBD_FL_SHORT_IO)
2342                         req_capsule_shrink(&req->rq_pill, &RMF_SHORT_IO, 0,
2343                                            RCL_SERVER);
2344         }
2345
2346 out_commitrw:
2347         /* Must commit after prep above in all cases */
2348         rc = obd_commitrw(tsi->tsi_env, OBD_BRW_READ, exp, &repbody->oa, 1, ioo,
2349                           remote_nb, npages, local_nb, rc);
2350 out_lock:
2351         tgt_brw_unlock(ioo, remote_nb, &lockh, LCK_PR);
2352
2353         if (desc && !CFS_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CLIENT_BULK_CB2))
2354                 ptlrpc_free_bulk(desc);
2355
2356         LASSERT(rc <= 0);
2357         if (rc == 0) {
2358                 rc = nob;
2359                 ptlrpc_lprocfs_brw(req, nob);
2360         } else if (no_reply) {
2361                 req->rq_no_reply = 1;
2362                 /* reply out callback would free */
2363                 ptlrpc_req_drop_rs(req);
2364                 LCONSOLE_WARN("%s: Bulk IO read error with %s (at %s), "
2365                               "client will retry: rc %d\n",
2366                               obd_name,
2367                               obd_uuid2str(&exp->exp_client_uuid),
2368                               obd_export_nid2str(exp), rc);
2369         }
2370         /* send a bulk after reply to simulate a network delay or reordering
2371          * by a router - Note that !desc implies short io, so there is no bulk
2372          * to reorder. */
2373         if (unlikely(CFS_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CLIENT_BULK_CB2)) &&
2374             desc) {
2375                 wait_queue_head_t        waitq;
2376                 struct l_wait_info       lwi1;
2377
2378                 CDEBUG(D_INFO, "reorder BULK\n");
2379                 init_waitqueue_head(&waitq);
2380
2381                 lwi1 = LWI_TIMEOUT_INTR(cfs_time_seconds(3), NULL, NULL, NULL);
2382                 l_wait_event(waitq, 0, &lwi1);
2383                 target_bulk_io(exp, desc, &lwi);
2384                 ptlrpc_free_bulk(desc);
2385         }
2386
2387         RETURN(rc);
2388 }
2389 EXPORT_SYMBOL(tgt_brw_read);
2390
2391 static int tgt_shortio2pages(struct niobuf_local *local, int npages,
2392                              unsigned char *buf, unsigned int size)
2393 {
2394         int     i, off, len;
2395         char    *ptr;
2396
2397         for (i = 0; i < npages; i++) {
2398                 off = local[i].lnb_page_offset & ~PAGE_MASK;
2399                 len = local[i].lnb_len;
2400
2401                 if (len == 0)
2402                         continue;
2403
2404                 CDEBUG(D_PAGE, "index %d offset = %d len = %d left = %d\n",
2405                        i, off, len, size);
2406                 ptr = ll_kmap_atomic(local[i].lnb_page, KM_USER0);
2407                 if (ptr == NULL)
2408                         return -EINVAL;
2409                 memcpy(ptr + off, buf, len < size ? len : size);
2410                 ll_kunmap_atomic(ptr, KM_USER0);
2411                 buf += len;
2412                 size -= len;
2413         }
2414         return 0;
2415 }
2416
2417 static void tgt_warn_on_cksum(struct ptlrpc_request *req,
2418                               struct ptlrpc_bulk_desc *desc,
2419                               struct niobuf_local *local_nb, int npages,
2420                               u32 client_cksum, u32 server_cksum,
2421                               bool mmap)
2422 {
2423         struct obd_export *exp = req->rq_export;
2424         struct ost_body *body;
2425         char *router = "";
2426         char *via = "";
2427
2428         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
2429         LASSERT(body != NULL);
2430
2431         if (desc && req->rq_peer.nid != desc->bd_sender) {
2432                 via = " via ";
2433                 router = libcfs_nid2str(desc->bd_sender);
2434         }
2435
2436         if (exp->exp_obd->obd_checksum_dump)
2437                 dump_all_bulk_pages(&body->oa, npages, local_nb, server_cksum,
2438                                     client_cksum);
2439
2440         if (mmap) {
2441                 CDEBUG_LIMIT(D_INFO, "client csum %x, server csum %x\n",
2442                              client_cksum, server_cksum);
2443                 return;
2444         }
2445
2446         LCONSOLE_ERROR_MSG(0x168, "%s: BAD WRITE CHECKSUM: from %s%s%s inode "
2447                            DFID" object "DOSTID" extent [%llu-%llu"
2448                            "]: client csum %x, server csum %x\n",
2449                            exp->exp_obd->obd_name, libcfs_id2str(req->rq_peer),
2450                            via, router,
2451                            body->oa.o_valid & OBD_MD_FLFID ?
2452                            body->oa.o_parent_seq : (__u64)0,
2453                            body->oa.o_valid & OBD_MD_FLFID ?
2454                            body->oa.o_parent_oid : 0,
2455                            body->oa.o_valid & OBD_MD_FLFID ?
2456                            body->oa.o_parent_ver : 0,
2457                            POSTID(&body->oa.o_oi),
2458                            local_nb[0].lnb_file_offset,
2459                            local_nb[npages-1].lnb_file_offset +
2460                            local_nb[npages - 1].lnb_len - 1,
2461                            client_cksum, server_cksum);
2462 }
2463
2464 int tgt_brw_write(struct tgt_session_info *tsi)
2465 {
2466         struct ptlrpc_request   *req = tgt_ses_req(tsi);
2467         struct ptlrpc_bulk_desc *desc = NULL;
2468         struct obd_export       *exp = req->rq_export;
2469         struct niobuf_remote    *remote_nb;
2470         struct niobuf_local     *local_nb;
2471         struct obd_ioobj        *ioo;
2472         struct ost_body         *body, *repbody;
2473         struct l_wait_info       lwi;
2474         struct lustre_handle     lockh = {0};
2475         __u32                   *rcs;
2476         int                      objcount, niocount, npages;
2477         int                      rc, i, j;
2478         enum cksum_types cksum_type = OBD_CKSUM_CRC32;
2479         bool                     no_reply = false, mmap;
2480         struct tgt_thread_big_cache *tbc = req->rq_svc_thread->t_data;
2481         bool wait_sync = false;
2482         const char *obd_name = exp->exp_obd->obd_name;
2483
2484         ENTRY;
2485
2486         if (ptlrpc_req2svc(req)->srv_req_portal != OST_IO_PORTAL &&
2487             ptlrpc_req2svc(req)->srv_req_portal != MDS_IO_PORTAL) {
2488                 CERROR("%s: deny write request from %s to portal %u\n",
2489                        tgt_name(tsi->tsi_tgt),
2490                        obd_export_nid2str(req->rq_export),
2491                        ptlrpc_req2svc(req)->srv_req_portal);
2492                 RETURN(err_serious(-EPROTO));
2493         }
2494
2495         if (OBD_FAIL_CHECK(OBD_FAIL_OST_ENOSPC))
2496                 RETURN(err_serious(-ENOSPC));
2497         if (OBD_FAIL_TIMEOUT(OBD_FAIL_OST_EROFS, 1))
2498                 RETURN(err_serious(-EROFS));
2499
2500         req->rq_bulk_write = 1;
2501
2502         if (OBD_FAIL_CHECK(OBD_FAIL_OST_BRW_WRITE_BULK))
2503                 RETURN(err_serious(-EIO));
2504         if (OBD_FAIL_CHECK(OBD_FAIL_OST_BRW_WRITE_BULK2))
2505                 RETURN(err_serious(-EFAULT));
2506
2507         /* pause before transaction has been started */
2508         CFS_FAIL_TIMEOUT(OBD_FAIL_OST_BRW_PAUSE_BULK, cfs_fail_val > 0 ?
2509                          cfs_fail_val : (obd_timeout + 1) / 4);
2510
2511         /* Delay write commit to show stale size information */
2512         CFS_FAIL_TIMEOUT(OBD_FAIL_OSC_NO_SIZE_DATA, cfs_fail_val);
2513
2514         /* There must be big cache in current thread to process this request
2515          * if it is NULL then something went wrong and it wasn't allocated,
2516          * report -ENOMEM in that case */
2517         if (tbc == NULL)
2518                 RETURN(-ENOMEM);
2519
2520         body = tsi->tsi_ost_body;
2521         LASSERT(body != NULL);
2522
2523         ioo = req_capsule_client_get(&req->rq_pill, &RMF_OBD_IOOBJ);
2524         LASSERT(ioo != NULL); /* must exists after tgt_ost_body_unpack */
2525
2526         objcount = req_capsule_get_size(&req->rq_pill, &RMF_OBD_IOOBJ,
2527                                         RCL_CLIENT) / sizeof(*ioo);
2528
2529         for (niocount = i = 0; i < objcount; i++)
2530                 niocount += ioo[i].ioo_bufcnt;
2531
2532         remote_nb = req_capsule_client_get(&req->rq_pill, &RMF_NIOBUF_REMOTE);
2533         LASSERT(remote_nb != NULL); /* must exists after tgt_ost_body_unpack */
2534         if (niocount != req_capsule_get_size(&req->rq_pill,
2535                                              &RMF_NIOBUF_REMOTE, RCL_CLIENT) /
2536                         sizeof(*remote_nb))
2537                 RETURN(err_serious(-EPROTO));
2538
2539         if ((remote_nb[0].rnb_flags & OBD_BRW_MEMALLOC) &&
2540             ptlrpc_connection_is_local(exp->exp_connection))
2541                 memory_pressure_set();
2542
2543         req_capsule_set_size(&req->rq_pill, &RMF_RCS, RCL_SERVER,
2544                              niocount * sizeof(*rcs));
2545         rc = req_capsule_server_pack(&req->rq_pill);
2546         if (rc != 0)
2547                 GOTO(out, rc = err_serious(rc));
2548
2549         CFS_FAIL_TIMEOUT(OBD_FAIL_OST_BRW_PAUSE_PACK, cfs_fail_val);
2550         rcs = req_capsule_server_get(&req->rq_pill, &RMF_RCS);
2551
2552         local_nb = tbc->local;
2553
2554         rc = tgt_brw_lock(tsi->tsi_env, exp, &tsi->tsi_resid, ioo, remote_nb,
2555                           &lockh, LCK_PW);
2556         if (rc != 0)
2557                 GOTO(out, rc);
2558
2559         /*
2560          * If getting the lock took more time than
2561          * client was willing to wait, drop it. b=11330
2562          */
2563         if (ktime_get_real_seconds() > req->rq_deadline ||
2564             OBD_FAIL_CHECK(OBD_FAIL_OST_DROP_REQ)) {
2565                 no_reply = true;
2566                 CERROR("%s: Dropping timed-out write from %s because locking object " DOSTID " took %lld seconds (limit was %lld).\n",
2567                        tgt_name(tsi->tsi_tgt), libcfs_id2str(req->rq_peer),
2568                        POSTID(&ioo->ioo_oid),
2569                        ktime_get_real_seconds() - req->rq_arrival_time.tv_sec,
2570                        req->rq_deadline - req->rq_arrival_time.tv_sec);
2571                 GOTO(out_lock, rc = -ETIMEDOUT);
2572         }
2573
2574         /* Because we already sync grant info with client when reconnect,
2575          * grant info will be cleared for resent req, then fed_grant and
2576          * total_grant will not be modified in following preprw_write */
2577         if (lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT | MSG_REPLAY)) {
2578                 DEBUG_REQ(D_CACHE, req, "clear resent/replay req grant info");
2579                 body->oa.o_valid &= ~OBD_MD_FLGRANT;
2580         }
2581
2582         repbody = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
2583         if (repbody == NULL)
2584                 GOTO(out_lock, rc = -ENOMEM);
2585         repbody->oa = body->oa;
2586
2587         npages = PTLRPC_MAX_BRW_PAGES;
2588         rc = obd_preprw(tsi->tsi_env, OBD_BRW_WRITE, exp, &repbody->oa,
2589                         objcount, ioo, remote_nb, &npages, local_nb);
2590         if (rc < 0)
2591                 GOTO(out_lock, rc);
2592         if (body->oa.o_valid & OBD_MD_FLFLAGS &&
2593             body->oa.o_flags & OBD_FL_SHORT_IO) {
2594                 unsigned int short_io_size;
2595                 unsigned char *short_io_buf;
2596
2597                 short_io_size = req_capsule_get_size(&req->rq_pill,
2598                                                      &RMF_SHORT_IO,
2599                                                      RCL_CLIENT);
2600                 short_io_buf = req_capsule_client_get(&req->rq_pill,
2601                                                       &RMF_SHORT_IO);
2602                 CDEBUG(D_INFO, "Client use short io for data transfer,"
2603                                " size = %d\n", short_io_size);
2604
2605                 /* Copy short io buf to pages */
2606                 rc = tgt_shortio2pages(local_nb, npages, short_io_buf,
2607                                        short_io_size);
2608                 desc = NULL;
2609         } else {
2610                 desc = ptlrpc_prep_bulk_exp(req, npages, ioobj_max_brw_get(ioo),
2611                                             PTLRPC_BULK_GET_SINK |
2612                                             PTLRPC_BULK_BUF_KIOV,
2613                                             OST_BULK_PORTAL,
2614                                             &ptlrpc_bulk_kiov_nopin_ops);
2615                 if (desc == NULL)
2616                         GOTO(skip_transfer, rc = -ENOMEM);
2617
2618                 /* NB Having prepped, we must commit... */
2619                 for (i = 0; i < npages; i++)
2620                         desc->bd_frag_ops->add_kiov_frag(desc,
2621                                         local_nb[i].lnb_page,
2622                                         local_nb[i].lnb_page_offset & ~PAGE_MASK,
2623                                         local_nb[i].lnb_len);
2624
2625                 rc = sptlrpc_svc_prep_bulk(req, desc);
2626                 if (rc != 0)
2627                         GOTO(skip_transfer, rc);
2628
2629                 rc = target_bulk_io(exp, desc, &lwi);
2630         }
2631
2632         no_reply = rc != 0;
2633
2634 skip_transfer:
2635         if (body->oa.o_valid & OBD_MD_FLCKSUM && rc == 0) {
2636                 static int cksum_counter;
2637
2638                 if (body->oa.o_valid & OBD_MD_FLFLAGS)
2639                         cksum_type = obd_cksum_type_unpack(body->oa.o_flags);
2640
2641                 repbody->oa.o_valid |= OBD_MD_FLCKSUM | OBD_MD_FLFLAGS;
2642                 repbody->oa.o_flags &= ~OBD_FL_CKSUM_ALL;
2643                 repbody->oa.o_flags |= obd_cksum_type_pack(obd_name,
2644                                                            cksum_type);
2645
2646                 rc = tgt_checksum_niobuf_rw(tsi->tsi_tgt, cksum_type,
2647                                             local_nb, npages, OST_WRITE,
2648                                             &repbody->oa.o_cksum);
2649                 if (rc < 0)
2650                         GOTO(out_commitrw, rc);
2651
2652                 cksum_counter++;
2653
2654                 if (unlikely(body->oa.o_cksum != repbody->oa.o_cksum)) {
2655                         mmap = (body->oa.o_valid & OBD_MD_FLFLAGS &&
2656                                 body->oa.o_flags & OBD_FL_MMAP);
2657
2658                         tgt_warn_on_cksum(req, desc, local_nb, npages,
2659                                           body->oa.o_cksum,
2660                                           repbody->oa.o_cksum, mmap);
2661                         cksum_counter = 0;
2662                 } else if ((cksum_counter & (-cksum_counter)) ==
2663                            cksum_counter) {
2664                         CDEBUG(D_INFO, "Checksum %u from %s OK: %x\n",
2665                                cksum_counter, libcfs_id2str(req->rq_peer),
2666                                repbody->oa.o_cksum);
2667                 }
2668         }
2669
2670 out_commitrw:
2671         /* Must commit after prep above in all cases */
2672         rc = obd_commitrw(tsi->tsi_env, OBD_BRW_WRITE, exp, &repbody->oa,
2673                           objcount, ioo, remote_nb, npages, local_nb, rc);
2674         if (rc == -ENOTCONN)
2675                 /* quota acquire process has been given up because
2676                  * either the client has been evicted or the client
2677                  * has timed out the request already */
2678                 no_reply = true;
2679
2680         for (i = 0; i < niocount; i++) {
2681                 if (!(local_nb[i].lnb_flags & OBD_BRW_ASYNC)) {
2682                         wait_sync = true;
2683                         break;
2684                 }
2685         }
2686         /*
2687          * Disable sending mtime back to the client. If the client locked the
2688          * whole object, then it has already updated the mtime on its side,
2689          * otherwise it will have to glimpse anyway (see bug 21489, comment 32)
2690          */
2691         repbody->oa.o_valid &= ~(OBD_MD_FLMTIME | OBD_MD_FLATIME);
2692
2693         if (rc == 0) {
2694                 int nob = 0;
2695
2696                 /* set per-requested niobuf return codes */
2697                 for (i = j = 0; i < niocount; i++) {
2698                         int len = remote_nb[i].rnb_len;
2699
2700                         nob += len;
2701                         rcs[i] = 0;
2702                         do {
2703                                 LASSERT(j < npages);
2704                                 if (local_nb[j].lnb_rc < 0)
2705                                         rcs[i] = local_nb[j].lnb_rc;
2706                                 len -= local_nb[j].lnb_len;
2707                                 j++;
2708                         } while (len > 0);
2709                         LASSERT(len == 0);
2710                 }
2711                 LASSERT(j == npages);
2712                 ptlrpc_lprocfs_brw(req, nob);
2713         }
2714 out_lock:
2715         tgt_brw_unlock(ioo, remote_nb, &lockh, LCK_PW);
2716         if (desc)
2717                 ptlrpc_free_bulk(desc);
2718 out:
2719         if (unlikely(no_reply || (exp->exp_obd->obd_no_transno && wait_sync))) {
2720                 req->rq_no_reply = 1;
2721                 /* reply out callback would free */
2722                 ptlrpc_req_drop_rs(req);
2723                 if (!exp->exp_obd->obd_no_transno)
2724                         LCONSOLE_WARN("%s: Bulk IO write error with %s (at %s),"
2725                                       " client will retry: rc = %d\n",
2726                                       obd_name,
2727                                       obd_uuid2str(&exp->exp_client_uuid),
2728                                       obd_export_nid2str(exp), rc);
2729         }
2730         memory_pressure_clr();
2731         RETURN(rc);
2732 }
2733 EXPORT_SYMBOL(tgt_brw_write);
2734
2735 /* Check if request can be reconstructed from saved reply data
2736  * A copy of the reply data is returned in @trd if the pointer is not NULL
2737  */
2738 bool req_can_reconstruct(struct ptlrpc_request *req,
2739                          struct tg_reply_data *trd)
2740 {
2741         struct tg_export_data *ted = &req->rq_export->exp_target_data;
2742         struct lsd_client_data *lcd = ted->ted_lcd;
2743         bool found;
2744
2745         if (tgt_is_multimodrpcs_client(req->rq_export))
2746                 return tgt_lookup_reply(req, trd);
2747
2748         mutex_lock(&ted->ted_lcd_lock);
2749         found = req->rq_xid == lcd->lcd_last_xid ||
2750                 req->rq_xid == lcd->lcd_last_close_xid;
2751
2752         if (found && trd != NULL) {
2753                 if (lustre_msg_get_opc(req->rq_reqmsg) == MDS_CLOSE) {
2754                         trd->trd_reply.lrd_xid = lcd->lcd_last_close_xid;
2755                         trd->trd_reply.lrd_transno =
2756                                                 lcd->lcd_last_close_transno;
2757                         trd->trd_reply.lrd_result = lcd->lcd_last_close_result;
2758                 } else {
2759                         trd->trd_reply.lrd_xid = lcd->lcd_last_xid;
2760                         trd->trd_reply.lrd_transno = lcd->lcd_last_transno;
2761                         trd->trd_reply.lrd_result = lcd->lcd_last_result;
2762                         trd->trd_reply.lrd_data = lcd->lcd_last_data;
2763                         trd->trd_pre_versions[0] = lcd->lcd_pre_versions[0];
2764                         trd->trd_pre_versions[1] = lcd->lcd_pre_versions[1];
2765                         trd->trd_pre_versions[2] = lcd->lcd_pre_versions[2];
2766                         trd->trd_pre_versions[3] = lcd->lcd_pre_versions[3];
2767                 }
2768         }
2769         mutex_unlock(&ted->ted_lcd_lock);
2770
2771         return found;
2772 }
2773 EXPORT_SYMBOL(req_can_reconstruct);
2774