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