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