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