Whamcloud - gitweb
LU-15245 mdc: GET(X)ATTR to READPAGE portal
[fs/lustre-release.git] / lustre / mdc / mdc_request.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  */
31
32 #define DEBUG_SUBSYSTEM S_MDC
33
34 #include <linux/init.h>
35 #include <linux/kthread.h>
36 #include <linux/module.h>
37 #include <linux/pagemap.h>
38 #include <linux/user_namespace.h>
39 #include <linux/utsname.h>
40 #include <linux/delay.h>
41 #include <linux/uidgid.h>
42 #include <linux/device.h>
43 #include <linux/xarray.h>
44
45 #include <lustre_errno.h>
46
47 #include <cl_object.h>
48 #include <llog_swab.h>
49 #include <lprocfs_status.h>
50 #include <lustre_acl.h>
51 #include <lustre_compat.h>
52 #include <lustre_fid.h>
53 #include <uapi/linux/lustre/lustre_ioctl.h>
54 #include <lustre_kernelcomm.h>
55 #include <lustre_lmv.h>
56 #include <lustre_log.h>
57 #include <lustre_swab.h>
58 #include <obd_class.h>
59 #include <lustre_osc.h>
60
61 #include "mdc_internal.h"
62
63 #define REQUEST_MINOR 244
64
65 static int mdc_cleanup(struct obd_device *obd);
66
67 static inline int mdc_queue_wait(struct ptlrpc_request *req)
68 {
69         struct client_obd *cli = &req->rq_import->imp_obd->u.cli;
70         int rc;
71
72         /* obd_get_request_slot() ensures that this client has no more
73          * than cl_max_rpcs_in_flight RPCs simultaneously inf light
74          * against an MDT. */
75         rc = obd_get_request_slot(cli);
76         if (rc != 0)
77                 return rc;
78
79         rc = ptlrpc_queue_wait(req);
80         obd_put_request_slot(cli);
81
82         return rc;
83 }
84
85 /*
86  * Send MDS_GET_ROOT RPC to fetch root FID.
87  *
88  * If \a fileset is not NULL it should contain a subdirectory off
89  * the ROOT/ directory to be mounted on the client. Return the FID
90  * of the subdirectory to the client to mount onto its mountpoint.
91  *
92  * \param[in]   imp     MDC import
93  * \param[in]   fileset fileset name, which could be NULL
94  * \param[out]  rootfid root FID of this mountpoint
95  * \param[out]  pc      root capa will be unpacked and saved in this pointer
96  *
97  * \retval      0 on success, negative errno on failure
98  */
99 static int mdc_get_root(struct obd_export *exp, const char *fileset,
100                          struct lu_fid *rootfid)
101 {
102         struct ptlrpc_request   *req;
103         struct mdt_body         *body;
104         int                      rc;
105
106         ENTRY;
107
108         if (fileset && !(exp_connect_flags(exp) & OBD_CONNECT_SUBTREE))
109                 RETURN(-ENOTSUPP);
110
111         req = ptlrpc_request_alloc(class_exp2cliimp(exp),
112                                 &RQF_MDS_GET_ROOT);
113         if (req == NULL)
114                 RETURN(-ENOMEM);
115
116         if (fileset != NULL)
117                 req_capsule_set_size(&req->rq_pill, &RMF_NAME, RCL_CLIENT,
118                                      strlen(fileset) + 1);
119         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_GET_ROOT);
120         if (rc) {
121                 ptlrpc_request_free(req);
122                 RETURN(rc);
123         }
124         mdc_pack_body(&req->rq_pill, NULL, 0, 0, -1, 0);
125         if (fileset != NULL) {
126                 char *name = req_capsule_client_get(&req->rq_pill, &RMF_NAME);
127
128                 memcpy(name, fileset, strlen(fileset));
129         }
130         lustre_msg_add_flags(req->rq_reqmsg, LUSTRE_IMP_FULL);
131         req->rq_send_state = LUSTRE_IMP_FULL;
132
133         ptlrpc_request_set_replen(req);
134
135         rc = ptlrpc_queue_wait(req);
136         if (rc)
137                 GOTO(out, rc);
138
139         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
140         if (body == NULL)
141                 GOTO(out, rc = -EPROTO);
142
143         *rootfid = body->mbo_fid1;
144         CDEBUG(D_NET, "root fid="DFID", last_committed=%llu\n",
145                PFID(rootfid), lustre_msg_get_last_committed(req->rq_repmsg));
146         EXIT;
147 out:
148         ptlrpc_req_finished(req);
149
150         return rc;
151 }
152
153 /*
154  * This function now is known to always saying that it will receive 4 buffers
155  * from server. Even for cases when acl_size and md_size is zero, RPC header
156  * will contain 4 fields and RPC itself will contain zero size fields. This is
157  * because mdt_getattr*() _always_ returns 4 fields, but if acl is not needed
158  * and thus zero, it shrinks it, making zero size. The same story about
159  * md_size. And this is course of problem when client waits for smaller number
160  * of fields. This issue will be fixed later when client gets aware of RPC
161  * layouts.  --umka
162  */
163 static int mdc_getattr_common(struct obd_export *exp,
164                               struct ptlrpc_request *req)
165 {
166         struct req_capsule *pill = &req->rq_pill;
167         struct mdt_body    *body;
168         void               *eadata;
169         int                 rc;
170         ENTRY;
171
172         /* Request message already built. */
173         rc = ptlrpc_queue_wait(req);
174         if (rc != 0)
175                 RETURN(rc);
176
177         /* sanity check for the reply */
178         body = req_capsule_server_get(pill, &RMF_MDT_BODY);
179         if (body == NULL)
180                 RETURN(-EPROTO);
181
182         CDEBUG(D_NET, "mode: %o\n", body->mbo_mode);
183
184         mdc_update_max_ea_from_body(exp, body);
185         if (body->mbo_eadatasize != 0) {
186                 eadata = req_capsule_server_sized_get(pill, &RMF_MDT_MD,
187                                                       body->mbo_eadatasize);
188                 if (eadata == NULL)
189                         RETURN(-EPROTO);
190         }
191
192         RETURN(0);
193 }
194
195 static void mdc_reset_acl_req(struct ptlrpc_request *req)
196 {
197         spin_lock(&req->rq_early_free_lock);
198         sptlrpc_cli_free_repbuf(req);
199         req->rq_repbuf = NULL;
200         req->rq_repbuf_len = 0;
201         req->rq_repdata = NULL;
202         req->rq_reqdata_len = 0;
203         spin_unlock(&req->rq_early_free_lock);
204 }
205
206 static int mdc_getattr(struct obd_export *exp, struct md_op_data *op_data,
207                        struct ptlrpc_request **request)
208 {
209         struct ptlrpc_request *req;
210         struct obd_import *imp = class_exp2cliimp(exp);
211         __u32 acl_bufsize = LUSTRE_POSIX_ACL_MAX_SIZE_OLD;
212         int rc;
213         ENTRY;
214
215         /* Single MDS without an LMV case */
216         if (op_data->op_flags & MF_GET_MDT_IDX) {
217                 op_data->op_mds = 0;
218                 RETURN(0);
219         }
220
221         *request = NULL;
222         req = ptlrpc_request_alloc(imp, &RQF_MDS_GETATTR);
223         if (req == NULL)
224                 RETURN(-ENOMEM);
225
226         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_GETATTR);
227         if (rc) {
228                 ptlrpc_request_free(req);
229                 RETURN(rc);
230         }
231
232         /* LU-15245: avoid deadlock with modifying RPCs on MDS_REQUEST_PORTAL */
233         req->rq_request_portal = MDS_READPAGE_PORTAL;
234
235 again:
236         mdc_pack_body(&req->rq_pill, &op_data->op_fid1, op_data->op_valid,
237                       op_data->op_mode, -1, 0);
238         req_capsule_set_size(&req->rq_pill, &RMF_ACL, RCL_SERVER, acl_bufsize);
239         req_capsule_set_size(&req->rq_pill, &RMF_MDT_MD, RCL_SERVER,
240                              op_data->op_mode);
241         ptlrpc_request_set_replen(req);
242
243         rc = mdc_getattr_common(exp, req);
244         if (rc) {
245                 if (rc == -ERANGE) {
246                         acl_bufsize = min_t(__u32,
247                                             imp->imp_connect_data.ocd_max_easize,
248                                             XATTR_SIZE_MAX);
249                         mdc_reset_acl_req(req);
250                         goto again;
251                 }
252
253                 ptlrpc_req_finished(req);
254         } else {
255                 *request = req;
256         }
257
258         RETURN(rc);
259 }
260
261 static int mdc_getattr_name(struct obd_export *exp, struct md_op_data *op_data,
262                             struct ptlrpc_request **request)
263 {
264         struct ptlrpc_request *req;
265         struct obd_import *imp = class_exp2cliimp(exp);
266         __u32 acl_bufsize = LUSTRE_POSIX_ACL_MAX_SIZE_OLD;
267         int rc;
268         ENTRY;
269
270         *request = NULL;
271         req = ptlrpc_request_alloc(imp, &RQF_MDS_GETATTR_NAME);
272         if (req == NULL)
273                 RETURN(-ENOMEM);
274
275         req_capsule_set_size(&req->rq_pill, &RMF_NAME, RCL_CLIENT,
276                              op_data->op_namelen + 1);
277
278         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_GETATTR_NAME);
279         if (rc) {
280                 ptlrpc_request_free(req);
281                 RETURN(rc);
282         }
283
284         if (op_data->op_name) {
285                 char *name = req_capsule_client_get(&req->rq_pill, &RMF_NAME);
286                 LASSERT(strnlen(op_data->op_name, op_data->op_namelen) ==
287                                 op_data->op_namelen);
288                 memcpy(name, op_data->op_name, op_data->op_namelen);
289         }
290
291 again:
292         mdc_pack_body(&req->rq_pill, &op_data->op_fid1, op_data->op_valid,
293                       op_data->op_mode, op_data->op_suppgids[0], 0);
294         req_capsule_set_size(&req->rq_pill, &RMF_MDT_MD, RCL_SERVER,
295                              op_data->op_mode);
296         req_capsule_set_size(&req->rq_pill, &RMF_ACL, RCL_SERVER, acl_bufsize);
297         ptlrpc_request_set_replen(req);
298         if (op_data->op_bias & MDS_FID_OP) {
299                 struct mdt_body *b = req_capsule_client_get(&req->rq_pill,
300                                                             &RMF_MDT_BODY);
301
302                 if (b) {
303                         b->mbo_valid |= OBD_MD_NAMEHASH;
304                         b->mbo_fid2 = op_data->op_fid2;
305                 }
306         }
307
308         rc = mdc_getattr_common(exp, req);
309         if (rc) {
310                 if (rc == -ERANGE) {
311                         acl_bufsize = min_t(__u32,
312                                             imp->imp_connect_data.ocd_max_easize,
313                                             XATTR_SIZE_MAX);
314                         mdc_reset_acl_req(req);
315                         goto again;
316                 }
317
318                 ptlrpc_req_finished(req);
319         } else {
320                 *request = req;
321         }
322
323         RETURN(rc);
324 }
325
326 static int mdc_xattr_common(struct obd_export *exp,const struct req_format *fmt,
327                             const struct lu_fid *fid, int opcode, u64 valid,
328                             const char *xattr_name, const char *input,
329                             int input_size, int output_size, int flags,
330                             __u32 suppgid, struct ptlrpc_request **request)
331 {
332         struct ptlrpc_request *req;
333         int   xattr_namelen = 0;
334         char *tmp;
335         int   rc;
336         ENTRY;
337
338         *request = NULL;
339         req = ptlrpc_request_alloc(class_exp2cliimp(exp), fmt);
340         if (req == NULL)
341                 RETURN(-ENOMEM);
342
343         if (xattr_name) {
344                 xattr_namelen = strlen(xattr_name) + 1;
345                 req_capsule_set_size(&req->rq_pill, &RMF_NAME, RCL_CLIENT,
346                                      xattr_namelen);
347         }
348         if (input_size)
349                 LASSERT(input);
350         req_capsule_set_size(&req->rq_pill, &RMF_EADATA, RCL_CLIENT,
351                              input_size);
352
353         /* get SELinux policy info if any */
354         rc = sptlrpc_get_sepol(req);
355         if (rc < 0) {
356                 ptlrpc_request_free(req);
357                 RETURN(rc);
358         }
359         req_capsule_set_size(&req->rq_pill, &RMF_SELINUX_POL, RCL_CLIENT,
360                              strlen(req->rq_sepol) ?
361                              strlen(req->rq_sepol) + 1 : 0);
362
363         /* Flush local XATTR locks to get rid of a possible cancel RPC */
364         if (opcode == MDS_REINT && fid_is_sane(fid) &&
365             exp->exp_connect_data.ocd_ibits_known & MDS_INODELOCK_XATTR) {
366                 LIST_HEAD(cancels);
367                 int count;
368
369                 /* Without that packing would fail */
370                 if (input_size == 0)
371                         req_capsule_set_size(&req->rq_pill, &RMF_EADATA,
372                                              RCL_CLIENT, 0);
373
374                 count = mdc_resource_get_unused(exp, fid,
375                                                 &cancels, LCK_EX,
376                                                 MDS_INODELOCK_XATTR);
377
378                 rc = mdc_prep_elc_req(exp, req, MDS_REINT, &cancels, count);
379                 if (rc) {
380                         ptlrpc_request_free(req);
381                         RETURN(rc);
382                 }
383         } else {
384                 rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, opcode);
385                 if (rc) {
386                         ptlrpc_request_free(req);
387                         RETURN(rc);
388                 }
389         }
390
391         if (opcode == MDS_REINT) {
392                 struct mdt_rec_setxattr *rec;
393
394                 BUILD_BUG_ON(sizeof(struct mdt_rec_setxattr) !=
395                              sizeof(struct mdt_rec_reint));
396                 rec = req_capsule_client_get(&req->rq_pill, &RMF_REC_REINT);
397                 rec->sx_opcode = REINT_SETXATTR;
398                 rec->sx_fsuid  = from_kuid(&init_user_ns, current_fsuid());
399                 rec->sx_fsgid  = from_kgid(&init_user_ns, current_fsgid());
400                 rec->sx_cap = current_cap().cap[0];
401                 rec->sx_suppgid1 = suppgid;
402                 rec->sx_suppgid2 = -1;
403                 rec->sx_fid    = *fid;
404                 rec->sx_valid  = valid | OBD_MD_FLCTIME;
405                 rec->sx_time   = ktime_get_real_seconds();
406                 rec->sx_size   = output_size;
407                 rec->sx_flags  = flags;
408         } else {
409                 mdc_pack_body(&req->rq_pill, fid, valid, output_size,
410                               suppgid, flags);
411                 /* Avoid deadlock with modifying RPCs on MDS_REQUEST_PORTAL.
412                  * See LU-15245.
413                  */
414                 req->rq_request_portal = MDS_READPAGE_PORTAL;
415         }
416
417         if (xattr_name) {
418                 tmp = req_capsule_client_get(&req->rq_pill, &RMF_NAME);
419                 memcpy(tmp, xattr_name, xattr_namelen);
420         }
421         if (input_size) {
422                 tmp = req_capsule_client_get(&req->rq_pill, &RMF_EADATA);
423                 memcpy(tmp, input, input_size);
424         }
425
426         mdc_file_sepol_pack(&req->rq_pill);
427
428         if (req_capsule_has_field(&req->rq_pill, &RMF_EADATA, RCL_SERVER))
429                 req_capsule_set_size(&req->rq_pill, &RMF_EADATA,
430                                      RCL_SERVER, output_size);
431         ptlrpc_request_set_replen(req);
432
433         /* make rpc */
434         if (opcode == MDS_REINT)
435                 ptlrpc_get_mod_rpc_slot(req);
436
437         rc = ptlrpc_queue_wait(req);
438
439         if (opcode == MDS_REINT)
440                 ptlrpc_put_mod_rpc_slot(req);
441
442         if (rc)
443                 ptlrpc_req_finished(req);
444         else
445                 *request = req;
446         RETURN(rc);
447 }
448
449 static int mdc_setxattr(struct obd_export *exp, const struct lu_fid *fid,
450                         u64 obd_md_valid, const char *name,
451                         const void *value, size_t value_size,
452                         unsigned int xattr_flags, u32 suppgid,
453                         struct ptlrpc_request **req)
454 {
455         LASSERT(obd_md_valid == OBD_MD_FLXATTR ||
456                 obd_md_valid == OBD_MD_FLXATTRRM);
457
458         return mdc_xattr_common(exp, &RQF_MDS_REINT_SETXATTR,
459                                 fid, MDS_REINT, obd_md_valid, name,
460                                 value, value_size, 0, xattr_flags, suppgid,
461                                 req);
462 }
463
464 static int mdc_getxattr(struct obd_export *exp, const struct lu_fid *fid,
465                         u64 obd_md_valid, const char *name, size_t buf_size,
466                         struct ptlrpc_request **req)
467 {
468         struct mdt_body *body;
469         int rc;
470
471         LASSERT(obd_md_valid == OBD_MD_FLXATTR ||
472                 obd_md_valid == OBD_MD_FLXATTRLS);
473
474         /* Message below is checked in sanity-selinux test_20d
475          * and sanity-sec test_49
476          */
477         CDEBUG(D_INFO, "%s: get xattr '%s' for "DFID"\n",
478                exp->exp_obd->obd_name, name, PFID(fid));
479         rc = mdc_xattr_common(exp, &RQF_MDS_GETXATTR, fid, MDS_GETXATTR,
480                               obd_md_valid, name, NULL, 0, buf_size, 0, -1,
481                               req);
482         if (rc < 0)
483                 GOTO(out, rc);
484
485         body = req_capsule_server_get(&(*req)->rq_pill, &RMF_MDT_BODY);
486         if (body == NULL)
487                 GOTO(out, rc = -EPROTO);
488
489         /* only detect the xattr size */
490         if (buf_size == 0) {
491                 /* LU-11109: Older MDTs do not distinguish
492                  * between nonexistent xattrs and zero length
493                  * values in this case. Newer MDTs will return
494                  * -ENODATA or set OBD_MD_FLXATTR. */
495                 GOTO(out, rc = body->mbo_eadatasize);
496         }
497
498         if (body->mbo_eadatasize == 0) {
499                 /* LU-11109: Newer MDTs set OBD_MD_FLXATTR on
500                  * success so that we can distinguish between
501                  * zero length value and nonexistent xattr.
502                  *
503                  * If OBD_MD_FLXATTR is not set then we keep
504                  * the old behavior and return -ENODATA for
505                  * getxattr() when mbo_eadatasize is 0. But
506                  * -ENODATA only makes sense for getxattr()
507                  * and not for listxattr(). */
508                 if (body->mbo_valid & OBD_MD_FLXATTR)
509                         GOTO(out, rc = 0);
510                 else if (obd_md_valid == OBD_MD_FLXATTR)
511                         GOTO(out, rc = -ENODATA);
512                 else
513                         GOTO(out, rc = 0);
514         }
515
516         GOTO(out, rc = body->mbo_eadatasize);
517 out:
518         if (rc < 0) {
519                 ptlrpc_req_finished(*req);
520                 *req = NULL;
521         }
522
523         return rc;
524 }
525
526 static int mdc_get_lustre_md(struct obd_export *exp, struct req_capsule *pill,
527                              struct obd_export *dt_exp,
528                              struct obd_export *md_exp,
529                              struct lustre_md *md)
530 {
531         int rc;
532         ENTRY;
533
534         LASSERT(md);
535         memset(md, 0, sizeof(*md));
536
537         md->body = req_capsule_server_get(pill, &RMF_MDT_BODY);
538         LASSERT(md->body != NULL);
539
540         if (md->body->mbo_valid & OBD_MD_FLEASIZE) {
541                 if (!S_ISREG(md->body->mbo_mode)) {
542                         CDEBUG(D_INFO, "OBD_MD_FLEASIZE set, should be a "
543                                "regular file, but is not\n");
544                         GOTO(out, rc = -EPROTO);
545                 }
546
547                 if (md->body->mbo_eadatasize == 0) {
548                         CDEBUG(D_INFO, "OBD_MD_FLEASIZE set, "
549                                "but eadatasize 0\n");
550                         GOTO(out, rc = -EPROTO);
551                 }
552
553                 md->layout.lb_len = md->body->mbo_eadatasize;
554                 md->layout.lb_buf = req_capsule_server_sized_get(pill,
555                                                         &RMF_MDT_MD,
556                                                         md->layout.lb_len);
557                 if (md->layout.lb_buf == NULL)
558                         GOTO(out, rc = -EPROTO);
559         } else if (md->body->mbo_valid & OBD_MD_FLDIREA) {
560                 const union lmv_mds_md *lmv;
561                 size_t lmv_size;
562
563                 if (!S_ISDIR(md->body->mbo_mode)) {
564                         CDEBUG(D_INFO, "OBD_MD_FLDIREA set, should be a "
565                                "directory, but is not\n");
566                         GOTO(out, rc = -EPROTO);
567                 }
568
569                 if (md_exp->exp_obd->obd_type->typ_lu == &mdc_device_type) {
570                         CERROR("%s: no LMV, upgrading from old version?\n",
571                                md_exp->exp_obd->obd_name);
572
573                         GOTO(out_acl, rc = 0);
574                 }
575
576                 if (md->body->mbo_valid & OBD_MD_MEA) {
577                         lmv_size = md->body->mbo_eadatasize;
578                         if (lmv_size == 0) {
579                                 CDEBUG(D_INFO, "OBD_MD_FLDIREA is set, "
580                                        "but eadatasize 0\n");
581                                 RETURN(-EPROTO);
582                         }
583
584                         lmv = req_capsule_server_sized_get(pill, &RMF_MDT_MD,
585                                                            lmv_size);
586                         if (lmv == NULL)
587                                 GOTO(out, rc = -EPROTO);
588
589                         rc = md_unpackmd(md_exp, &md->lmv, lmv, lmv_size);
590                         if (rc < 0)
591                                 GOTO(out, rc);
592
593                         if (rc < (int)sizeof(*md->lmv)) {
594                                 struct lmv_foreign_md *lfm = md->lfm;
595
596                                 /* short (< sizeof(struct lmv_stripe_md))
597                                  * foreign LMV case
598                                  */
599                                 if (lfm->lfm_magic != LMV_MAGIC_FOREIGN) {
600                                         CDEBUG(D_INFO,
601                                                "lmv size too small: %d < %d\n",
602                                                rc, (int)sizeof(*md->lmv));
603                                         GOTO(out, rc = -EPROTO);
604                                 }
605                         }
606                 }
607
608                 /* since 2.12.58 intent_getattr fetches default LMV */
609                 if (md->body->mbo_valid & OBD_MD_DEFAULT_MEA) {
610                         lmv_size = sizeof(struct lmv_user_md);
611                         lmv = req_capsule_server_sized_get(pill,
612                                                            &RMF_DEFAULT_MDT_MD,
613                                                            lmv_size);
614                         if (!lmv)
615                                 GOTO(out, rc = -EPROTO);
616
617                         rc = md_unpackmd(md_exp, &md->default_lmv, lmv,
618                                          lmv_size);
619                         if (rc < 0)
620                                 GOTO(out, rc);
621
622                         if (rc < (int)sizeof(*md->default_lmv)) {
623                                 CDEBUG(D_INFO,
624                                        "default lmv size too small: %d < %d\n",
625                                         rc, (int)sizeof(*md->default_lmv));
626                                 GOTO(out, rc = -EPROTO);
627                         }
628                 }
629         }
630         rc = 0;
631
632 out_acl:
633         if (md->body->mbo_valid & OBD_MD_FLACL) {
634                 /* for ACL, it's possible that FLACL is set but aclsize is zero.
635                  * only when aclsize != 0 there's an actual segment for ACL
636                  * in reply buffer.
637                  */
638                 rc = mdc_unpack_acl(pill, md);
639                 if (rc)
640                         GOTO(out, rc);
641         }
642
643         EXIT;
644 out:
645         if (rc)
646                 lmd_clear_acl(md);
647
648         return rc;
649 }
650
651 static int mdc_free_lustre_md(struct obd_export *exp, struct lustre_md *md)
652 {
653         ENTRY;
654         RETURN(0);
655 }
656
657 void mdc_replay_open(struct ptlrpc_request *req)
658 {
659         struct md_open_data *mod = req->rq_cb_data;
660         struct ptlrpc_request *close_req;
661         struct obd_client_handle *och;
662         struct lustre_handle old_open_handle = { };
663         struct mdt_body *body;
664         struct ldlm_reply *rep;
665         ENTRY;
666
667         if (mod == NULL) {
668                 DEBUG_REQ(D_ERROR, req,
669                           "cannot properly replay without open data");
670                 EXIT;
671                 return;
672         }
673
674         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
675         LASSERT(body != NULL);
676
677         rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
678         if (rep != NULL && rep->lock_policy_res2 != 0)
679                 DEBUG_REQ(D_ERROR, req, "Open request replay failed with %ld ",
680                         (long int)rep->lock_policy_res2);
681
682         spin_lock(&req->rq_lock);
683         och = mod->mod_och;
684         if (och && och->och_open_handle.cookie)
685                 req->rq_early_free_repbuf = 1;
686         else
687                 req->rq_early_free_repbuf = 0;
688         spin_unlock(&req->rq_lock);
689
690         if (req->rq_early_free_repbuf) {
691                 struct lustre_handle *file_open_handle;
692
693                 LASSERT(och->och_magic == OBD_CLIENT_HANDLE_MAGIC);
694
695                 file_open_handle = &och->och_open_handle;
696                 CDEBUG(D_HA, "updating handle from %#llx to %#llx\n",
697                        file_open_handle->cookie, body->mbo_open_handle.cookie);
698                 old_open_handle = *file_open_handle;
699                 *file_open_handle = body->mbo_open_handle;
700         }
701
702         close_req = mod->mod_close_req;
703         if (close_req) {
704                 __u32 opc = lustre_msg_get_opc(close_req->rq_reqmsg);
705                 struct mdt_ioepoch *epoch;
706
707                 LASSERT(opc == MDS_CLOSE);
708                 epoch = req_capsule_client_get(&close_req->rq_pill,
709                                                &RMF_MDT_EPOCH);
710                 LASSERT(epoch);
711
712                 if (req->rq_early_free_repbuf)
713                         LASSERT(old_open_handle.cookie ==
714                                 epoch->mio_open_handle.cookie);
715
716                 DEBUG_REQ(D_HA, close_req, "updating close body with new fh");
717                 epoch->mio_open_handle = body->mbo_open_handle;
718         }
719         EXIT;
720 }
721
722 void mdc_commit_open(struct ptlrpc_request *req)
723 {
724         struct md_open_data *mod = req->rq_cb_data;
725         if (mod == NULL)
726                 return;
727
728         /**
729          * No need to touch md_open_data::mod_och, it holds a reference on
730          * \var mod and will zero references to each other, \var mod will be
731          * freed after that when md_open_data::mod_och will put the reference.
732          */
733
734         /**
735          * Do not let open request to disappear as it still may be needed
736          * for close rpc to happen (it may happen on evict only, otherwise
737          * ptlrpc_request::rq_replay does not let mdc_commit_open() to be
738          * called), just mark this rpc as committed to distinguish these 2
739          * cases, see mdc_close() for details. The open request reference will
740          * be put along with freeing \var mod.
741          */
742         ptlrpc_request_addref(req);
743         spin_lock(&req->rq_lock);
744         req->rq_committed = 1;
745         spin_unlock(&req->rq_lock);
746         req->rq_cb_data = NULL;
747         obd_mod_put(mod);
748 }
749
750 int mdc_set_open_replay_data(struct obd_export *exp,
751                              struct obd_client_handle *och,
752                              struct lookup_intent *it)
753 {
754         struct md_open_data     *mod;
755         struct mdt_rec_create   *rec;
756         struct mdt_body         *body;
757         struct ptlrpc_request   *open_req = it->it_request;
758         struct obd_import       *imp = open_req->rq_import;
759         ENTRY;
760
761         if (!open_req->rq_replay)
762                 RETURN(0);
763
764         rec = req_capsule_client_get(&open_req->rq_pill, &RMF_REC_REINT);
765         body = req_capsule_server_get(&open_req->rq_pill, &RMF_MDT_BODY);
766         LASSERT(rec != NULL);
767         /* Incoming message in my byte order (it's been swabbed). */
768         /* Outgoing messages always in my byte order. */
769         LASSERT(body != NULL);
770
771         /* Only if the import is replayable, we set replay_open data */
772         if (och && imp->imp_replayable) {
773                 mod = obd_mod_alloc();
774                 if (mod == NULL) {
775                         DEBUG_REQ(D_ERROR, open_req,
776                                   "cannot allocate md_open_data");
777                         RETURN(0);
778                 }
779
780                 /**
781                  * Take a reference on \var mod, to be freed on mdc_close().
782                  * It protects \var mod from being freed on eviction (commit
783                  * callback is called despite rq_replay flag).
784                  * Another reference for \var och.
785                  */
786                 obd_mod_get(mod);
787                 obd_mod_get(mod);
788
789                 spin_lock(&open_req->rq_lock);
790                 och->och_mod = mod;
791                 mod->mod_och = och;
792                 mod->mod_is_create = it_disposition(it, DISP_OPEN_CREATE) ||
793                                      it_disposition(it, DISP_OPEN_STRIPE);
794                 mod->mod_open_req = open_req;
795                 open_req->rq_cb_data = mod;
796                 open_req->rq_commit_cb = mdc_commit_open;
797                 open_req->rq_early_free_repbuf = 1;
798                 spin_unlock(&open_req->rq_lock);
799         }
800
801         rec->cr_fid2 = body->mbo_fid1;
802         rec->cr_open_handle_old = body->mbo_open_handle;
803         open_req->rq_replay_cb = mdc_replay_open;
804         if (!fid_is_sane(&body->mbo_fid1)) {
805                 DEBUG_REQ(D_ERROR, open_req,
806                           "saving replay request with insane FID " DFID,
807                           PFID(&body->mbo_fid1));
808                 LBUG();
809         }
810
811         DEBUG_REQ(D_RPCTRACE, open_req, "Set up open replay data");
812         RETURN(0);
813 }
814
815 static void mdc_free_open(struct md_open_data *mod)
816 {
817         int committed = 0;
818
819         if (mod->mod_is_create == 0 &&
820             imp_connect_disp_stripe(mod->mod_open_req->rq_import))
821                 committed = 1;
822
823         /**
824          * No reason to asssert here if the open request has
825          * rq_replay == 1. It means that mdc_close failed, and
826          * close request wasn`t sent. It is not fatal to client.
827          * The worst thing is eviction if the client gets open lock
828          **/
829
830         DEBUG_REQ(D_RPCTRACE, mod->mod_open_req,
831                   "free open request, rq_replay=%d",
832                   mod->mod_open_req->rq_replay);
833
834         ptlrpc_request_committed(mod->mod_open_req, committed);
835         if (mod->mod_close_req)
836                 ptlrpc_request_committed(mod->mod_close_req, committed);
837 }
838
839 static int mdc_clear_open_replay_data(struct obd_export *exp,
840                                       struct obd_client_handle *och)
841 {
842         struct md_open_data *mod = och->och_mod;
843         ENTRY;
844
845         /**
846          * It is possible to not have \var mod in a case of eviction between
847          * lookup and ll_file_open().
848          **/
849         if (mod == NULL)
850                 RETURN(0);
851
852         LASSERT(mod != LP_POISON);
853         LASSERT(mod->mod_open_req != NULL);
854
855         spin_lock(&mod->mod_open_req->rq_lock);
856         if (mod->mod_och)
857                 mod->mod_och->och_open_handle.cookie = 0;
858         mod->mod_open_req->rq_early_free_repbuf = 0;
859         spin_unlock(&mod->mod_open_req->rq_lock);
860         mdc_free_open(mod);
861
862         mod->mod_och = NULL;
863         och->och_mod = NULL;
864         obd_mod_put(mod);
865
866         RETURN(0);
867 }
868
869 static int mdc_close(struct obd_export *exp, struct md_op_data *op_data,
870                      struct md_open_data *mod, struct ptlrpc_request **request)
871 {
872         struct obd_device     *obd = class_exp2obd(exp);
873         struct ptlrpc_request *req;
874         struct req_format     *req_fmt;
875         size_t                 u32_count = 0;
876         int                    rc;
877         int                    saved_rc = 0;
878         ENTRY;
879
880         CDEBUG(D_INODE, "%s: "DFID" file closed with intent: %x\n",
881                exp->exp_obd->obd_name, PFID(&op_data->op_fid1),
882                op_data->op_bias);
883
884         if (op_data->op_bias & MDS_CLOSE_INTENT) {
885                 req_fmt = &RQF_MDS_CLOSE_INTENT;
886                 if (op_data->op_bias & MDS_HSM_RELEASE) {
887                         /* allocate a FID for volatile file */
888                         rc = mdc_fid_alloc(NULL, exp, &op_data->op_fid2,
889                                            op_data);
890                         if (rc < 0) {
891                                 CERROR("%s: "DFID" allocating FID: rc = %d\n",
892                                        obd->obd_name, PFID(&op_data->op_fid1),
893                                        rc);
894                                 /* save the errcode and proceed to close */
895                                 saved_rc = rc;
896                         }
897                 }
898                 if (op_data->op_bias & MDS_CLOSE_RESYNC_DONE) {
899                         size_t count = op_data->op_data_size / sizeof(__u32);
900
901                         if (count > INLINE_RESYNC_ARRAY_SIZE)
902                                 u32_count = count;
903                 }
904         } else {
905                 req_fmt = &RQF_MDS_CLOSE;
906         }
907
908         *request = NULL;
909         if (OBD_FAIL_CHECK(OBD_FAIL_MDC_CLOSE))
910                 req = NULL;
911         else
912                 req = ptlrpc_request_alloc(class_exp2cliimp(exp), req_fmt);
913
914         /* Ensure that this close's handle is fixed up during replay. */
915         if (likely(mod != NULL)) {
916                 LASSERTF(mod->mod_open_req != NULL &&
917                          mod->mod_open_req->rq_type != LI_POISON,
918                          "POISONED open %p!\n", mod->mod_open_req);
919
920                 mod->mod_close_req = req;
921
922                 DEBUG_REQ(D_RPCTRACE, mod->mod_open_req, "matched open");
923                 /* We no longer want to preserve this open for replay even
924                  * though the open was committed. b=3632, b=3633 */
925                 spin_lock(&mod->mod_open_req->rq_lock);
926                 mod->mod_open_req->rq_replay = 0;
927                 spin_unlock(&mod->mod_open_req->rq_lock);
928         } else {
929                 CDEBUG(D_HA, "couldn't find open req; expecting close error\n");
930         }
931         if (req == NULL) {
932                 /**
933                  * TODO: repeat close after errors
934                  */
935                 CWARN("%s: close of FID "DFID" failed, file reference will be "
936                       "dropped when this client unmounts or is evicted\n",
937                       obd->obd_name, PFID(&op_data->op_fid1));
938                 GOTO(out, rc = -ENOMEM);
939         }
940
941         if (u32_count > 0)
942                 req_capsule_set_size(&req->rq_pill, &RMF_U32, RCL_CLIENT,
943                                      u32_count * sizeof(__u32));
944
945         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_CLOSE);
946         if (rc) {
947                 ptlrpc_request_free(req);
948                 req = NULL;
949                 GOTO(out, rc);
950         }
951
952         /* To avoid a livelock (bug 7034), we need to send CLOSE RPCs to a
953          * portal whose threads are not taking any DLM locks and are therefore
954          * always progressing */
955         req->rq_request_portal = MDS_READPAGE_PORTAL;
956         ptlrpc_at_set_req_timeout(req);
957
958         if (!obd->u.cli.cl_lsom_update ||
959             !(exp_connect_flags2(exp) & OBD_CONNECT2_LSOM))
960                 op_data->op_xvalid &= ~(OP_XVALID_LAZYSIZE |
961                                         OP_XVALID_LAZYBLOCKS);
962
963         mdc_close_pack(&req->rq_pill, op_data);
964
965         req_capsule_set_size(&req->rq_pill, &RMF_MDT_MD, RCL_SERVER,
966                              obd->u.cli.cl_default_mds_easize);
967
968         ptlrpc_request_set_replen(req);
969
970         ptlrpc_get_mod_rpc_slot(req);
971         rc = ptlrpc_queue_wait(req);
972         ptlrpc_put_mod_rpc_slot(req);
973
974         if (req->rq_repmsg == NULL) {
975                 CDEBUG(D_RPCTRACE, "request %p failed to send: rc = %d\n", req,
976                        req->rq_status);
977                 if (rc == 0)
978                         rc = req->rq_status ?: -EIO;
979         } else if (rc == 0 || rc == -EAGAIN) {
980                 struct mdt_body *body;
981
982                 rc = lustre_msg_get_status(req->rq_repmsg);
983                 if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR) {
984                         DEBUG_REQ(D_ERROR, req,
985                                   "type = PTL_RPC_MSG_ERR: rc = %d", rc);
986                         if (rc > 0)
987                                 rc = -rc;
988                 }
989                 body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
990                 if (body == NULL)
991                         rc = -EPROTO;
992         } else if (rc == -ESTALE) {
993                 /**
994                  * it can be allowed error after 3633 if open was committed and
995                  * server failed before close was sent. Let's check if mod
996                  * exists and return no error in that case
997                  */
998                 if (mod) {
999                         DEBUG_REQ(D_HA, req, "Reset ESTALE = %d", rc);
1000                         LASSERT(mod->mod_open_req != NULL);
1001                         if (mod->mod_open_req->rq_committed)
1002                                 rc = 0;
1003                 }
1004         }
1005
1006 out:
1007         if (mod) {
1008                 if (rc != 0)
1009                         mod->mod_close_req = NULL;
1010                 /* Since now, mod is accessed through open_req only,
1011                  * thus close req does not keep a reference on mod anymore. */
1012                 obd_mod_put(mod);
1013         }
1014         *request = req;
1015
1016         RETURN(rc < 0 ? rc : saved_rc);
1017 }
1018
1019 static int mdc_getpage(struct obd_export *exp, const struct lu_fid *fid,
1020                        u64 offset, struct page **pages, int npages,
1021                        struct ptlrpc_request **request)
1022 {
1023         struct ptlrpc_request   *req;
1024         struct ptlrpc_bulk_desc *desc;
1025         int                      i;
1026         int                      resends = 0;
1027         int                      rc;
1028         ENTRY;
1029
1030         *request = NULL;
1031
1032 restart_bulk:
1033         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_MDS_READPAGE);
1034         if (req == NULL)
1035                 RETURN(-ENOMEM);
1036
1037         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_READPAGE);
1038         if (rc) {
1039                 ptlrpc_request_free(req);
1040                 RETURN(rc);
1041         }
1042
1043         req->rq_request_portal = MDS_READPAGE_PORTAL;
1044         ptlrpc_at_set_req_timeout(req);
1045
1046         desc = ptlrpc_prep_bulk_imp(req, npages, 1,
1047                                     PTLRPC_BULK_PUT_SINK,
1048                                     MDS_BULK_PORTAL,
1049                                     &ptlrpc_bulk_kiov_pin_ops);
1050         if (desc == NULL) {
1051                 ptlrpc_req_finished(req);
1052                 RETURN(-ENOMEM);
1053         }
1054
1055         /* NB req now owns desc and will free it when it gets freed */
1056         for (i = 0; i < npages; i++)
1057                 desc->bd_frag_ops->add_kiov_frag(desc, pages[i], 0,
1058                                                  PAGE_SIZE);
1059
1060         mdc_readdir_pack(&req->rq_pill, offset, PAGE_SIZE * npages, fid);
1061
1062         ptlrpc_request_set_replen(req);
1063         rc = ptlrpc_queue_wait(req);
1064         if (rc) {
1065                 ptlrpc_req_finished(req);
1066                 if (rc != -ETIMEDOUT)
1067                         RETURN(rc);
1068
1069                 resends++;
1070                 if (!client_should_resend(resends, &exp->exp_obd->u.cli)) {
1071                         CERROR("%s: too many resend retries: rc = %d\n",
1072                                exp->exp_obd->obd_name, -EIO);
1073                         RETURN(-EIO);
1074                 }
1075
1076                 /* If a signal interrupts then the timeout returned will
1077                  * not be zero. In that case return -EINTR
1078                  */
1079                 if (msleep_interruptible(resends * 1000))
1080                         RETURN(-EINTR);
1081
1082                 goto restart_bulk;
1083         }
1084
1085         rc = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk,
1086                                           req->rq_bulk->bd_nob_transferred);
1087         if (rc < 0) {
1088                 ptlrpc_req_finished(req);
1089                 RETURN(rc);
1090         }
1091
1092         if (req->rq_bulk->bd_nob_transferred & ~LU_PAGE_MASK) {
1093                 CERROR("%s: unexpected bytes transferred: %d (%ld expected)\n",
1094                        exp->exp_obd->obd_name, req->rq_bulk->bd_nob_transferred,
1095                        PAGE_SIZE * npages);
1096                 ptlrpc_req_finished(req);
1097                 RETURN(-EPROTO);
1098         }
1099
1100         *request = req;
1101         RETURN(0);
1102 }
1103
1104 static void mdc_release_page(struct page *page, int remove)
1105 {
1106         if (remove) {
1107                 lock_page(page);
1108                 if (likely(page->mapping != NULL))
1109                         delete_from_page_cache(page);
1110                 unlock_page(page);
1111         }
1112         put_page(page);
1113 }
1114
1115 static struct page *mdc_page_locate(struct address_space *mapping, __u64 *hash,
1116                                     __u64 *start, __u64 *end, int hash64)
1117 {
1118         /*
1119          * Complement of hash is used as an index so that
1120          * radix_tree_gang_lookup() can be used to find a page with starting
1121          * hash _smaller_ than one we are looking for.
1122          */
1123         unsigned long offset = hash_x_index(*hash, hash64);
1124         struct page *page;
1125         unsigned long flags;
1126         int found;
1127
1128         ll_xa_lock_irqsave(&mapping->i_pages, flags);
1129         found = radix_tree_gang_lookup(&mapping->page_tree,
1130                                        (void **)&page, offset, 1);
1131         if (found > 0 && !ll_xa_is_value(page)) {
1132                 struct lu_dirpage *dp;
1133
1134                 get_page(page);
1135                 ll_xa_unlock_irqrestore(&mapping->i_pages, flags);
1136                 /*
1137                  * In contrast to find_lock_page() we are sure that directory
1138                  * page cannot be truncated (while DLM lock is held) and,
1139                  * hence, can avoid restart.
1140                  *
1141                  * In fact, page cannot be locked here at all, because
1142                  * mdc_read_page_remote does synchronous io.
1143                  */
1144                 wait_on_page_locked(page);
1145                 if (PageUptodate(page)) {
1146                         dp = kmap(page);
1147                         if (BITS_PER_LONG == 32 && hash64) {
1148                                 *start = le64_to_cpu(dp->ldp_hash_start) >> 32;
1149                                 *end   = le64_to_cpu(dp->ldp_hash_end) >> 32;
1150                                 *hash  = *hash >> 32;
1151                         } else {
1152                                 *start = le64_to_cpu(dp->ldp_hash_start);
1153                                 *end   = le64_to_cpu(dp->ldp_hash_end);
1154                         }
1155                         if (unlikely(*start == 1 && *hash == 0))
1156                                 *hash = *start;
1157                         else
1158                                 LASSERTF(*start <= *hash, "start = %#llx"
1159                                          ",end = %#llx,hash = %#llx\n",
1160                                          *start, *end, *hash);
1161                         CDEBUG(D_VFSTRACE, "offset %lx [%#llx %#llx],"
1162                               " hash %#llx\n", offset, *start, *end, *hash);
1163                         if (*hash > *end) {
1164                                 kunmap(page);
1165                                 mdc_release_page(page, 0);
1166                                 page = NULL;
1167                         } else if (*end != *start && *hash == *end) {
1168                                 /*
1169                                  * upon hash collision, remove this page,
1170                                  * otherwise put page reference, and
1171                                  * mdc_read_page_remote() will issue RPC to
1172                                  * fetch the page we want.
1173                                  */
1174                                 kunmap(page);
1175                                 mdc_release_page(page,
1176                                     le32_to_cpu(dp->ldp_flags) & LDF_COLLIDE);
1177                                 page = NULL;
1178                         }
1179                 } else {
1180                         put_page(page);
1181                         page = ERR_PTR(-EIO);
1182                 }
1183         } else {
1184                 ll_xa_unlock_irqrestore(&mapping->i_pages, flags);
1185                 page = NULL;
1186         }
1187         return page;
1188 }
1189
1190 /*
1191  * Adjust a set of pages, each page containing an array of lu_dirpages,
1192  * so that each page can be used as a single logical lu_dirpage.
1193  *
1194  * A lu_dirpage is laid out as follows, where s = ldp_hash_start,
1195  * e = ldp_hash_end, f = ldp_flags, p = padding, and each "ent" is a
1196  * struct lu_dirent.  It has size up to LU_PAGE_SIZE. The ldp_hash_end
1197  * value is used as a cookie to request the next lu_dirpage in a
1198  * directory listing that spans multiple pages (two in this example):
1199  *   ________
1200  *  |        |
1201  * .|--------v-------   -----.
1202  * |s|e|f|p|ent|ent| ... |ent|
1203  * '--|--------------   -----'   Each PAGE contains a single
1204  *    '------.                   lu_dirpage.
1205  * .---------v-------   -----.
1206  * |s|e|f|p|ent| 0 | ... | 0 |
1207  * '-----------------   -----'
1208  *
1209  * However, on hosts where the native VM page size (PAGE_SIZE) is
1210  * larger than LU_PAGE_SIZE, a single host page may contain multiple
1211  * lu_dirpages. After reading the lu_dirpages from the MDS, the
1212  * ldp_hash_end of the first lu_dirpage refers to the one immediately
1213  * after it in the same PAGE (arrows simplified for brevity, but
1214  * in general e0==s1, e1==s2, etc.):
1215  *
1216  * .--------------------   -----.
1217  * |s0|e0|f0|p|ent|ent| ... |ent|
1218  * |---v----------------   -----|
1219  * |s1|e1|f1|p|ent|ent| ... |ent|
1220  * |---v----------------   -----|  Here, each PAGE contains
1221  *             ...                 multiple lu_dirpages.
1222  * |---v----------------   -----|
1223  * |s'|e'|f'|p|ent|ent| ... |ent|
1224  * '---|----------------   -----'
1225  *     v
1226  * .----------------------------.
1227  * |        next PAGE           |
1228  *
1229  * This structure is transformed into a single logical lu_dirpage as follows:
1230  *
1231  * - Replace e0 with e' so the request for the next lu_dirpage gets the page
1232  *   labeled 'next PAGE'.
1233  *
1234  * - Copy the LDF_COLLIDE flag from f' to f0 to correctly reflect whether
1235  *   a hash collision with the next page exists.
1236  *
1237  * - Adjust the lde_reclen of the ending entry of each lu_dirpage to span
1238  *   to the first entry of the next lu_dirpage.
1239  */
1240 #if PAGE_SIZE > LU_PAGE_SIZE
1241 static void mdc_adjust_dirpages(struct page **pages, int cfs_pgs, int lu_pgs)
1242 {
1243         int i;
1244
1245         for (i = 0; i < cfs_pgs; i++) {
1246                 struct lu_dirpage *dp = kmap(pages[i]);
1247                 struct lu_dirpage *first = dp;
1248                 struct lu_dirent *end_dirent = NULL;
1249                 struct lu_dirent *ent;
1250                 __u64 hash_end = dp->ldp_hash_end;
1251                 __u32 flags = dp->ldp_flags;
1252
1253                 while (--lu_pgs > 0) {
1254                         ent = lu_dirent_start(dp);
1255                         for (end_dirent = ent; ent != NULL;
1256                              end_dirent = ent, ent = lu_dirent_next(ent));
1257
1258                         /* Advance dp to next lu_dirpage. */
1259                         dp = (struct lu_dirpage *)((char *)dp + LU_PAGE_SIZE);
1260
1261                         /* Check if we've reached the end of the PAGE. */
1262                         if (!((unsigned long)dp & ~PAGE_MASK))
1263                                 break;
1264
1265                         /* Save the hash and flags of this lu_dirpage. */
1266                         hash_end = dp->ldp_hash_end;
1267                         flags = dp->ldp_flags;
1268
1269                         /* Check if lu_dirpage contains no entries. */
1270                         if (end_dirent == NULL)
1271                                 break;
1272
1273                         /* Enlarge the end entry lde_reclen from 0 to
1274                          * first entry of next lu_dirpage. */
1275                         LASSERT(le16_to_cpu(end_dirent->lde_reclen) == 0);
1276                         end_dirent->lde_reclen =
1277                                 cpu_to_le16((char *)(dp->ldp_entries) -
1278                                             (char *)end_dirent);
1279                 }
1280
1281                 first->ldp_hash_end = hash_end;
1282                 first->ldp_flags &= ~cpu_to_le32(LDF_COLLIDE);
1283                 first->ldp_flags |= flags & cpu_to_le32(LDF_COLLIDE);
1284
1285                 kunmap(pages[i]);
1286         }
1287         LASSERTF(lu_pgs == 0, "left = %d\n", lu_pgs);
1288 }
1289 #else
1290 #define mdc_adjust_dirpages(pages, cfs_pgs, lu_pgs) do {} while (0)
1291 #endif  /* PAGE_SIZE > LU_PAGE_SIZE */
1292
1293 /* parameters for readdir page */
1294 struct readpage_param {
1295         struct md_op_data       *rp_mod;
1296         __u64                   rp_off;
1297         int                     rp_hash64;
1298         struct obd_export       *rp_exp;
1299 };
1300
1301 /**
1302  * Read pages from server.
1303  *
1304  * Page in MDS_READPAGE RPC is packed in LU_PAGE_SIZE, and each page contains
1305  * a header lu_dirpage which describes the start/end hash, and whether this
1306  * page is empty (contains no dir entry) or hash collide with next page.
1307  * After client receives reply, several pages will be integrated into dir page
1308  * in PAGE_SIZE (if PAGE_SIZE greater than LU_PAGE_SIZE), and the
1309  * lu_dirpage for this integrated page will be adjusted.
1310  **/
1311 static int mdc_read_page_remote(void *data, struct page *page0)
1312 {
1313         struct readpage_param *rp = data;
1314         struct page **page_pool;
1315         struct page *page;
1316         struct lu_dirpage *dp;
1317         struct md_op_data *op_data = rp->rp_mod;
1318         struct ptlrpc_request *req;
1319         int max_pages;
1320         struct inode *inode;
1321         struct lu_fid *fid;
1322         int rd_pgs = 0; /* number of pages actually read */
1323         int npages;
1324         int i;
1325         int rc;
1326         ENTRY;
1327
1328         max_pages = rp->rp_exp->exp_obd->u.cli.cl_max_pages_per_rpc;
1329         inode = op_data->op_data;
1330         fid = &op_data->op_fid1;
1331         LASSERT(inode != NULL);
1332
1333         OBD_ALLOC_PTR_ARRAY_LARGE(page_pool, max_pages);
1334         if (page_pool != NULL) {
1335                 page_pool[0] = page0;
1336         } else {
1337                 page_pool = &page0;
1338                 max_pages = 1;
1339         }
1340
1341         for (npages = 1; npages < max_pages; npages++) {
1342                 page = page_cache_alloc(inode->i_mapping);
1343                 if (page == NULL)
1344                         break;
1345                 page_pool[npages] = page;
1346         }
1347
1348         rc = mdc_getpage(rp->rp_exp, fid, rp->rp_off, page_pool, npages, &req);
1349         if (rc < 0) {
1350                 /* page0 is special, which was added into page cache early */
1351                 delete_from_page_cache(page0);
1352         } else {
1353                 int lu_pgs;
1354
1355                 rd_pgs = (req->rq_bulk->bd_nob_transferred + PAGE_SIZE - 1) >>
1356                         PAGE_SHIFT;
1357                 lu_pgs = req->rq_bulk->bd_nob_transferred >> LU_PAGE_SHIFT;
1358                 LASSERT(!(req->rq_bulk->bd_nob_transferred & ~LU_PAGE_MASK));
1359
1360                 CDEBUG(D_INODE, "read %d(%d) pages\n", rd_pgs, lu_pgs);
1361
1362                 mdc_adjust_dirpages(page_pool, rd_pgs, lu_pgs);
1363
1364                 SetPageUptodate(page0);
1365         }
1366         unlock_page(page0);
1367
1368         ptlrpc_req_finished(req);
1369         CDEBUG(D_CACHE, "read %d/%d pages\n", rd_pgs, npages);
1370         for (i = 1; i < npages; i++) {
1371                 unsigned long   offset;
1372                 __u64           hash;
1373                 int ret;
1374
1375                 page = page_pool[i];
1376
1377                 if (rc < 0 || i >= rd_pgs) {
1378                         put_page(page);
1379                         continue;
1380                 }
1381
1382                 SetPageUptodate(page);
1383
1384                 dp = kmap(page);
1385                 hash = le64_to_cpu(dp->ldp_hash_start);
1386                 kunmap(page);
1387
1388                 offset = hash_x_index(hash, rp->rp_hash64);
1389
1390                 prefetchw(&page->flags);
1391                 ret = add_to_page_cache_lru(page, inode->i_mapping, offset,
1392                                             GFP_KERNEL);
1393                 if (ret == 0)
1394                         unlock_page(page);
1395                 else
1396                         CDEBUG(D_VFSTRACE, "page %lu add to page cache failed:"
1397                                " rc = %d\n", offset, ret);
1398                 put_page(page);
1399         }
1400
1401         if (page_pool != &page0)
1402                 OBD_FREE_PTR_ARRAY_LARGE(page_pool, max_pages);
1403
1404         RETURN(rc);
1405 }
1406
1407 /**
1408  * Read dir page from cache first, if it can not find it, read it from
1409  * server and add into the cache.
1410  *
1411  * \param[in] exp       MDC export
1412  * \param[in] op_data   client MD stack parameters, transfering parameters
1413  *                      between different layers on client MD stack.
1414  * \param[in] mrinfo    callback required for ldlm lock enqueue during
1415  *                      read page
1416  * \param[in] hash_offset the hash offset of the page to be read
1417  * \param[in] ppage     the page to be read
1418  *
1419  * retval               = 0 get the page successfully
1420  *                      errno(<0) get the page failed
1421  */
1422 static int mdc_read_page(struct obd_export *exp, struct md_op_data *op_data,
1423                          struct md_readdir_info *mrinfo, __u64 hash_offset,
1424                          struct page **ppage)
1425 {
1426         struct lookup_intent    it = { .it_op = IT_READDIR };
1427         struct page             *page;
1428         struct inode            *dir = op_data->op_data;
1429         struct address_space    *mapping;
1430         struct lu_dirpage       *dp;
1431         __u64                   start = 0;
1432         __u64                   end = 0;
1433         struct lustre_handle    lockh;
1434         struct ptlrpc_request   *enq_req = NULL;
1435         struct readpage_param   rp_param;
1436         int rc;
1437
1438         ENTRY;
1439
1440         *ppage = NULL;
1441
1442         LASSERT(dir != NULL);
1443         mapping = dir->i_mapping;
1444
1445         rc = mdc_intent_lock(exp, op_data, &it, &enq_req,
1446                              mrinfo->mr_blocking_ast, 0);
1447         if (enq_req != NULL)
1448                 ptlrpc_req_finished(enq_req);
1449
1450         if (rc < 0) {
1451                 CERROR("%s: "DFID" lock enqueue fails: rc = %d\n",
1452                        exp->exp_obd->obd_name, PFID(&op_data->op_fid1), rc);
1453                 RETURN(rc);
1454         }
1455
1456         rc = 0;
1457         lockh.cookie = it.it_lock_handle;
1458         mdc_set_lock_data(exp, &lockh, dir, NULL);
1459
1460         rp_param.rp_off = hash_offset;
1461         rp_param.rp_hash64 = op_data->op_cli_flags & CLI_HASH64;
1462         page = mdc_page_locate(mapping, &rp_param.rp_off, &start, &end,
1463                                rp_param.rp_hash64);
1464         if (IS_ERR(page)) {
1465                 CERROR("%s: dir page locate: "DFID" at %llu: rc %ld\n",
1466                        exp->exp_obd->obd_name, PFID(&op_data->op_fid1),
1467                        rp_param.rp_off, PTR_ERR(page));
1468                 GOTO(out_unlock, rc = PTR_ERR(page));
1469         } else if (page != NULL) {
1470                 /*
1471                  * XXX nikita: not entirely correct handling of a corner case:
1472                  * suppose hash chain of entries with hash value HASH crosses
1473                  * border between pages P0 and P1. First both P0 and P1 are
1474                  * cached, seekdir() is called for some entry from the P0 part
1475                  * of the chain. Later P0 goes out of cache. telldir(HASH)
1476                  * happens and finds P1, as it starts with matching hash
1477                  * value. Remaining entries from P0 part of the chain are
1478                  * skipped. (Is that really a bug?)
1479                  *
1480                  * Possible solutions: 0. don't cache P1 is such case, handle
1481                  * it as an "overflow" page. 1. invalidate all pages at
1482                  * once. 2. use HASH|1 as an index for P1.
1483                  */
1484                 GOTO(hash_collision, page);
1485         }
1486
1487         rp_param.rp_exp = exp;
1488         rp_param.rp_mod = op_data;
1489         page = read_cache_page(mapping,
1490                                hash_x_index(rp_param.rp_off,
1491                                             rp_param.rp_hash64),
1492                                mdc_read_page_remote, &rp_param);
1493         if (IS_ERR(page)) {
1494                 CDEBUG(D_INFO, "%s: read cache page: "DFID" at %llu: %ld\n",
1495                        exp->exp_obd->obd_name, PFID(&op_data->op_fid1),
1496                        rp_param.rp_off, PTR_ERR(page));
1497                 GOTO(out_unlock, rc = PTR_ERR(page));
1498         }
1499
1500         wait_on_page_locked(page);
1501         (void)kmap(page);
1502         if (!PageUptodate(page)) {
1503                 CERROR("%s: page not updated: "DFID" at %llu: rc %d\n",
1504                        exp->exp_obd->obd_name, PFID(&op_data->op_fid1),
1505                        rp_param.rp_off, -5);
1506                 goto fail;
1507         }
1508         if (!PageChecked(page))
1509                 SetPageChecked(page);
1510         if (PageError(page)) {
1511                 CERROR("%s: page error: "DFID" at %llu: rc %d\n",
1512                        exp->exp_obd->obd_name, PFID(&op_data->op_fid1),
1513                        rp_param.rp_off, -5);
1514                 goto fail;
1515         }
1516
1517 hash_collision:
1518         dp = page_address(page);
1519         if (BITS_PER_LONG == 32 && rp_param.rp_hash64) {
1520                 start = le64_to_cpu(dp->ldp_hash_start) >> 32;
1521                 end   = le64_to_cpu(dp->ldp_hash_end) >> 32;
1522                 rp_param.rp_off = hash_offset >> 32;
1523         } else {
1524                 start = le64_to_cpu(dp->ldp_hash_start);
1525                 end   = le64_to_cpu(dp->ldp_hash_end);
1526                 rp_param.rp_off = hash_offset;
1527         }
1528         if (end == start) {
1529                 LASSERT(start == rp_param.rp_off);
1530                 CWARN("Page-wide hash collision: %#lx\n", (unsigned long)end);
1531 #if BITS_PER_LONG == 32
1532                 CWARN("Real page-wide hash collision at [%llu %llu] with "
1533                       "hash %llu\n", le64_to_cpu(dp->ldp_hash_start),
1534                       le64_to_cpu(dp->ldp_hash_end), hash_offset);
1535 #endif
1536
1537                 /*
1538                  * Fetch whole overflow chain...
1539                  *
1540                  * XXX not yet.
1541                  */
1542                 goto fail;
1543         }
1544         *ppage = page;
1545 out_unlock:
1546         ldlm_lock_decref(&lockh, it.it_lock_mode);
1547         return rc;
1548 fail:
1549         kunmap(page);
1550         mdc_release_page(page, 1);
1551         rc = -EIO;
1552         goto out_unlock;
1553 }
1554
1555 static int mdc_statfs_interpret(const struct lu_env *env,
1556                                 struct ptlrpc_request *req, void *args, int rc)
1557 {
1558         struct obd_info *oinfo = args;
1559         struct obd_statfs *osfs;
1560
1561         if (!rc) {
1562                 osfs = req_capsule_server_get(&req->rq_pill, &RMF_OBD_STATFS);
1563                 if (!osfs)
1564                         return -EPROTO;
1565
1566                 oinfo->oi_osfs = osfs;
1567
1568                 CDEBUG(D_CACHE, "blocks=%llu free=%llu avail=%llu "
1569                        "objects=%llu free=%llu state=%x\n",
1570                         osfs->os_blocks, osfs->os_bfree, osfs->os_bavail,
1571                         osfs->os_files, osfs->os_ffree, osfs->os_state);
1572         }
1573
1574         oinfo->oi_cb_up(oinfo, rc);
1575
1576         return rc;
1577 }
1578
1579 static int mdc_statfs_async(struct obd_export *exp,
1580                             struct obd_info *oinfo, time64_t max_age,
1581                             struct ptlrpc_request_set *unused)
1582 {
1583         struct ptlrpc_request *req;
1584         struct obd_info *aa;
1585
1586         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp), &RQF_MDS_STATFS,
1587                                         LUSTRE_MDS_VERSION, MDS_STATFS);
1588         if (req == NULL)
1589                 return -ENOMEM;
1590
1591         ptlrpc_request_set_replen(req);
1592         req->rq_interpret_reply = mdc_statfs_interpret;
1593
1594         aa = ptlrpc_req_async_args(aa, req);
1595         *aa = *oinfo;
1596
1597         ptlrpcd_add_req(req);
1598
1599         return 0;
1600 }
1601
1602 static int mdc_statfs(const struct lu_env *env,
1603                       struct obd_export *exp, struct obd_statfs *osfs,
1604                       time64_t max_age, __u32 flags)
1605 {
1606         struct obd_device *obd = class_exp2obd(exp);
1607         struct req_format *fmt;
1608         struct ptlrpc_request *req;
1609         struct obd_statfs *msfs;
1610         struct obd_import *imp, *imp0;
1611         int rc;
1612         ENTRY;
1613
1614         /*
1615          * Since the request might also come from lprocfs, so we need
1616          * sync this with client_disconnect_export Bug15684
1617          */
1618         with_imp_locked(obd, imp0, rc)
1619                 imp = class_import_get(imp0);
1620         if (rc)
1621                 RETURN(rc);
1622
1623         fmt = &RQF_MDS_STATFS;
1624         if ((exp_connect_flags2(exp) & OBD_CONNECT2_SUM_STATFS) &&
1625             (flags & OBD_STATFS_SUM))
1626                 fmt = &RQF_MDS_STATFS_NEW;
1627         req = ptlrpc_request_alloc_pack(imp, fmt, LUSTRE_MDS_VERSION,
1628                                         MDS_STATFS);
1629         if (req == NULL)
1630                 GOTO(output, rc = -ENOMEM);
1631         req->rq_allow_intr = 1;
1632
1633         if ((flags & OBD_STATFS_SUM) &&
1634             (exp_connect_flags2(exp) & OBD_CONNECT2_SUM_STATFS)) {
1635                 /* request aggregated states */
1636                 struct mdt_body *body;
1637
1638                 body = req_capsule_client_get(&req->rq_pill, &RMF_MDT_BODY);
1639                 if (body == NULL)
1640                         GOTO(out, rc = -EPROTO);
1641                 body->mbo_valid = OBD_MD_FLAGSTATFS;
1642         }
1643
1644         ptlrpc_request_set_replen(req);
1645
1646         if (flags & OBD_STATFS_NODELAY) {
1647                 /* procfs requests not want stay in wait for avoid deadlock */
1648                 req->rq_no_resend = 1;
1649                 req->rq_no_delay = 1;
1650         }
1651
1652         rc = ptlrpc_queue_wait(req);
1653         if (rc) {
1654                 /* check connection error first */
1655                 if (imp->imp_connect_error)
1656                         rc = imp->imp_connect_error;
1657                 GOTO(out, rc);
1658         }
1659
1660         msfs = req_capsule_server_get(&req->rq_pill, &RMF_OBD_STATFS);
1661         if (msfs == NULL)
1662                 GOTO(out, rc = -EPROTO);
1663
1664         *osfs = *msfs;
1665         EXIT;
1666 out:
1667         ptlrpc_req_finished(req);
1668 output:
1669         class_import_put(imp);
1670         return rc;
1671 }
1672
1673 static int mdc_ioc_fid2path(struct obd_export *exp, struct getinfo_fid2path *gf)
1674 {
1675         __u32 keylen, vallen;
1676         void *key;
1677         int rc;
1678
1679         if (gf->gf_pathlen > PATH_MAX)
1680                 RETURN(-ENAMETOOLONG);
1681         if (gf->gf_pathlen < 2)
1682                 RETURN(-EOVERFLOW);
1683
1684         /* Key is KEY_FID2PATH + getinfo_fid2path description */
1685         keylen = cfs_size_round(sizeof(KEY_FID2PATH) + sizeof(*gf) +
1686                                 sizeof(struct lu_fid));
1687         OBD_ALLOC(key, keylen);
1688         if (key == NULL)
1689                 RETURN(-ENOMEM);
1690         memcpy(key, KEY_FID2PATH, sizeof(KEY_FID2PATH));
1691         memcpy(key + cfs_size_round(sizeof(KEY_FID2PATH)), gf, sizeof(*gf));
1692         memcpy(key + cfs_size_round(sizeof(KEY_FID2PATH)) + sizeof(*gf),
1693                gf->gf_u.gf_root_fid, sizeof(struct lu_fid));
1694         CDEBUG(D_IOCTL, "path get "DFID" from %llu #%d\n",
1695                PFID(&gf->gf_fid), gf->gf_recno, gf->gf_linkno);
1696
1697         if (!fid_is_sane(&gf->gf_fid))
1698                 GOTO(out, rc = -EINVAL);
1699
1700         /* Val is struct getinfo_fid2path result plus path */
1701         vallen = sizeof(*gf) + gf->gf_pathlen;
1702
1703         rc = obd_get_info(NULL, exp, keylen, key, &vallen, gf);
1704         if (rc != 0 && rc != -EREMOTE)
1705                 GOTO(out, rc);
1706
1707         if (vallen <= sizeof(*gf))
1708                 GOTO(out, rc = -EPROTO);
1709         if (vallen > sizeof(*gf) + gf->gf_pathlen)
1710                 GOTO(out, rc = -EOVERFLOW);
1711
1712         CDEBUG(D_IOCTL, "path got "DFID" from %llu #%d: %s\n",
1713                PFID(&gf->gf_fid), gf->gf_recno, gf->gf_linkno,
1714                gf->gf_pathlen < 512 ? gf->gf_u.gf_path :
1715                /* only log the last 512 characters of the path */
1716                gf->gf_u.gf_path + gf->gf_pathlen - 512);
1717
1718 out:
1719         OBD_FREE(key, keylen);
1720         return rc;
1721 }
1722
1723 static int mdc_ioc_hsm_progress(struct obd_export *exp,
1724                                 struct hsm_progress_kernel *hpk)
1725 {
1726         struct obd_import               *imp = class_exp2cliimp(exp);
1727         struct hsm_progress_kernel      *req_hpk;
1728         struct ptlrpc_request           *req;
1729         int                              rc;
1730         ENTRY;
1731
1732         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_HSM_PROGRESS,
1733                                         LUSTRE_MDS_VERSION, MDS_HSM_PROGRESS);
1734         if (req == NULL)
1735                 GOTO(out, rc = -ENOMEM);
1736
1737         mdc_pack_body(&req->rq_pill, NULL, 0, 0, -1, 0);
1738
1739         /* Copy hsm_progress struct */
1740         req_hpk = req_capsule_client_get(&req->rq_pill, &RMF_MDS_HSM_PROGRESS);
1741         if (req_hpk == NULL)
1742                 GOTO(out, rc = -EPROTO);
1743
1744         *req_hpk = *hpk;
1745         req_hpk->hpk_errval = lustre_errno_hton(hpk->hpk_errval);
1746
1747         ptlrpc_request_set_replen(req);
1748
1749         ptlrpc_get_mod_rpc_slot(req);
1750         rc = ptlrpc_queue_wait(req);
1751         ptlrpc_put_mod_rpc_slot(req);
1752
1753         GOTO(out, rc);
1754 out:
1755         ptlrpc_req_finished(req);
1756         return rc;
1757 }
1758 /**
1759  * Send hsm_ct_register to MDS
1760  *
1761  * \param[in]   imp             import
1762  * \param[in]   archive_count   if in bitmap format, it is the bitmap,
1763  *                              else it is the count of archive_ids
1764  * \param[in]   archives        if in bitmap format, it is NULL,
1765  *                              else it is archive_id lists
1766  */
1767 static int mdc_ioc_hsm_ct_register(struct obd_import *imp, __u32 archive_count,
1768                                    __u32 *archives)
1769 {
1770         struct ptlrpc_request *req;
1771         __u32 *archive_array;
1772         size_t archives_size;
1773         int rc;
1774         ENTRY;
1775
1776         req = ptlrpc_request_alloc(imp, &RQF_MDS_HSM_CT_REGISTER);
1777         if (req == NULL)
1778                 RETURN(-ENOMEM);
1779
1780         if (archives != NULL)
1781                 archives_size = sizeof(*archive_array) * archive_count;
1782         else
1783                 archives_size = sizeof(archive_count);
1784
1785         req_capsule_set_size(&req->rq_pill, &RMF_MDS_HSM_ARCHIVE,
1786                              RCL_CLIENT, archives_size);
1787
1788         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_HSM_CT_REGISTER);
1789         if (rc) {
1790                 ptlrpc_request_free(req);
1791                 RETURN(-ENOMEM);
1792         }
1793
1794         mdc_pack_body(&req->rq_pill, NULL, 0, 0, -1, 0);
1795
1796         archive_array = req_capsule_client_get(&req->rq_pill,
1797                                                &RMF_MDS_HSM_ARCHIVE);
1798         if (archive_array == NULL)
1799                 GOTO(out, rc = -EPROTO);
1800
1801         if (archives != NULL)
1802                 memcpy(archive_array, archives, archives_size);
1803         else
1804                 *archive_array = archive_count;
1805
1806         ptlrpc_request_set_replen(req);
1807         req->rq_no_resend = 1;
1808
1809         rc = mdc_queue_wait(req);
1810         GOTO(out, rc);
1811 out:
1812         ptlrpc_req_finished(req);
1813         return rc;
1814 }
1815
1816 static int mdc_ioc_hsm_current_action(struct obd_export *exp,
1817                                       struct md_op_data *op_data)
1818 {
1819         struct hsm_current_action       *hca = op_data->op_data;
1820         struct hsm_current_action       *req_hca;
1821         struct ptlrpc_request           *req;
1822         int                              rc;
1823         ENTRY;
1824
1825         req = ptlrpc_request_alloc(class_exp2cliimp(exp),
1826                                    &RQF_MDS_HSM_ACTION);
1827         if (req == NULL)
1828                 RETURN(-ENOMEM);
1829
1830         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_HSM_ACTION);
1831         if (rc) {
1832                 ptlrpc_request_free(req);
1833                 RETURN(rc);
1834         }
1835
1836         mdc_pack_body(&req->rq_pill, &op_data->op_fid1, 0, 0,
1837                       op_data->op_suppgids[0], 0);
1838
1839         ptlrpc_request_set_replen(req);
1840
1841         rc = mdc_queue_wait(req);
1842         if (rc)
1843                 GOTO(out, rc);
1844
1845         req_hca = req_capsule_server_get(&req->rq_pill,
1846                                          &RMF_MDS_HSM_CURRENT_ACTION);
1847         if (req_hca == NULL)
1848                 GOTO(out, rc = -EPROTO);
1849
1850         *hca = *req_hca;
1851
1852         EXIT;
1853 out:
1854         ptlrpc_req_finished(req);
1855         return rc;
1856 }
1857
1858 static int mdc_ioc_hsm_ct_unregister(struct obd_import *imp)
1859 {
1860         struct ptlrpc_request   *req;
1861         int                      rc;
1862         ENTRY;
1863
1864         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_HSM_CT_UNREGISTER,
1865                                         LUSTRE_MDS_VERSION,
1866                                         MDS_HSM_CT_UNREGISTER);
1867         if (req == NULL)
1868                 GOTO(out, rc = -ENOMEM);
1869
1870         mdc_pack_body(&req->rq_pill, NULL, 0, 0, -1, 0);
1871
1872         ptlrpc_request_set_replen(req);
1873
1874         rc = mdc_queue_wait(req);
1875         GOTO(out, rc);
1876 out:
1877         ptlrpc_req_finished(req);
1878         return rc;
1879 }
1880
1881 static int mdc_ioc_hsm_state_get(struct obd_export *exp,
1882                                  struct md_op_data *op_data)
1883 {
1884         struct hsm_user_state   *hus = op_data->op_data;
1885         struct hsm_user_state   *req_hus;
1886         struct ptlrpc_request   *req;
1887         int                      rc;
1888         ENTRY;
1889
1890         req = ptlrpc_request_alloc(class_exp2cliimp(exp),
1891                                    &RQF_MDS_HSM_STATE_GET);
1892         if (req == NULL)
1893                 RETURN(-ENOMEM);
1894
1895         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_HSM_STATE_GET);
1896         if (rc != 0) {
1897                 ptlrpc_request_free(req);
1898                 RETURN(rc);
1899         }
1900
1901         mdc_pack_body(&req->rq_pill, &op_data->op_fid1, 0, 0,
1902                       op_data->op_suppgids[0], 0);
1903
1904         ptlrpc_request_set_replen(req);
1905
1906         rc = mdc_queue_wait(req);
1907         if (rc)
1908                 GOTO(out, rc);
1909
1910         req_hus = req_capsule_server_get(&req->rq_pill, &RMF_HSM_USER_STATE);
1911         if (req_hus == NULL)
1912                 GOTO(out, rc = -EPROTO);
1913
1914         *hus = *req_hus;
1915
1916         EXIT;
1917 out:
1918         ptlrpc_req_finished(req);
1919         return rc;
1920 }
1921
1922 static int mdc_ioc_hsm_state_set(struct obd_export *exp,
1923                                  struct md_op_data *op_data)
1924 {
1925         struct hsm_state_set    *hss = op_data->op_data;
1926         struct hsm_state_set    *req_hss;
1927         struct ptlrpc_request   *req;
1928         int                      rc;
1929         ENTRY;
1930
1931         req = ptlrpc_request_alloc(class_exp2cliimp(exp),
1932                                    &RQF_MDS_HSM_STATE_SET);
1933         if (req == NULL)
1934                 RETURN(-ENOMEM);
1935
1936         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_HSM_STATE_SET);
1937         if (rc) {
1938                 ptlrpc_request_free(req);
1939                 RETURN(rc);
1940         }
1941
1942         mdc_pack_body(&req->rq_pill, &op_data->op_fid1, 0, 0,
1943                       op_data->op_suppgids[0], 0);
1944
1945         /* Copy states */
1946         req_hss = req_capsule_client_get(&req->rq_pill, &RMF_HSM_STATE_SET);
1947         if (req_hss == NULL)
1948                 GOTO(out, rc = -EPROTO);
1949         *req_hss = *hss;
1950
1951         ptlrpc_request_set_replen(req);
1952
1953         ptlrpc_get_mod_rpc_slot(req);
1954         rc = ptlrpc_queue_wait(req);
1955         ptlrpc_put_mod_rpc_slot(req);
1956
1957         GOTO(out, rc);
1958 out:
1959         ptlrpc_req_finished(req);
1960         return rc;
1961 }
1962
1963 static int mdc_ioc_hsm_request(struct obd_export *exp,
1964                                struct hsm_user_request *hur)
1965 {
1966         struct obd_import       *imp = class_exp2cliimp(exp);
1967         struct ptlrpc_request   *req;
1968         struct hsm_request      *req_hr;
1969         struct hsm_user_item    *req_hui;
1970         char                    *req_opaque;
1971         int                      rc;
1972         ENTRY;
1973
1974         req = ptlrpc_request_alloc(imp, &RQF_MDS_HSM_REQUEST);
1975         if (req == NULL)
1976                 GOTO(out, rc = -ENOMEM);
1977
1978         req_capsule_set_size(&req->rq_pill, &RMF_MDS_HSM_USER_ITEM, RCL_CLIENT,
1979                              hur->hur_request.hr_itemcount
1980                              * sizeof(struct hsm_user_item));
1981         req_capsule_set_size(&req->rq_pill, &RMF_GENERIC_DATA, RCL_CLIENT,
1982                              hur->hur_request.hr_data_len);
1983
1984         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_HSM_REQUEST);
1985         if (rc) {
1986                 ptlrpc_request_free(req);
1987                 RETURN(rc);
1988         }
1989
1990         mdc_pack_body(&req->rq_pill, NULL, 0, 0, -1, 0);
1991
1992         /* Copy hsm_request struct */
1993         req_hr = req_capsule_client_get(&req->rq_pill, &RMF_MDS_HSM_REQUEST);
1994         if (req_hr == NULL)
1995                 GOTO(out, rc = -EPROTO);
1996         *req_hr = hur->hur_request;
1997
1998         /* Copy hsm_user_item structs */
1999         req_hui = req_capsule_client_get(&req->rq_pill, &RMF_MDS_HSM_USER_ITEM);
2000         if (req_hui == NULL)
2001                 GOTO(out, rc = -EPROTO);
2002         memcpy(req_hui, hur->hur_user_item,
2003                hur->hur_request.hr_itemcount * sizeof(struct hsm_user_item));
2004
2005         /* Copy opaque field */
2006         req_opaque = req_capsule_client_get(&req->rq_pill, &RMF_GENERIC_DATA);
2007         if (req_opaque == NULL)
2008                 GOTO(out, rc = -EPROTO);
2009         memcpy(req_opaque, hur_data(hur), hur->hur_request.hr_data_len);
2010
2011         ptlrpc_request_set_replen(req);
2012
2013         ptlrpc_get_mod_rpc_slot(req);
2014         rc = ptlrpc_queue_wait(req);
2015         ptlrpc_put_mod_rpc_slot(req);
2016
2017         GOTO(out, rc);
2018
2019 out:
2020         ptlrpc_req_finished(req);
2021         return rc;
2022 }
2023
2024 static int mdc_ioc_hsm_ct_start(struct obd_export *exp,
2025                                 struct lustre_kernelcomm *lk);
2026
2027 static int mdc_quotactl(struct obd_device *unused, struct obd_export *exp,
2028                         struct obd_quotactl *oqctl)
2029 {
2030         struct ptlrpc_request *req;
2031         struct obd_quotactl *oqc;
2032         int rc;
2033         ENTRY;
2034
2035         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_MDS_QUOTACTL);
2036         if (req == NULL)
2037                 RETURN(-ENOMEM);
2038
2039
2040         if (LUSTRE_Q_CMD_IS_POOL(oqctl->qc_cmd))
2041                 req_capsule_set_size(&req->rq_pill,
2042                                      &RMF_OBD_QUOTACTL,
2043                                      RCL_CLIENT,
2044                                      sizeof(*oqc) + LOV_MAXPOOLNAME + 1);
2045
2046         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION,
2047                                  MDS_QUOTACTL);
2048         if (rc) {
2049                 ptlrpc_request_free(req);
2050                 RETURN(rc);
2051         }
2052
2053         oqc = req_capsule_client_get(&req->rq_pill, &RMF_OBD_QUOTACTL);
2054         QCTL_COPY(oqc, oqctl);
2055
2056         ptlrpc_request_set_replen(req);
2057         ptlrpc_at_set_req_timeout(req);
2058
2059         rc = ptlrpc_queue_wait(req);
2060         if (rc) {
2061                 CERROR("%s: ptlrpc_queue_wait failed: rc = %d\n",
2062                        exp->exp_obd->obd_name, rc);
2063                 GOTO(out, rc);
2064         }
2065
2066         if (req->rq_repmsg &&
2067             (oqc = req_capsule_server_get(&req->rq_pill, &RMF_OBD_QUOTACTL))) {
2068                 QCTL_COPY(oqctl, oqc);
2069         } else if (!rc) {
2070                 rc = -EPROTO;
2071                 CERROR("%s: cannot unpack obd_quotactl: rc = %d\n",
2072                         exp->exp_obd->obd_name, rc);
2073         }
2074 out:
2075         ptlrpc_req_finished(req);
2076
2077         RETURN(rc);
2078 }
2079
2080 static int mdc_ioc_swap_layouts(struct obd_export *exp,
2081                                 struct md_op_data *op_data)
2082 {
2083         LIST_HEAD(cancels);
2084         struct ptlrpc_request   *req;
2085         int                      rc, count;
2086         struct mdc_swap_layouts *msl, *payload;
2087         ENTRY;
2088
2089         msl = op_data->op_data;
2090
2091         /* When the MDT will get the MDS_SWAP_LAYOUTS RPC the
2092          * first thing it will do is to cancel the 2 layout
2093          * locks held by this client.
2094          * So the client must cancel its layout locks on the 2 fids
2095          * with the request RPC to avoid extra RPC round trips.
2096          */
2097         count = mdc_resource_get_unused(exp, &op_data->op_fid1, &cancels,
2098                                         LCK_EX, MDS_INODELOCK_LAYOUT |
2099                                         MDS_INODELOCK_XATTR);
2100         count += mdc_resource_get_unused(exp, &op_data->op_fid2, &cancels,
2101                                          LCK_EX, MDS_INODELOCK_LAYOUT |
2102                                          MDS_INODELOCK_XATTR);
2103
2104         req = ptlrpc_request_alloc(class_exp2cliimp(exp),
2105                                    &RQF_MDS_SWAP_LAYOUTS);
2106         if (req == NULL) {
2107                 ldlm_lock_list_put(&cancels, l_bl_ast, count);
2108                 RETURN(-ENOMEM);
2109         }
2110
2111         rc = mdc_prep_elc_req(exp, req, MDS_SWAP_LAYOUTS, &cancels, count);
2112         if (rc) {
2113                 ptlrpc_request_free(req);
2114                 RETURN(rc);
2115         }
2116
2117         mdc_swap_layouts_pack(&req->rq_pill, op_data);
2118
2119         payload = req_capsule_client_get(&req->rq_pill, &RMF_SWAP_LAYOUTS);
2120         LASSERT(payload);
2121
2122         *payload = *msl;
2123
2124         ptlrpc_request_set_replen(req);
2125
2126         rc = ptlrpc_queue_wait(req);
2127         if (rc)
2128                 GOTO(out, rc);
2129         EXIT;
2130
2131 out:
2132         ptlrpc_req_finished(req);
2133         return rc;
2134 }
2135
2136 static int mdc_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
2137                          void *karg, void __user *uarg)
2138 {
2139         struct obd_device *obd = exp->exp_obd;
2140         struct obd_ioctl_data *data = karg;
2141         struct obd_import *imp = obd->u.cli.cl_import;
2142         int rc;
2143         ENTRY;
2144
2145         if (!try_module_get(THIS_MODULE)) {
2146                 CERROR("%s: cannot get module '%s'\n", obd->obd_name,
2147                        module_name(THIS_MODULE));
2148                 return -EINVAL;
2149         }
2150         switch (cmd) {
2151         case OBD_IOC_FID2PATH:
2152                 rc = mdc_ioc_fid2path(exp, karg);
2153                 GOTO(out, rc);
2154         case LL_IOC_HSM_CT_START:
2155                 rc = mdc_ioc_hsm_ct_start(exp, karg);
2156                 /* ignore if it was already registered on this MDS. */
2157                 if (rc == -EEXIST)
2158                         rc = 0;
2159                 GOTO(out, rc);
2160         case LL_IOC_HSM_PROGRESS:
2161                 rc = mdc_ioc_hsm_progress(exp, karg);
2162                 GOTO(out, rc);
2163         case LL_IOC_HSM_STATE_GET:
2164                 rc = mdc_ioc_hsm_state_get(exp, karg);
2165                 GOTO(out, rc);
2166         case LL_IOC_HSM_STATE_SET:
2167                 rc = mdc_ioc_hsm_state_set(exp, karg);
2168                 GOTO(out, rc);
2169         case LL_IOC_HSM_ACTION:
2170                 rc = mdc_ioc_hsm_current_action(exp, karg);
2171                 GOTO(out, rc);
2172         case LL_IOC_HSM_REQUEST:
2173                 rc = mdc_ioc_hsm_request(exp, karg);
2174                 GOTO(out, rc);
2175         case OBD_IOC_CLIENT_RECOVER:
2176                 rc = ptlrpc_recover_import(imp, data->ioc_inlbuf1, 0);
2177                 if (rc < 0)
2178                         GOTO(out, rc);
2179                 GOTO(out, rc = 0);
2180         case IOC_OSC_SET_ACTIVE:
2181                 rc = ptlrpc_set_import_active(imp, data->ioc_offset);
2182                 GOTO(out, rc);
2183         /*
2184          * Normally IOC_OBD_STATFS, OBD_IOC_QUOTACTL iocontrol are handled by
2185          * LMV instead of MDC. But when the cluster is upgraded from 1.8,
2186          * there'd be no LMV layer thus we might be called here. Eventually
2187          * this code should be removed.
2188          * bz20731, LU-592.
2189          */
2190         case IOC_OBD_STATFS: {
2191                 struct obd_statfs stat_buf = {0};
2192
2193                 if (*((__u32 *) data->ioc_inlbuf2) != 0)
2194                         GOTO(out, rc = -ENODEV);
2195
2196                 /* copy UUID */
2197                 if (copy_to_user(data->ioc_pbuf2, obd2cli_tgt(obd),
2198                                  min((int)data->ioc_plen2,
2199                                      (int)sizeof(struct obd_uuid))))
2200                         GOTO(out, rc = -EFAULT);
2201
2202                 rc = mdc_statfs(NULL, obd->obd_self_export, &stat_buf,
2203                                 ktime_get_seconds() - OBD_STATFS_CACHE_SECONDS,
2204                                 0);
2205                 if (rc != 0)
2206                         GOTO(out, rc);
2207
2208                 if (copy_to_user(data->ioc_pbuf1, &stat_buf,
2209                                      min((int) data->ioc_plen1,
2210                                          (int) sizeof(stat_buf))))
2211                         GOTO(out, rc = -EFAULT);
2212
2213                 GOTO(out, rc = 0);
2214         }
2215         case OBD_IOC_QUOTACTL: {
2216                 struct if_quotactl *qctl = karg;
2217                 struct obd_quotactl *oqctl;
2218
2219                 OBD_ALLOC_PTR(oqctl);
2220                 if (oqctl == NULL)
2221                         GOTO(out, rc = -ENOMEM);
2222
2223                 QCTL_COPY(oqctl, qctl);
2224                 rc = obd_quotactl(exp, oqctl);
2225                 if (rc == 0) {
2226                         QCTL_COPY(qctl, oqctl);
2227                         qctl->qc_valid = QC_MDTIDX;
2228                         qctl->obd_uuid = obd->u.cli.cl_target_uuid;
2229                 }
2230
2231                 OBD_FREE_PTR(oqctl);
2232                 GOTO(out, rc);
2233         }
2234         case LL_IOC_GET_CONNECT_FLAGS:
2235                 if (copy_to_user(uarg, exp_connect_flags_ptr(exp),
2236                                  sizeof(*exp_connect_flags_ptr(exp))))
2237                         GOTO(out, rc = -EFAULT);
2238
2239                 GOTO(out, rc = 0);
2240         case LL_IOC_LOV_SWAP_LAYOUTS:
2241                 rc = mdc_ioc_swap_layouts(exp, karg);
2242                 GOTO(out, rc);
2243         default:
2244                 CERROR("unrecognised ioctl: cmd = %#x\n", cmd);
2245                 GOTO(out, rc = -ENOTTY);
2246         }
2247 out:
2248         module_put(THIS_MODULE);
2249
2250         return rc;
2251 }
2252
2253 static int mdc_get_info_rpc(struct obd_export *exp,
2254                             u32 keylen, void *key,
2255                             u32 vallen, void *val)
2256 {
2257         struct obd_import      *imp = class_exp2cliimp(exp);
2258         struct ptlrpc_request  *req;
2259         char                   *tmp;
2260         int                     rc = -EINVAL;
2261         ENTRY;
2262
2263         req = ptlrpc_request_alloc(imp, &RQF_MDS_GET_INFO);
2264         if (req == NULL)
2265                 RETURN(-ENOMEM);
2266
2267         req_capsule_set_size(&req->rq_pill, &RMF_GETINFO_KEY,
2268                              RCL_CLIENT, keylen);
2269         req_capsule_set_size(&req->rq_pill, &RMF_GETINFO_VALLEN,
2270                              RCL_CLIENT, sizeof(vallen));
2271
2272         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_GET_INFO);
2273         if (rc) {
2274                 ptlrpc_request_free(req);
2275                 RETURN(rc);
2276         }
2277
2278         tmp = req_capsule_client_get(&req->rq_pill, &RMF_GETINFO_KEY);
2279         memcpy(tmp, key, keylen);
2280         tmp = req_capsule_client_get(&req->rq_pill, &RMF_GETINFO_VALLEN);
2281         memcpy(tmp, &vallen, sizeof(vallen));
2282
2283         req_capsule_set_size(&req->rq_pill, &RMF_GETINFO_VAL,
2284                              RCL_SERVER, vallen);
2285         ptlrpc_request_set_replen(req);
2286
2287         /* if server failed to resolve FID, and OI scrub not able to fix it, it
2288          * will return -EINPROGRESS, ptlrpc_queue_wait() will keep retrying,
2289          * set request interruptible to avoid deadlock.
2290          */
2291         if (KEY_IS(KEY_FID2PATH))
2292                 req->rq_allow_intr = 1;
2293
2294         rc = ptlrpc_queue_wait(req);
2295         /* -EREMOTE means the get_info result is partial, and it needs to
2296          * continue on another MDT, see fid2path part in lmv_iocontrol */
2297         if (rc == 0 || rc == -EREMOTE) {
2298                 tmp = req_capsule_server_get(&req->rq_pill, &RMF_GETINFO_VAL);
2299                 memcpy(val, tmp, vallen);
2300                 if (req_capsule_rep_need_swab(&req->rq_pill)) {
2301                         if (KEY_IS(KEY_FID2PATH))
2302                                 lustre_swab_fid2path(val);
2303                 }
2304         }
2305         ptlrpc_req_finished(req);
2306
2307         RETURN(rc);
2308 }
2309
2310 static void lustre_swab_hai(struct hsm_action_item *h)
2311 {
2312         __swab32s(&h->hai_len);
2313         __swab32s(&h->hai_action);
2314         lustre_swab_lu_fid(&h->hai_fid);
2315         lustre_swab_lu_fid(&h->hai_dfid);
2316         __swab64s(&h->hai_cookie);
2317         __swab64s(&h->hai_extent.offset);
2318         __swab64s(&h->hai_extent.length);
2319         __swab64s(&h->hai_gid);
2320 }
2321
2322 static void lustre_swab_hal(struct hsm_action_list *h)
2323 {
2324         struct hsm_action_item  *hai;
2325         __u32                    i;
2326
2327         __swab32s(&h->hal_version);
2328         __swab32s(&h->hal_count);
2329         __swab32s(&h->hal_archive_id);
2330         __swab64s(&h->hal_flags);
2331         hai = hai_first(h);
2332         for (i = 0; i < h->hal_count; i++, hai = hai_next(hai))
2333                 lustre_swab_hai(hai);
2334 }
2335
2336 static void lustre_swab_kuch(struct kuc_hdr *l)
2337 {
2338         __swab16s(&l->kuc_magic);
2339         /* __u8 l->kuc_transport */
2340         __swab16s(&l->kuc_msgtype);
2341         __swab16s(&l->kuc_msglen);
2342 }
2343
2344 static int mdc_ioc_hsm_ct_start(struct obd_export *exp,
2345                                 struct lustre_kernelcomm *lk)
2346 {
2347         struct obd_import *imp = class_exp2cliimp(exp);
2348         int rc = 0;
2349
2350         if (lk->lk_group != KUC_GRP_HSM) {
2351                 CERROR("Bad copytool group %d\n", lk->lk_group);
2352                 return -EINVAL;
2353         }
2354
2355         CDEBUG(D_HSM, "CT start r%d w%d u%d g%d f%#x\n", lk->lk_rfd, lk->lk_wfd,
2356                lk->lk_uid, lk->lk_group, lk->lk_flags);
2357
2358         if (lk->lk_flags & LK_FLG_STOP) {
2359                 /* Unregister with the coordinator */
2360                 rc = mdc_ioc_hsm_ct_unregister(imp);
2361         } else {
2362                 __u32 *archives = NULL;
2363
2364                 if ((lk->lk_flags & LK_FLG_DATANR) && lk->lk_data_count > 0)
2365                         archives = lk->lk_data;
2366
2367                 rc = mdc_ioc_hsm_ct_register(imp, lk->lk_data_count, archives);
2368         }
2369
2370         return rc;
2371 }
2372
2373 /**
2374  * Send a message to any listening copytools
2375  * @param val KUC message (kuc_hdr + hsm_action_list)
2376  * @param len total length of message
2377  */
2378 static int mdc_hsm_copytool_send(const struct obd_uuid *uuid,
2379                                  size_t len, void *val)
2380 {
2381         struct kuc_hdr          *lh = (struct kuc_hdr *)val;
2382         struct hsm_action_list  *hal = (struct hsm_action_list *)(lh + 1);
2383         int                      rc;
2384         ENTRY;
2385
2386         if (len < sizeof(*lh) + sizeof(*hal)) {
2387                 CERROR("Short HSM message %zu < %zu\n", len,
2388                        sizeof(*lh) + sizeof(*hal));
2389                 RETURN(-EPROTO);
2390         }
2391         if (lh->kuc_magic == __swab16(KUC_MAGIC)) {
2392                 lustre_swab_kuch(lh);
2393                 lustre_swab_hal(hal);
2394         } else if (lh->kuc_magic != KUC_MAGIC) {
2395                 CERROR("Bad magic %x!=%x\n", lh->kuc_magic, KUC_MAGIC);
2396                 RETURN(-EPROTO);
2397         }
2398
2399         CDEBUG(D_HSM, " Received message mg=%x t=%d m=%d l=%d actions=%d "
2400                "on %s\n",
2401                lh->kuc_magic, lh->kuc_transport, lh->kuc_msgtype,
2402                lh->kuc_msglen, hal->hal_count, hal->hal_fsname);
2403
2404         /* Broadcast to HSM listeners */
2405         rc = libcfs_kkuc_group_put(uuid, KUC_GRP_HSM, lh);
2406
2407         RETURN(rc);
2408 }
2409
2410 /**
2411  * callback function passed to kuc for re-registering each HSM copytool
2412  * running on MDC, after MDT shutdown/recovery.
2413  * @param data copytool registration data
2414  * @param cb_arg callback argument (obd_import)
2415  */
2416 static int mdc_hsm_ct_reregister(void *data, void *cb_arg)
2417 {
2418         struct obd_import *imp = (struct obd_import *)cb_arg;
2419         struct kkuc_ct_data *kcd = data;
2420         __u32 *archives = NULL;
2421         int rc;
2422
2423         if (kcd == NULL ||
2424             (kcd->kcd_magic != KKUC_CT_DATA_ARRAY_MAGIC &&
2425              kcd->kcd_magic != KKUC_CT_DATA_BITMAP_MAGIC))
2426                 return -EPROTO;
2427
2428         if (kcd->kcd_magic == KKUC_CT_DATA_BITMAP_MAGIC) {
2429                 CDEBUG(D_HA, "%s: recover copytool registration to MDT "
2430                        "(archive=%#x)\n", imp->imp_obd->obd_name,
2431                        kcd->kcd_nr_archives);
2432         } else {
2433                 CDEBUG(D_HA, "%s: recover copytool registration to MDT "
2434                        "(archive nr = %u)\n",
2435                        imp->imp_obd->obd_name, kcd->kcd_nr_archives);
2436                 if (kcd->kcd_nr_archives != 0)
2437                         archives = kcd->kcd_archives;
2438         }
2439
2440         rc = mdc_ioc_hsm_ct_register(imp, kcd->kcd_nr_archives, archives);
2441         /* ignore error if the copytool is already registered */
2442         return (rc == -EEXIST) ? 0 : rc;
2443 }
2444
2445 /**
2446  * Re-establish all kuc contexts with MDT
2447  * after MDT shutdown/recovery.
2448  */
2449 static int mdc_kuc_reregister(struct obd_import *imp)
2450 {
2451         /* re-register HSM agents */
2452         return libcfs_kkuc_group_foreach(&imp->imp_obd->obd_uuid, KUC_GRP_HSM,
2453                                          mdc_hsm_ct_reregister, imp);
2454 }
2455
2456 static int mdc_set_info_async(const struct lu_env *env,
2457                               struct obd_export *exp,
2458                               u32 keylen, void *key,
2459                               u32 vallen, void *val,
2460                               struct ptlrpc_request_set *set)
2461 {
2462         struct obd_import       *imp = class_exp2cliimp(exp);
2463         int                      rc;
2464         ENTRY;
2465
2466         if (KEY_IS(KEY_READ_ONLY)) {
2467                 if (vallen != sizeof(int))
2468                         RETURN(-EINVAL);
2469
2470                 spin_lock(&imp->imp_lock);
2471                 if (*((int *)val)) {
2472                         imp->imp_connect_flags_orig |= OBD_CONNECT_RDONLY;
2473                         imp->imp_connect_data.ocd_connect_flags |=
2474                                                         OBD_CONNECT_RDONLY;
2475                 } else {
2476                         imp->imp_connect_flags_orig &= ~OBD_CONNECT_RDONLY;
2477                         imp->imp_connect_data.ocd_connect_flags &=
2478                                                         ~OBD_CONNECT_RDONLY;
2479                 }
2480                 spin_unlock(&imp->imp_lock);
2481
2482                 rc = do_set_info_async(imp, MDS_SET_INFO, LUSTRE_MDS_VERSION,
2483                                        keylen, key, vallen, val, set);
2484                 RETURN(rc);
2485         }
2486         if (KEY_IS(KEY_CHANGELOG_CLEAR)) {
2487                 rc = do_set_info_async(imp, MDS_SET_INFO, LUSTRE_MDS_VERSION,
2488                                        keylen, key, vallen, val, set);
2489                 RETURN(rc);
2490         }
2491         if (KEY_IS(KEY_HSM_COPYTOOL_SEND)) {
2492                 rc = mdc_hsm_copytool_send(&imp->imp_obd->obd_uuid, vallen,
2493                                            val);
2494                 RETURN(rc);
2495         }
2496
2497         if (KEY_IS(KEY_DEFAULT_EASIZE)) {
2498                 __u32 *default_easize = val;
2499
2500                 exp->exp_obd->u.cli.cl_default_mds_easize = *default_easize;
2501                 RETURN(0);
2502         }
2503
2504         rc = osc_set_info_async(env, exp, keylen, key, vallen, val, set);
2505         RETURN(rc);
2506 }
2507
2508 static int mdc_get_info(const struct lu_env *env, struct obd_export *exp,
2509                         __u32 keylen, void *key, __u32 *vallen, void *val)
2510 {
2511         int rc = -EINVAL;
2512
2513         if (KEY_IS(KEY_MAX_EASIZE)) {
2514                 __u32 mdsize, *max_easize;
2515
2516                 if (*vallen != sizeof(int))
2517                         RETURN(-EINVAL);
2518                 mdsize = *(__u32 *)val;
2519                 if (mdsize > exp->exp_obd->u.cli.cl_max_mds_easize)
2520                         exp->exp_obd->u.cli.cl_max_mds_easize = mdsize;
2521                 max_easize = val;
2522                 *max_easize = exp->exp_obd->u.cli.cl_max_mds_easize;
2523                 RETURN(0);
2524         } else if (KEY_IS(KEY_DEFAULT_EASIZE)) {
2525                 __u32 *default_easize;
2526
2527                 if (*vallen != sizeof(int))
2528                         RETURN(-EINVAL);
2529                 default_easize = val;
2530                 *default_easize = exp->exp_obd->u.cli.cl_default_mds_easize;
2531                 RETURN(0);
2532         } else if (KEY_IS(KEY_CONN_DATA)) {
2533                 struct obd_import *imp = class_exp2cliimp(exp);
2534                 struct obd_connect_data *data = val;
2535
2536                 if (*vallen != sizeof(*data))
2537                         RETURN(-EINVAL);
2538
2539                 *data = imp->imp_connect_data;
2540                 RETURN(0);
2541         } else if (KEY_IS(KEY_TGT_COUNT)) {
2542                 *((__u32 *)val) = 1;
2543                 RETURN(0);
2544         }
2545
2546         rc = mdc_get_info_rpc(exp, keylen, key, *vallen, val);
2547
2548         RETURN(rc);
2549 }
2550
2551 static int mdc_fsync(struct obd_export *exp, const struct lu_fid *fid,
2552                      struct ptlrpc_request **request)
2553 {
2554         struct ptlrpc_request *req;
2555         int                    rc;
2556         ENTRY;
2557
2558         *request = NULL;
2559         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_MDS_SYNC);
2560         if (req == NULL)
2561                 RETURN(-ENOMEM);
2562
2563         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_SYNC);
2564         if (rc) {
2565                 ptlrpc_request_free(req);
2566                 RETURN(rc);
2567         }
2568
2569         mdc_pack_body(&req->rq_pill, fid, 0, 0, -1, 0);
2570
2571         ptlrpc_request_set_replen(req);
2572
2573         rc = ptlrpc_queue_wait(req);
2574         if (rc)
2575                 ptlrpc_req_finished(req);
2576         else
2577                 *request = req;
2578         RETURN(rc);
2579 }
2580
2581 struct mdc_rmfid_args {
2582         int *mra_rcs;
2583         int mra_nr;
2584 };
2585
2586 int mdc_rmfid_interpret(const struct lu_env *env, struct ptlrpc_request *req,
2587                           void *args, int rc)
2588 {
2589         struct mdc_rmfid_args *aa;
2590         int *rcs, size;
2591         ENTRY;
2592
2593         if (!rc) {
2594                 aa = ptlrpc_req_async_args(aa, req);
2595
2596                 size = req_capsule_get_size(&req->rq_pill, &RMF_RCS,
2597                                             RCL_SERVER);
2598                 LASSERT(size == sizeof(int) * aa->mra_nr);
2599                 rcs = req_capsule_server_get(&req->rq_pill, &RMF_RCS);
2600                 LASSERT(rcs);
2601                 LASSERT(aa->mra_rcs);
2602                 LASSERT(aa->mra_nr);
2603                 memcpy(aa->mra_rcs, rcs, size);
2604         }
2605
2606         RETURN(rc);
2607 }
2608
2609 static int mdc_rmfid(struct obd_export *exp, struct fid_array *fa,
2610                      int *rcs, struct ptlrpc_request_set *set)
2611 {
2612         struct ptlrpc_request *req;
2613         struct mdc_rmfid_args *aa;
2614         struct mdt_body *b;
2615         struct lu_fid *tmp;
2616         int rc, flen;
2617         ENTRY;
2618
2619         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_MDS_RMFID);
2620         if (req == NULL)
2621                 RETURN(-ENOMEM);
2622
2623         flen = fa->fa_nr * sizeof(struct lu_fid);
2624         req_capsule_set_size(&req->rq_pill, &RMF_FID_ARRAY,
2625                              RCL_CLIENT, flen);
2626         req_capsule_set_size(&req->rq_pill, &RMF_FID_ARRAY,
2627                              RCL_SERVER, flen);
2628         req_capsule_set_size(&req->rq_pill, &RMF_RCS,
2629                              RCL_SERVER, fa->fa_nr * sizeof(__u32));
2630         rc = ptlrpc_request_pack(req, LUSTRE_MDS_VERSION, MDS_RMFID);
2631         if (rc) {
2632                 ptlrpc_request_free(req);
2633                 RETURN(rc);
2634         }
2635         tmp = req_capsule_client_get(&req->rq_pill, &RMF_FID_ARRAY);
2636         memcpy(tmp, fa->fa_fids, flen);
2637
2638         mdc_pack_body(&req->rq_pill, NULL, 0, 0, -1, 0);
2639         b = req_capsule_client_get(&req->rq_pill, &RMF_MDT_BODY);
2640         b->mbo_ctime = ktime_get_real_seconds();
2641
2642         ptlrpc_request_set_replen(req);
2643
2644         LASSERT(rcs);
2645         aa = ptlrpc_req_async_args(aa, req);
2646         aa->mra_rcs = rcs;
2647         aa->mra_nr = fa->fa_nr;
2648         req->rq_interpret_reply = mdc_rmfid_interpret;
2649
2650         ptlrpc_set_add_req(set, req);
2651         ptlrpc_check_set(NULL, set);
2652
2653         RETURN(rc);
2654 }
2655
2656 static int mdc_import_event(struct obd_device *obd, struct obd_import *imp,
2657                             enum obd_import_event event)
2658 {
2659         struct client_obd *cli = &obd->u.cli;
2660         int rc = 0;
2661
2662         LASSERT(imp->imp_obd == obd);
2663
2664         switch (event) {
2665         case IMP_EVENT_DISCON:
2666                 spin_lock(&cli->cl_loi_list_lock);
2667                 cli->cl_avail_grant = 0;
2668                 cli->cl_lost_grant = 0;
2669                 spin_unlock(&cli->cl_loi_list_lock);
2670                 break;
2671         case IMP_EVENT_INACTIVE:
2672                 /*
2673                  * Flush current sequence to make client obtain new one
2674                  * from server in case of disconnect/reconnect.
2675                  */
2676                 down_read(&cli->cl_seq_rwsem);
2677                 if (cli->cl_seq)
2678                         seq_client_flush(cli->cl_seq);
2679                 up_read(&cli->cl_seq_rwsem);
2680
2681                 rc = obd_notify_observer(obd, obd, OBD_NOTIFY_INACTIVE);
2682                 break;
2683         case IMP_EVENT_INVALIDATE: {
2684                 struct ldlm_namespace *ns = obd->obd_namespace;
2685                 struct lu_env *env;
2686                 __u16 refcheck;
2687
2688                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
2689
2690                 env = cl_env_get(&refcheck);
2691                 if (!IS_ERR(env)) {
2692                         /* Reset grants. All pages go to failing rpcs due to
2693                          * the invalid import.
2694                          */
2695                         osc_io_unplug(env, cli, NULL);
2696
2697                         cfs_hash_for_each_nolock(ns->ns_rs_hash,
2698                                                  osc_ldlm_resource_invalidate,
2699                                                  env, 0);
2700                         cl_env_put(env, &refcheck);
2701                         ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
2702                 } else {
2703                         rc = PTR_ERR(env);
2704                 }
2705                 break;
2706         }
2707         case IMP_EVENT_ACTIVE:
2708                 rc = obd_notify_observer(obd, obd, OBD_NOTIFY_ACTIVE);
2709                 /* redo the kuc registration after reconnecting */
2710                 if (rc == 0)
2711                         rc = mdc_kuc_reregister(imp);
2712                 break;
2713         case IMP_EVENT_OCD: {
2714                 struct obd_connect_data *ocd = &imp->imp_connect_data;
2715
2716                 if (OCD_HAS_FLAG(ocd, GRANT))
2717                         osc_init_grant(cli, ocd);
2718
2719                 md_init_ea_size(obd->obd_self_export, ocd->ocd_max_easize, 0);
2720                 rc = obd_notify_observer(obd, obd, OBD_NOTIFY_OCD);
2721                 break;
2722         }
2723         case IMP_EVENT_DEACTIVATE:
2724         case IMP_EVENT_ACTIVATE:
2725                 break;
2726         default:
2727                 CERROR("Unknown import event %x\n", event);
2728                 LBUG();
2729         }
2730         RETURN(rc);
2731 }
2732
2733 int mdc_fid_alloc(const struct lu_env *env, struct obd_export *exp,
2734                   struct lu_fid *fid, struct md_op_data *op_data)
2735 {
2736         struct client_obd *cli = &exp->exp_obd->u.cli;
2737         int rc = -EIO;
2738
2739         ENTRY;
2740
2741         down_read(&cli->cl_seq_rwsem);
2742         if (cli->cl_seq)
2743                 rc = seq_client_alloc_fid(env, cli->cl_seq, fid);
2744         up_read(&cli->cl_seq_rwsem);
2745
2746         RETURN(rc);
2747 }
2748
2749 static struct obd_uuid *mdc_get_uuid(struct obd_export *exp)
2750 {
2751         struct client_obd *cli = &exp->exp_obd->u.cli;
2752         return &cli->cl_target_uuid;
2753 }
2754
2755 /**
2756  * Determine whether the lock can be canceled before replaying it during
2757  * recovery, non zero value will be return if the lock can be canceled,
2758  * or zero returned for not
2759  */
2760 static int mdc_cancel_weight(struct ldlm_lock *lock)
2761 {
2762         if (lock->l_resource->lr_type != LDLM_IBITS)
2763                 RETURN(0);
2764
2765         /* FIXME: if we ever get into a situation where there are too many
2766          * opened files with open locks on a single node, then we really
2767          * should replay these open locks to reget it */
2768         if (lock->l_policy_data.l_inodebits.bits & MDS_INODELOCK_OPEN)
2769                 RETURN(0);
2770
2771         /* Special case for DoM locks, cancel only unused and granted locks */
2772         if (ldlm_has_dom(lock) &&
2773             (lock->l_granted_mode != lock->l_req_mode ||
2774              osc_ldlm_weigh_ast(lock) != 0))
2775                 RETURN(0);
2776
2777         RETURN(1);
2778 }
2779
2780 static int mdc_resource_inode_free(struct ldlm_resource *res)
2781 {
2782         if (res->lr_lvb_inode)
2783                 res->lr_lvb_inode = NULL;
2784
2785         return 0;
2786 }
2787
2788 static struct ldlm_valblock_ops inode_lvbo = {
2789         .lvbo_free = mdc_resource_inode_free
2790 };
2791
2792 static int mdc_llog_init(struct obd_device *obd)
2793 {
2794         struct obd_llog_group   *olg = &obd->obd_olg;
2795         struct llog_ctxt        *ctxt;
2796         int                      rc;
2797
2798         ENTRY;
2799
2800         rc = llog_setup(NULL, obd, olg, LLOG_CHANGELOG_REPL_CTXT, obd,
2801                         &llog_client_ops);
2802         if (rc < 0)
2803                 RETURN(rc);
2804
2805         ctxt = llog_group_get_ctxt(olg, LLOG_CHANGELOG_REPL_CTXT);
2806         llog_initiator_connect(ctxt);
2807         llog_ctxt_put(ctxt);
2808
2809         RETURN(0);
2810 }
2811
2812 static void mdc_llog_finish(struct obd_device *obd)
2813 {
2814         struct llog_ctxt *ctxt;
2815
2816         ENTRY;
2817
2818         ctxt = llog_get_context(obd, LLOG_CHANGELOG_REPL_CTXT);
2819         if (ctxt != NULL)
2820                 llog_cleanup(NULL, ctxt);
2821
2822         EXIT;
2823 }
2824
2825 int mdc_setup(struct obd_device *obd, struct lustre_cfg *cfg)
2826 {
2827         int rc;
2828
2829         ENTRY;
2830
2831         rc = osc_setup_common(obd, cfg);
2832         if (rc < 0)
2833                 RETURN(rc);
2834
2835         rc = mdc_tunables_init(obd);
2836         if (rc)
2837                 GOTO(err_osc_cleanup, rc);
2838
2839         obd->u.cli.cl_dom_min_inline_repsize = MDC_DOM_DEF_INLINE_REPSIZE;
2840         obd->u.cli.cl_lsom_update = true;
2841
2842         ns_register_cancel(obd->obd_namespace, mdc_cancel_weight);
2843
2844         obd->obd_namespace->ns_lvbo = &inode_lvbo;
2845
2846         rc = mdc_llog_init(obd);
2847         if (rc) {
2848                 CERROR("%s: failed to setup llogging subsystems: rc = %d\n",
2849                        obd->obd_name, rc);
2850                 GOTO(err_llog_cleanup, rc);
2851         }
2852
2853         rc = mdc_changelog_cdev_init(obd);
2854         if (rc) {
2855                 CERROR("%s: failed to setup changelog char device: rc = %d\n",
2856                        obd->obd_name, rc);
2857                 GOTO(err_changelog_cleanup, rc);
2858         }
2859
2860         RETURN(rc);
2861
2862 err_changelog_cleanup:
2863         mdc_llog_finish(obd);
2864 err_llog_cleanup:
2865         lprocfs_free_md_stats(obd);
2866         ptlrpc_lprocfs_unregister_obd(obd);
2867 err_osc_cleanup:
2868         osc_cleanup_common(obd);
2869         return rc;
2870 }
2871
2872 /* Initialize the default and maximum LOV EA sizes.  This allows
2873  * us to make MDS RPCs with large enough reply buffers to hold a default
2874  * sized EA without having to calculate this (via a call into the
2875  * LOV + OSCs) each time we make an RPC.  The maximum size is also tracked
2876  * but not used to avoid wastefully vmalloc()'ing large reply buffers when
2877  * a large number of stripes is possible.  If a larger reply buffer is
2878  * required it will be reallocated in the ptlrpc layer due to overflow.
2879  */
2880 static int mdc_init_ea_size(struct obd_export *exp, __u32 easize,
2881                             __u32 def_easize)
2882 {
2883         struct obd_device *obd = exp->exp_obd;
2884         struct client_obd *cli = &obd->u.cli;
2885         ENTRY;
2886
2887         if (cli->cl_max_mds_easize < easize)
2888                 cli->cl_max_mds_easize = easize;
2889
2890         if (cli->cl_default_mds_easize < def_easize)
2891                 cli->cl_default_mds_easize = def_easize;
2892
2893         RETURN(0);
2894 }
2895
2896 static int mdc_precleanup(struct obd_device *obd)
2897 {
2898         ENTRY;
2899
2900         osc_precleanup_common(obd);
2901         mdc_changelog_cdev_finish(obd);
2902
2903         obd_cleanup_client_import(obd);
2904         ptlrpc_lprocfs_unregister_obd(obd);
2905         lprocfs_free_md_stats(obd);
2906         mdc_llog_finish(obd);
2907         RETURN(0);
2908 }
2909
2910 static int mdc_cleanup(struct obd_device *obd)
2911 {
2912         return osc_cleanup_common(obd);
2913 }
2914
2915 static const struct obd_ops mdc_obd_ops = {
2916         .o_owner            = THIS_MODULE,
2917         .o_setup            = mdc_setup,
2918         .o_precleanup       = mdc_precleanup,
2919         .o_cleanup          = mdc_cleanup,
2920         .o_add_conn         = client_import_add_conn,
2921         .o_del_conn         = client_import_del_conn,
2922         .o_connect          = client_connect_import,
2923         .o_reconnect        = osc_reconnect,
2924         .o_disconnect       = osc_disconnect,
2925         .o_iocontrol        = mdc_iocontrol,
2926         .o_set_info_async   = mdc_set_info_async,
2927         .o_statfs           = mdc_statfs,
2928         .o_statfs_async     = mdc_statfs_async,
2929         .o_fid_init         = client_fid_init,
2930         .o_fid_fini         = client_fid_fini,
2931         .o_fid_alloc        = mdc_fid_alloc,
2932         .o_import_event     = mdc_import_event,
2933         .o_get_info         = mdc_get_info,
2934         .o_get_uuid         = mdc_get_uuid,
2935         .o_quotactl         = mdc_quotactl,
2936 };
2937
2938 static const struct md_ops mdc_md_ops = {
2939         .m_get_root         = mdc_get_root,
2940         .m_null_inode       = mdc_null_inode,
2941         .m_close            = mdc_close,
2942         .m_create           = mdc_create,
2943         .m_enqueue          = mdc_enqueue,
2944         .m_getattr          = mdc_getattr,
2945         .m_getattr_name     = mdc_getattr_name,
2946         .m_intent_lock      = mdc_intent_lock,
2947         .m_link             = mdc_link,
2948         .m_rename           = mdc_rename,
2949         .m_setattr          = mdc_setattr,
2950         .m_setxattr         = mdc_setxattr,
2951         .m_getxattr         = mdc_getxattr,
2952         .m_fsync                = mdc_fsync,
2953         .m_file_resync          = mdc_file_resync,
2954         .m_read_page            = mdc_read_page,
2955         .m_unlink           = mdc_unlink,
2956         .m_cancel_unused    = mdc_cancel_unused,
2957         .m_init_ea_size     = mdc_init_ea_size,
2958         .m_set_lock_data    = mdc_set_lock_data,
2959         .m_lock_match       = mdc_lock_match,
2960         .m_get_lustre_md    = mdc_get_lustre_md,
2961         .m_free_lustre_md   = mdc_free_lustre_md,
2962         .m_set_open_replay_data = mdc_set_open_replay_data,
2963         .m_clear_open_replay_data = mdc_clear_open_replay_data,
2964         .m_intent_getattr_async = mdc_intent_getattr_async,
2965         .m_revalidate_lock      = mdc_revalidate_lock,
2966         .m_rmfid                = mdc_rmfid,
2967 };
2968
2969 dev_t mdc_changelog_dev;
2970 struct class *mdc_changelog_class;
2971 static int __init mdc_init(void)
2972 {
2973         int rc = 0;
2974         rc = alloc_chrdev_region(&mdc_changelog_dev, 0,
2975                                  MDC_CHANGELOG_DEV_COUNT,
2976                                  MDC_CHANGELOG_DEV_NAME);
2977         if (rc)
2978                 return rc;
2979
2980         mdc_changelog_class = class_create(THIS_MODULE, MDC_CHANGELOG_DEV_NAME);
2981         if (IS_ERR(mdc_changelog_class)) {
2982                 rc = PTR_ERR(mdc_changelog_class);
2983                 goto out_dev;
2984         }
2985
2986         rc = class_register_type(&mdc_obd_ops, &mdc_md_ops, true,
2987                                  LUSTRE_MDC_NAME, &mdc_device_type);
2988         if (rc)
2989                 goto out_class;
2990
2991         return 0;
2992
2993 out_class:
2994         class_destroy(mdc_changelog_class);
2995 out_dev:
2996         unregister_chrdev_region(mdc_changelog_dev, MDC_CHANGELOG_DEV_COUNT);
2997         return rc;
2998 }
2999
3000 static void __exit mdc_exit(void)
3001 {
3002         class_unregister_type(LUSTRE_MDC_NAME);
3003         class_destroy(mdc_changelog_class);
3004         unregister_chrdev_region(mdc_changelog_dev, MDC_CHANGELOG_DEV_COUNT);
3005         idr_destroy(&mdc_changelog_minor_idr);
3006 }
3007
3008 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
3009 MODULE_DESCRIPTION("Lustre Metadata Client");
3010 MODULE_VERSION(LUSTRE_VERSION_STRING);
3011 MODULE_LICENSE("GPL");
3012
3013 module_init(mdc_init);
3014 module_exit(mdc_exit);