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