Whamcloud - gitweb
LU-6313 tests: more robust for scrub test_11
[fs/lustre-release.git] / lustre / mdt / mdt_handler.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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2010, 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  * lustre/mdt/mdt_handler.c
37  *
38  * Lustre Metadata Target (mdt) request handler
39  *
40  * Author: Peter Braam <braam@clusterfs.com>
41  * Author: Andreas Dilger <adilger@clusterfs.com>
42  * Author: Phil Schwan <phil@clusterfs.com>
43  * Author: Mike Shaver <shaver@clusterfs.com>
44  * Author: Nikita Danilov <nikita@clusterfs.com>
45  * Author: Huang Hua <huanghua@clusterfs.com>
46  * Author: Yury Umanets <umka@clusterfs.com>
47  */
48
49 #define DEBUG_SUBSYSTEM S_MDS
50
51 #include <linux/module.h>
52 /*
53  * struct OBD_{ALLOC,FREE}*()
54  */
55 #include <obd_support.h>
56 #include <lustre_ioctl.h>
57 /* struct ptlrpc_request */
58 #include <lustre_net.h>
59 /* struct obd_export */
60 #include <lustre_export.h>
61 /* struct obd_device */
62 #include <obd.h>
63 /* lu2dt_dev() */
64 #include <dt_object.h>
65 #include <lustre_mds.h>
66 #include <lustre_log.h>
67 #include "mdt_internal.h"
68 #include <lustre_acl.h>
69 #include <lustre_param.h>
70 #include <lustre_quota.h>
71 #include <lustre_lfsck.h>
72 #include <lustre_nodemap.h>
73
74 mdl_mode_t mdt_mdl_lock_modes[] = {
75         [LCK_MINMODE] = MDL_MINMODE,
76         [LCK_EX]      = MDL_EX,
77         [LCK_PW]      = MDL_PW,
78         [LCK_PR]      = MDL_PR,
79         [LCK_CW]      = MDL_CW,
80         [LCK_CR]      = MDL_CR,
81         [LCK_NL]      = MDL_NL,
82         [LCK_GROUP]   = MDL_GROUP
83 };
84
85 ldlm_mode_t mdt_dlm_lock_modes[] = {
86         [MDL_MINMODE] = LCK_MINMODE,
87         [MDL_EX]      = LCK_EX,
88         [MDL_PW]      = LCK_PW,
89         [MDL_PR]      = LCK_PR,
90         [MDL_CW]      = LCK_CW,
91         [MDL_CR]      = LCK_CR,
92         [MDL_NL]      = LCK_NL,
93         [MDL_GROUP]   = LCK_GROUP
94 };
95
96 static struct mdt_device *mdt_dev(struct lu_device *d);
97 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags);
98
99 static const struct lu_object_operations mdt_obj_ops;
100
101 /* Slab for MDT object allocation */
102 static struct kmem_cache *mdt_object_kmem;
103
104 /* For HSM restore handles */
105 struct kmem_cache *mdt_hsm_cdt_kmem;
106
107 /* For HSM request handles */
108 struct kmem_cache *mdt_hsm_car_kmem;
109
110 static struct lu_kmem_descr mdt_caches[] = {
111         {
112                 .ckd_cache = &mdt_object_kmem,
113                 .ckd_name  = "mdt_obj",
114                 .ckd_size  = sizeof(struct mdt_object)
115         },
116         {
117                 .ckd_cache      = &mdt_hsm_cdt_kmem,
118                 .ckd_name       = "mdt_cdt_restore_handle",
119                 .ckd_size       = sizeof(struct cdt_restore_handle)
120         },
121         {
122                 .ckd_cache      = &mdt_hsm_car_kmem,
123                 .ckd_name       = "mdt_cdt_agent_req",
124                 .ckd_size       = sizeof(struct cdt_agent_req)
125         },
126         {
127                 .ckd_cache = NULL
128         }
129 };
130
131 int mdt_get_disposition(struct ldlm_reply *rep, int flag)
132 {
133         if (!rep)
134                 return 0;
135         return (rep->lock_policy_res1 & flag);
136 }
137
138 void mdt_clear_disposition(struct mdt_thread_info *info,
139                            struct ldlm_reply *rep, int flag)
140 {
141         if (info) {
142                 info->mti_opdata &= ~flag;
143                 tgt_opdata_clear(info->mti_env, flag);
144         }
145         if (rep)
146                 rep->lock_policy_res1 &= ~flag;
147 }
148
149 void mdt_set_disposition(struct mdt_thread_info *info,
150                          struct ldlm_reply *rep, int flag)
151 {
152         if (info) {
153                 info->mti_opdata |= flag;
154                 tgt_opdata_set(info->mti_env, flag);
155         }
156         if (rep)
157                 rep->lock_policy_res1 |= flag;
158 }
159
160 void mdt_lock_reg_init(struct mdt_lock_handle *lh, ldlm_mode_t lm)
161 {
162         lh->mlh_pdo_hash = 0;
163         lh->mlh_reg_mode = lm;
164         lh->mlh_rreg_mode = lm;
165         lh->mlh_type = MDT_REG_LOCK;
166 }
167
168 void mdt_lock_pdo_init(struct mdt_lock_handle *lh, ldlm_mode_t lock_mode,
169                        const struct lu_name *lname)
170 {
171         lh->mlh_reg_mode = lock_mode;
172         lh->mlh_rreg_mode = lock_mode;
173         lh->mlh_type = MDT_PDO_LOCK;
174
175         if (lu_name_is_valid(lname)) {
176                 lh->mlh_pdo_hash = full_name_hash(lname->ln_name,
177                                                   lname->ln_namelen);
178                 /* XXX Workaround for LU-2856
179                  *
180                  * Zero is a valid return value of full_name_hash, but
181                  * several users of mlh_pdo_hash assume a non-zero
182                  * hash value. We therefore map zero onto an
183                  * arbitrary, but consistent value (1) to avoid
184                  * problems further down the road. */
185                 if (unlikely(lh->mlh_pdo_hash == 0))
186                         lh->mlh_pdo_hash = 1;
187         } else {
188                 lh->mlh_pdo_hash = 0;
189         }
190 }
191
192 static void mdt_lock_pdo_mode(struct mdt_thread_info *info, struct mdt_object *o,
193                               struct mdt_lock_handle *lh)
194 {
195         mdl_mode_t mode;
196         ENTRY;
197
198         /*
199          * Any dir access needs couple of locks:
200          *
201          * 1) on part of dir we gonna take lookup/modify;
202          *
203          * 2) on whole dir to protect it from concurrent splitting and/or to
204          * flush client's cache for readdir().
205          *
206          * so, for a given mode and object this routine decides what lock mode
207          * to use for lock #2:
208          *
209          * 1) if caller's gonna lookup in dir then we need to protect dir from
210          * being splitted only - LCK_CR
211          *
212          * 2) if caller's gonna modify dir then we need to protect dir from
213          * being splitted and to flush cache - LCK_CW
214          *
215          * 3) if caller's gonna modify dir and that dir seems ready for
216          * splitting then we need to protect it from any type of access
217          * (lookup/modify/split) - LCK_EX --bzzz
218          */
219
220         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
221         LASSERT(lh->mlh_pdo_mode == LCK_MINMODE);
222
223         /*
224          * Ask underlaying level its opinion about preferable PDO lock mode
225          * having access type passed as regular lock mode:
226          *
227          * - MDL_MINMODE means that lower layer does not want to specify lock
228          * mode;
229          *
230          * - MDL_NL means that no PDO lock should be taken. This is used in some
231          * cases. Say, for non-splittable directories no need to use PDO locks
232          * at all.
233          */
234         mode = mdo_lock_mode(info->mti_env, mdt_object_child(o),
235                              mdt_dlm_mode2mdl_mode(lh->mlh_reg_mode));
236
237         if (mode != MDL_MINMODE) {
238                 lh->mlh_pdo_mode = mdt_mdl_mode2dlm_mode(mode);
239         } else {
240                 /*
241                  * Lower layer does not want to specify locking mode. We do it
242                  * our selves. No special protection is needed, just flush
243                  * client's cache on modification and allow concurrent
244                  * mondification.
245                  */
246                 switch (lh->mlh_reg_mode) {
247                 case LCK_EX:
248                         lh->mlh_pdo_mode = LCK_EX;
249                         break;
250                 case LCK_PR:
251                         lh->mlh_pdo_mode = LCK_CR;
252                         break;
253                 case LCK_PW:
254                         lh->mlh_pdo_mode = LCK_CW;
255                         break;
256                 default:
257                         CERROR("Not expected lock type (0x%x)\n",
258                                (int)lh->mlh_reg_mode);
259                         LBUG();
260                 }
261         }
262
263         LASSERT(lh->mlh_pdo_mode != LCK_MINMODE);
264         EXIT;
265 }
266
267 static int mdt_getstatus(struct tgt_session_info *tsi)
268 {
269         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
270         struct mdt_device       *mdt = info->mti_mdt;
271         struct mdt_body         *repbody;
272         int                      rc;
273
274         ENTRY;
275
276         rc = mdt_check_ucred(info);
277         if (rc)
278                 GOTO(out, rc = err_serious(rc));
279
280         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETSTATUS_PACK))
281                 GOTO(out, rc = err_serious(-ENOMEM));
282
283         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
284         repbody->mbo_fid1 = mdt->mdt_md_root_fid;
285         repbody->mbo_valid |= OBD_MD_FLID;
286
287         if (tsi->tsi_tgt->lut_mds_capa &&
288             exp_connect_flags(info->mti_exp) & OBD_CONNECT_MDS_CAPA) {
289                 struct mdt_object       *root;
290                 struct lustre_capa      *capa;
291
292                 root = mdt_object_find(info->mti_env, mdt, &repbody->mbo_fid1);
293                 if (IS_ERR(root))
294                         GOTO(out, rc = PTR_ERR(root));
295
296                 capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA1);
297                 LASSERT(capa);
298                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
299                 rc = mo_capa_get(info->mti_env, mdt_object_child(root), capa,
300                                  0);
301                 mdt_object_put(info->mti_env, root);
302                 if (rc == 0)
303                         repbody->mbo_valid |= OBD_MD_FLMDSCAPA;
304         }
305         EXIT;
306 out:
307         mdt_thread_info_fini(info);
308         return rc;
309 }
310
311 static int mdt_statfs(struct tgt_session_info *tsi)
312 {
313         struct ptlrpc_request           *req = tgt_ses_req(tsi);
314         struct mdt_thread_info          *info = tsi2mdt_info(tsi);
315         struct md_device                *next = info->mti_mdt->mdt_child;
316         struct ptlrpc_service_part      *svcpt;
317         struct obd_statfs               *osfs;
318         int                             rc;
319
320         ENTRY;
321
322         svcpt = req->rq_rqbd->rqbd_svcpt;
323
324         /* This will trigger a watchdog timeout */
325         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_STATFS_LCW_SLEEP,
326                          (MDT_SERVICE_WATCHDOG_FACTOR *
327                           at_get(&svcpt->scp_at_estimate)) + 1);
328
329         rc = mdt_check_ucred(info);
330         if (rc)
331                 GOTO(out, rc = err_serious(rc));
332
333         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_STATFS_PACK))
334                 GOTO(out, rc = err_serious(-ENOMEM));
335
336         osfs = req_capsule_server_get(info->mti_pill, &RMF_OBD_STATFS);
337         if (!osfs)
338                 GOTO(out, rc = -EPROTO);
339
340         /** statfs information are cached in the mdt_device */
341         if (cfs_time_before_64(info->mti_mdt->mdt_osfs_age,
342                                cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS))) {
343                 /** statfs data is too old, get up-to-date one */
344                 rc = next->md_ops->mdo_statfs(info->mti_env, next, osfs);
345                 if (rc)
346                         GOTO(out, rc);
347                 spin_lock(&info->mti_mdt->mdt_osfs_lock);
348                 info->mti_mdt->mdt_osfs = *osfs;
349                 info->mti_mdt->mdt_osfs_age = cfs_time_current_64();
350                 spin_unlock(&info->mti_mdt->mdt_osfs_lock);
351         } else {
352                 /** use cached statfs data */
353                 spin_lock(&info->mti_mdt->mdt_osfs_lock);
354                 *osfs = info->mti_mdt->mdt_osfs;
355                 spin_unlock(&info->mti_mdt->mdt_osfs_lock);
356         }
357
358         if (rc == 0)
359                 mdt_counter_incr(req, LPROC_MDT_STATFS);
360 out:
361         mdt_thread_info_fini(info);
362         RETURN(rc);
363 }
364
365 /**
366  * Pack SOM attributes into the reply.
367  * Call under a DLM UPDATE lock.
368  */
369 static void mdt_pack_size2body(struct mdt_thread_info *info,
370                                struct mdt_object *mo)
371 {
372         struct mdt_body *b;
373         struct md_attr *ma = &info->mti_attr;
374
375         LASSERT(ma->ma_attr.la_valid & LA_MODE);
376         b = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
377
378         /* Check if Size-on-MDS is supported, if this is a regular file,
379          * if SOM is enabled on the object and if SOM cache exists and valid.
380          * Otherwise do not pack Size-on-MDS attributes to the reply. */
381         if (!(mdt_conn_flags(info) & OBD_CONNECT_SOM) ||
382             !S_ISREG(ma->ma_attr.la_mode) ||
383             !mdt_object_is_som_enabled(mo) ||
384             !(ma->ma_valid & MA_SOM))
385                 return;
386
387         b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
388         b->mbo_size = ma->ma_som->msd_size;
389         b->mbo_blocks = ma->ma_som->msd_blocks;
390 }
391
392 #ifdef CONFIG_FS_POSIX_ACL
393 /*
394  * Pack ACL data into the reply. UIDs/GIDs are mapped and filtered by nodemap.
395  *
396  * \param       info    thread info object
397  * \param       repbody reply to pack ACLs into
398  * \param       o       mdt object of file to examine
399  * \param       nodemap nodemap of client to reply to
400  * \retval      0       success
401  * \retval      -errno  error getting or parsing ACL from disk
402  */
403 int mdt_pack_acl2body(struct mdt_thread_info *info, struct mdt_body *repbody,
404                       struct mdt_object *o, struct lu_nodemap *nodemap)
405 {
406         const struct lu_env     *env = info->mti_env;
407         struct md_object        *next = mdt_object_child(o);
408         struct lu_buf           *buf = &info->mti_buf;
409         int rc;
410
411         buf->lb_buf = req_capsule_server_get(info->mti_pill, &RMF_ACL);
412         buf->lb_len = req_capsule_get_size(info->mti_pill, &RMF_ACL,
413                                            RCL_SERVER);
414         if (buf->lb_len == 0)
415                 return 0;
416
417         rc = mo_xattr_get(env, next, buf, XATTR_NAME_ACL_ACCESS);
418         if (rc < 0) {
419                 if (rc == -ENODATA) {
420                         repbody->mbo_aclsize = 0;
421                         repbody->mbo_valid |= OBD_MD_FLACL;
422                         rc = 0;
423                 } else if (rc == -EOPNOTSUPP) {
424                         rc = 0;
425                 } else {
426                         CERROR("%s: unable to read "DFID" ACL: rc = %d\n",
427                                mdt_obd_name(info->mti_mdt),
428                                PFID(mdt_object_fid(o)), rc);
429                 }
430         } else {
431                 rc = nodemap_map_acl(nodemap, buf->lb_buf,
432                                      rc, NODEMAP_FS_TO_CLIENT);
433                 /* if all ACLs mapped out, rc is still >= 0 */
434                 if (rc < 0) {
435                         CERROR("%s: nodemap_map_acl unable to parse "DFID
436                                " ACL: rc = %d\n", mdt_obd_name(info->mti_mdt),
437                                PFID(mdt_object_fid(o)), rc);
438                 } else {
439                         repbody->mbo_aclsize = rc;
440                         repbody->mbo_valid |= OBD_MD_FLACL;
441                         rc = 0;
442                 }
443         }
444         return rc;
445 }
446 #endif
447
448 void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
449                         const struct lu_attr *attr, const struct lu_fid *fid)
450 {
451         struct md_attr          *ma = &info->mti_attr;
452         struct obd_export       *exp = info->mti_exp;
453         struct lu_nodemap       *nodemap = exp->exp_target_data.ted_nodemap;
454
455         LASSERT(ma->ma_valid & MA_INODE);
456
457         if (attr->la_valid & LA_ATIME) {
458                 b->mbo_atime = attr->la_atime;
459                 b->mbo_valid |= OBD_MD_FLATIME;
460         }
461         if (attr->la_valid & LA_MTIME) {
462                 b->mbo_mtime = attr->la_mtime;
463                 b->mbo_valid |= OBD_MD_FLMTIME;
464         }
465         if (attr->la_valid & LA_CTIME) {
466                 b->mbo_ctime = attr->la_ctime;
467                 b->mbo_valid |= OBD_MD_FLCTIME;
468         }
469         if (attr->la_valid & LA_FLAGS) {
470                 b->mbo_flags = attr->la_flags;
471                 b->mbo_valid |= OBD_MD_FLFLAGS;
472         }
473         if (attr->la_valid & LA_NLINK) {
474                 b->mbo_nlink = attr->la_nlink;
475                 b->mbo_valid |= OBD_MD_FLNLINK;
476         }
477         if (attr->la_valid & LA_UID) {
478                 b->mbo_uid = nodemap_map_id(nodemap, NODEMAP_UID,
479                                             NODEMAP_FS_TO_CLIENT,
480                                             attr->la_uid);
481                 b->mbo_valid |= OBD_MD_FLUID;
482         }
483         if (attr->la_valid & LA_GID) {
484                 b->mbo_gid = nodemap_map_id(nodemap, NODEMAP_GID,
485                                             NODEMAP_FS_TO_CLIENT,
486                                             attr->la_gid);
487                 b->mbo_valid |= OBD_MD_FLGID;
488         }
489         b->mbo_mode = attr->la_mode;
490         if (attr->la_valid & LA_MODE)
491                 b->mbo_valid |= OBD_MD_FLMODE;
492         if (attr->la_valid & LA_TYPE)
493                 b->mbo_valid |= OBD_MD_FLTYPE;
494
495         if (fid != NULL) {
496                 b->mbo_fid1 = *fid;
497                 b->mbo_valid |= OBD_MD_FLID;
498                 CDEBUG(D_INODE, DFID": nlink=%d, mode=%o, valid="LPX64"\n",
499                        PFID(fid), b->mbo_nlink, b->mbo_mode, b->mbo_valid);
500         }
501
502         if (info != NULL)
503                 mdt_body_reverse_idmap(info, b);
504
505         if (!(attr->la_valid & LA_TYPE))
506                 return;
507
508         b->mbo_rdev   = attr->la_rdev;
509         b->mbo_size   = attr->la_size;
510         b->mbo_blocks = attr->la_blocks;
511
512         if (!S_ISREG(attr->la_mode)) {
513                 b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS | OBD_MD_FLRDEV;
514         } else if (ma->ma_need & MA_LOV && !(ma->ma_valid & MA_LOV)) {
515                 /* means no objects are allocated on osts. */
516                 LASSERT(!(ma->ma_valid & MA_LOV));
517                 /* just ignore blocks occupied by extend attributes on MDS */
518                 b->mbo_blocks = 0;
519                 /* if no object is allocated on osts, the size on mds is valid.
520                  * b=22272 */
521                 b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
522         } else if ((ma->ma_valid & MA_LOV) && ma->ma_lmm != NULL &&
523                    ma->ma_lmm->lmm_pattern & LOV_PATTERN_F_RELEASED) {
524                 /* A released file stores its size on MDS. */
525                 /* But return 1 block for released file, unless tools like tar
526                  * will consider it fully sparse. (LU-3864)
527                  */
528                 if (unlikely(b->mbo_size == 0))
529                         b->mbo_blocks = 0;
530                 else
531                         b->mbo_blocks = 1;
532                 b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
533         }
534
535         if (fid != NULL && (b->mbo_valid & OBD_MD_FLSIZE))
536                 CDEBUG(D_VFSTRACE, DFID": returning size %llu\n",
537                        PFID(fid), (unsigned long long)b->mbo_size);
538 }
539
540 static inline int mdt_body_has_lov(const struct lu_attr *la,
541                                    const struct mdt_body *body)
542 {
543         return (S_ISREG(la->la_mode) && (body->mbo_valid & OBD_MD_FLEASIZE)) ||
544                (S_ISDIR(la->la_mode) && (body->mbo_valid & OBD_MD_FLDIREA));
545 }
546
547 void mdt_client_compatibility(struct mdt_thread_info *info)
548 {
549         struct mdt_body       *body;
550         struct ptlrpc_request *req = mdt_info_req(info);
551         struct obd_export     *exp = req->rq_export;
552         struct md_attr        *ma = &info->mti_attr;
553         struct lu_attr        *la = &ma->ma_attr;
554         ENTRY;
555
556         if (exp_connect_layout(exp))
557                 /* the client can deal with 16-bit lmm_stripe_count */
558                 RETURN_EXIT;
559
560         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
561
562         if (!mdt_body_has_lov(la, body))
563                 RETURN_EXIT;
564
565         /* now we have a reply with a lov for a client not compatible with the
566          * layout lock so we have to clean the layout generation number */
567         if (S_ISREG(la->la_mode))
568                 ma->ma_lmm->lmm_layout_gen = 0;
569         EXIT;
570 }
571
572 static int mdt_attr_get_eabuf_size(struct mdt_thread_info *info,
573                                    struct mdt_object *o)
574 {
575         const struct lu_env *env = info->mti_env;
576         int rc, rc2;
577
578         rc = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL,
579                           XATTR_NAME_LOV);
580
581         if (rc == -ENODATA)
582                 rc = 0;
583
584         if (rc < 0)
585                 goto out;
586
587         /* Is it a directory? Let's check for the LMV as well */
588         if (S_ISDIR(lu_object_attr(&mdt_object_child(o)->mo_lu))) {
589                 rc2 = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL,
590                                    XATTR_NAME_LMV);
591
592                 if (rc2 == -ENODATA)
593                         rc2 = mo_xattr_get(env, mdt_object_child(o),
594                                            &LU_BUF_NULL,
595                                            XATTR_NAME_DEFAULT_LMV);
596
597                 if ((rc2 < 0 && rc2 != -ENODATA) || (rc2 > rc))
598                         rc = rc2;
599         }
600
601 out:
602         return rc;
603 }
604
605 int mdt_big_xattr_get(struct mdt_thread_info *info, struct mdt_object *o,
606                       const char *name)
607 {
608         const struct lu_env *env = info->mti_env;
609         int rc;
610         ENTRY;
611
612         LASSERT(info->mti_big_lmm_used == 0);
613         rc = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL, name);
614         if (rc < 0)
615                 RETURN(rc);
616
617         /* big_lmm may need to be grown */
618         if (info->mti_big_lmmsize < rc) {
619                 int size = size_roundup_power2(rc);
620
621                 if (info->mti_big_lmmsize > 0) {
622                         /* free old buffer */
623                         LASSERT(info->mti_big_lmm);
624                         OBD_FREE_LARGE(info->mti_big_lmm,
625                                        info->mti_big_lmmsize);
626                         info->mti_big_lmm = NULL;
627                         info->mti_big_lmmsize = 0;
628                 }
629
630                 OBD_ALLOC_LARGE(info->mti_big_lmm, size);
631                 if (info->mti_big_lmm == NULL)
632                         RETURN(-ENOMEM);
633                 info->mti_big_lmmsize = size;
634         }
635         LASSERT(info->mti_big_lmmsize >= rc);
636
637         info->mti_buf.lb_buf = info->mti_big_lmm;
638         info->mti_buf.lb_len = info->mti_big_lmmsize;
639         rc = mo_xattr_get(env, mdt_object_child(o), &info->mti_buf, name);
640
641         RETURN(rc);
642 }
643
644 int mdt_stripe_get(struct mdt_thread_info *info, struct mdt_object *o,
645                    struct md_attr *ma, const char *name)
646 {
647         struct md_object *next = mdt_object_child(o);
648         struct lu_buf    *buf = &info->mti_buf;
649         int rc;
650
651         if (strcmp(name, XATTR_NAME_LOV) == 0) {
652                 buf->lb_buf = ma->ma_lmm;
653                 buf->lb_len = ma->ma_lmm_size;
654                 LASSERT(!(ma->ma_valid & MA_LOV));
655         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
656                 buf->lb_buf = ma->ma_lmv;
657                 buf->lb_len = ma->ma_lmv_size;
658                 LASSERT(!(ma->ma_valid & MA_LMV));
659         } else if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
660                 buf->lb_buf = ma->ma_lmv;
661                 buf->lb_len = ma->ma_lmv_size;
662                 LASSERT(!(ma->ma_valid & MA_LMV_DEF));
663         } else {
664                 return -EINVAL;
665         }
666
667         rc = mo_xattr_get(info->mti_env, next, buf, name);
668         if (rc > 0) {
669
670 got:
671                 if (strcmp(name, XATTR_NAME_LOV) == 0) {
672                         if (info->mti_big_lmm_used)
673                                 ma->ma_lmm = info->mti_big_lmm;
674
675                         /* NOT return LOV EA with hole to old client. */
676                         if (unlikely(le32_to_cpu(ma->ma_lmm->lmm_pattern) &
677                                      LOV_PATTERN_F_HOLE) &&
678                             !(exp_connect_flags(info->mti_exp) &
679                               OBD_CONNECT_LFSCK)) {
680                                 return -EIO;
681                         } else {
682                                 ma->ma_lmm_size = rc;
683                                 ma->ma_valid |= MA_LOV;
684                         }
685                 } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
686                         if (info->mti_big_lmm_used)
687                                 ma->ma_lmv = info->mti_big_lmm;
688
689                         ma->ma_lmv_size = rc;
690                         ma->ma_valid |= MA_LMV;
691                 } else if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
692                         ma->ma_lmv_size = rc;
693                         ma->ma_valid |= MA_LMV_DEF;
694                 }
695
696                 /* Update mdt_max_mdsize so all clients will be aware that */
697                 if (info->mti_mdt->mdt_max_mdsize < rc)
698                         info->mti_mdt->mdt_max_mdsize = rc;
699
700                 rc = 0;
701         } else if (rc == -ENODATA) {
702                 /* no LOV EA */
703                 rc = 0;
704         } else if (rc == -ERANGE) {
705                 /* Default LMV has fixed size, so it must be able to fit
706                  * in the original buffer */
707                 if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
708                         return rc;
709                 rc = mdt_big_xattr_get(info, o, name);
710                 if (rc > 0) {
711                         info->mti_big_lmm_used = 1;
712                         goto got;
713                 }
714         }
715
716         return rc;
717 }
718
719 static int mdt_attr_get_pfid(struct mdt_thread_info *info,
720                              struct mdt_object *o, struct lu_fid *pfid)
721 {
722         struct lu_buf           *buf = &info->mti_buf;
723         struct link_ea_header   *leh;
724         struct link_ea_entry    *lee;
725         int                      rc;
726         ENTRY;
727
728         buf->lb_buf = info->mti_big_lmm;
729         buf->lb_len = info->mti_big_lmmsize;
730         rc = mo_xattr_get(info->mti_env, mdt_object_child(o),
731                           buf, XATTR_NAME_LINK);
732         /* ignore errors, MA_PFID won't be set and it is
733          * up to the caller to treat this as an error */
734         if (rc == -ERANGE || buf->lb_len == 0) {
735                 rc = mdt_big_xattr_get(info, o, XATTR_NAME_LINK);
736                 buf->lb_buf = info->mti_big_lmm;
737                 buf->lb_len = info->mti_big_lmmsize;
738         }
739
740         if (rc < 0)
741                 RETURN(rc);
742         if (rc < sizeof(*leh)) {
743                 CERROR("short LinkEA on "DFID": rc = %d\n",
744                        PFID(mdt_object_fid(o)), rc);
745                 RETURN(-ENODATA);
746         }
747
748         leh = (struct link_ea_header *) buf->lb_buf;
749         lee = (struct link_ea_entry *)(leh + 1);
750         if (leh->leh_magic == __swab32(LINK_EA_MAGIC)) {
751                 leh->leh_magic = LINK_EA_MAGIC;
752                 leh->leh_reccount = __swab32(leh->leh_reccount);
753                 leh->leh_len = __swab64(leh->leh_len);
754         }
755         if (leh->leh_magic != LINK_EA_MAGIC)
756                 RETURN(-EINVAL);
757         if (leh->leh_reccount == 0)
758                 RETURN(-ENODATA);
759
760         memcpy(pfid, &lee->lee_parent_fid, sizeof(*pfid));
761         fid_be_to_cpu(pfid, pfid);
762
763         RETURN(0);
764 }
765
766 int mdt_attr_get_complex(struct mdt_thread_info *info,
767                          struct mdt_object *o, struct md_attr *ma)
768 {
769         const struct lu_env *env = info->mti_env;
770         struct md_object    *next = mdt_object_child(o);
771         struct lu_buf       *buf = &info->mti_buf;
772         int                  need = ma->ma_need;
773         int                  rc = 0, rc2;
774         u32                  mode;
775         ENTRY;
776
777         ma->ma_valid = 0;
778
779         if (mdt_object_exists(o) == 0)
780                 GOTO(out, rc = -ENOENT);
781         mode = lu_object_attr(&next->mo_lu);
782
783         if (need & MA_INODE) {
784                 ma->ma_need = MA_INODE;
785                 rc = mo_attr_get(env, next, ma);
786                 if (rc)
787                         GOTO(out, rc);
788                 ma->ma_valid |= MA_INODE;
789         }
790
791         if (need & MA_PFID) {
792                 rc = mdt_attr_get_pfid(info, o, &ma->ma_pfid);
793                 if (rc == 0)
794                         ma->ma_valid |= MA_PFID;
795                 /* ignore this error, parent fid is not mandatory */
796                 rc = 0;
797         }
798
799         if (need & MA_LOV && (S_ISREG(mode) || S_ISDIR(mode))) {
800                 rc = mdt_stripe_get(info, o, ma, XATTR_NAME_LOV);
801                 if (rc)
802                         GOTO(out, rc);
803         }
804
805         if (need & MA_LMV && S_ISDIR(mode)) {
806                 rc = mdt_stripe_get(info, o, ma, XATTR_NAME_LMV);
807                 if (rc != 0)
808                         GOTO(out, rc);
809         }
810
811         if (need & MA_LMV_DEF && S_ISDIR(mode)) {
812                 rc = mdt_stripe_get(info, o, ma, XATTR_NAME_DEFAULT_LMV);
813                 if (rc != 0)
814                         GOTO(out, rc);
815         }
816
817         if (need & MA_SOM && S_ISREG(mode)) {
818                 buf->lb_buf = info->mti_xattr_buf;
819                 buf->lb_len = sizeof(info->mti_xattr_buf);
820                 CLASSERT(sizeof(struct som_attrs) <=
821                          sizeof(info->mti_xattr_buf));
822                 rc2 = mo_xattr_get(info->mti_env, next, buf, XATTR_NAME_SOM);
823                 rc2 = lustre_buf2som(info->mti_xattr_buf, rc2, ma->ma_som);
824                 if (rc2 == 0)
825                         ma->ma_valid |= MA_SOM;
826                 else if (rc2 < 0 && rc2 != -ENODATA)
827                         GOTO(out, rc = rc2);
828         }
829
830         if (need & MA_HSM && S_ISREG(mode)) {
831                 buf->lb_buf = info->mti_xattr_buf;
832                 buf->lb_len = sizeof(info->mti_xattr_buf);
833                 CLASSERT(sizeof(struct hsm_attrs) <=
834                          sizeof(info->mti_xattr_buf));
835                 rc2 = mo_xattr_get(info->mti_env, next, buf, XATTR_NAME_HSM);
836                 rc2 = lustre_buf2hsm(info->mti_xattr_buf, rc2, &ma->ma_hsm);
837                 if (rc2 == 0)
838                         ma->ma_valid |= MA_HSM;
839                 else if (rc2 < 0 && rc2 != -ENODATA)
840                         GOTO(out, rc = rc2);
841         }
842
843 #ifdef CONFIG_FS_POSIX_ACL
844         if (need & MA_ACL_DEF && S_ISDIR(mode)) {
845                 buf->lb_buf = ma->ma_acl;
846                 buf->lb_len = ma->ma_acl_size;
847                 rc2 = mo_xattr_get(env, next, buf, XATTR_NAME_ACL_DEFAULT);
848                 if (rc2 > 0) {
849                         ma->ma_acl_size = rc2;
850                         ma->ma_valid |= MA_ACL_DEF;
851                 } else if (rc2 == -ENODATA) {
852                         /* no ACLs */
853                         ma->ma_acl_size = 0;
854                 } else
855                         GOTO(out, rc = rc2);
856         }
857 #endif
858 out:
859         ma->ma_need = need;
860         CDEBUG(D_INODE, "after getattr rc = %d, ma_valid = "LPX64" ma_lmm=%p\n",
861                rc, ma->ma_valid, ma->ma_lmm);
862         RETURN(rc);
863 }
864
865 static int mdt_getattr_internal(struct mdt_thread_info *info,
866                                 struct mdt_object *o, int ma_need)
867 {
868         struct md_object        *next = mdt_object_child(o);
869         const struct mdt_body   *reqbody = info->mti_body;
870         struct ptlrpc_request   *req = mdt_info_req(info);
871         struct md_attr          *ma = &info->mti_attr;
872         struct lu_attr          *la = &ma->ma_attr;
873         struct req_capsule      *pill = info->mti_pill;
874         const struct lu_env     *env = info->mti_env;
875         struct mdt_body         *repbody;
876         struct lu_buf           *buffer = &info->mti_buf;
877         struct obd_export       *exp = info->mti_exp;
878         struct lu_nodemap       *nodemap = exp->exp_target_data.ted_nodemap;
879         int                      rc;
880         int                      is_root;
881         ENTRY;
882
883         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETATTR_PACK))
884                 RETURN(err_serious(-ENOMEM));
885
886         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
887
888         ma->ma_valid = 0;
889
890         if (mdt_object_remote(o)) {
891                 /* This object is located on remote node.*/
892                 /* Return -ENOTSUPP for old client */
893                 if (!mdt_is_dne_client(req->rq_export))
894                         GOTO(out, rc = -ENOTSUPP);
895
896                 repbody->mbo_fid1 = *mdt_object_fid(o);
897                 repbody->mbo_valid = OBD_MD_FLID | OBD_MD_MDS;
898                 GOTO(out, rc = 0);
899         }
900
901         if (reqbody->mbo_eadatasize > 0) {
902                 buffer->lb_buf = req_capsule_server_get(pill, &RMF_MDT_MD);
903                 if (buffer->lb_buf == NULL)
904                         GOTO(out, rc = -EPROTO);
905                 buffer->lb_len = req_capsule_get_size(pill, &RMF_MDT_MD,
906                                                       RCL_SERVER);
907         } else {
908                 buffer->lb_buf = NULL;
909                 buffer->lb_len = 0;
910                 ma_need &= ~(MA_LOV | MA_LMV);
911                 CDEBUG(D_INFO, "%s: RPC from %s: does not need LOVEA.\n",
912                        mdt_obd_name(info->mti_mdt),
913                        req->rq_export->exp_client_uuid.uuid);
914         }
915
916         /* If it is dir object and client require MEA, then we got MEA */
917         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
918             (reqbody->mbo_valid & (OBD_MD_MEA | OBD_MD_DEFAULT_MEA))) {
919                 /* Assumption: MDT_MD size is enough for lmv size. */
920                 ma->ma_lmv = buffer->lb_buf;
921                 ma->ma_lmv_size = buffer->lb_len;
922                 ma->ma_need = MA_INODE;
923                 if (ma->ma_lmv_size > 0) {
924                         if (reqbody->mbo_valid & OBD_MD_MEA)
925                                 ma->ma_need |= MA_LMV;
926                         else if (reqbody->mbo_valid & OBD_MD_DEFAULT_MEA)
927                                 ma->ma_need |= MA_LMV_DEF;
928                 }
929         } else {
930                 ma->ma_lmm = buffer->lb_buf;
931                 ma->ma_lmm_size = buffer->lb_len;
932                 ma->ma_need = MA_INODE | MA_HSM;
933                 if (ma->ma_lmm_size > 0)
934                         ma->ma_need |= MA_LOV;
935         }
936
937         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
938             reqbody->mbo_valid & OBD_MD_FLDIREA  &&
939             lustre_msg_get_opc(req->rq_reqmsg) == MDS_GETATTR) {
940                 /* get default stripe info for this dir. */
941                 ma->ma_need |= MA_LOV_DEF;
942         }
943         ma->ma_need |= ma_need;
944         if (ma->ma_need & MA_SOM)
945                 ma->ma_som = &info->mti_u.som.data;
946
947         rc = mdt_attr_get_complex(info, o, ma);
948         if (unlikely(rc)) {
949                 CERROR("%s: getattr error for "DFID": rc = %d\n",
950                        mdt_obd_name(info->mti_mdt),
951                        PFID(mdt_object_fid(o)), rc);
952                 RETURN(rc);
953         }
954
955         /* if file is released, check if a restore is running */
956         if ((ma->ma_valid & MA_HSM) && (ma->ma_hsm.mh_flags & HS_RELEASED) &&
957             mdt_hsm_restore_is_running(info, mdt_object_fid(o))) {
958                 repbody->mbo_t_state = MS_RESTORE;
959                 repbody->mbo_valid |= OBD_MD_TSTATE;
960         }
961
962         is_root = lu_fid_eq(mdt_object_fid(o), &info->mti_mdt->mdt_md_root_fid);
963
964         /* the Lustre protocol supposes to return default striping
965          * on the user-visible root if explicitly requested */
966         if ((ma->ma_valid & MA_LOV) == 0 && S_ISDIR(la->la_mode) &&
967             (ma->ma_need & MA_LOV_DEF && is_root) && ma->ma_need & MA_LOV) {
968                 struct lu_fid      rootfid;
969                 struct mdt_object *root;
970                 struct mdt_device *mdt = info->mti_mdt;
971
972                 rc = dt_root_get(env, mdt->mdt_bottom, &rootfid);
973                 if (rc)
974                         RETURN(rc);
975                 root = mdt_object_find(env, mdt, &rootfid);
976                 if (IS_ERR(root))
977                         RETURN(PTR_ERR(root));
978                 rc = mdt_stripe_get(info, root, ma, XATTR_NAME_LOV);
979                 mdt_object_put(info->mti_env, root);
980                 if (unlikely(rc)) {
981                         CERROR("%s: getattr error for "DFID": rc = %d\n",
982                                mdt_obd_name(info->mti_mdt),
983                                PFID(mdt_object_fid(o)), rc);
984                         RETURN(rc);
985                 }
986         }
987
988         if (likely(ma->ma_valid & MA_INODE))
989                 mdt_pack_attr2body(info, repbody, la, mdt_object_fid(o));
990         else
991                 RETURN(-EFAULT);
992
993         if (mdt_body_has_lov(la, reqbody)) {
994                 if (ma->ma_valid & MA_LOV) {
995                         LASSERT(ma->ma_lmm_size);
996                         repbody->mbo_eadatasize = ma->ma_lmm_size;
997                         if (S_ISDIR(la->la_mode))
998                                 repbody->mbo_valid |= OBD_MD_FLDIREA;
999                         else
1000                                 repbody->mbo_valid |= OBD_MD_FLEASIZE;
1001                         mdt_dump_lmm(D_INFO, ma->ma_lmm, repbody->mbo_valid);
1002                 }
1003                 if (ma->ma_valid & MA_LMV) {
1004                         /* Return -ENOTSUPP for old client */
1005                         if (!mdt_is_striped_client(req->rq_export))
1006                                 RETURN(-ENOTSUPP);
1007
1008                         LASSERT(S_ISDIR(la->la_mode));
1009                         mdt_dump_lmv(D_INFO, ma->ma_lmv);
1010                         repbody->mbo_eadatasize = ma->ma_lmv_size;
1011                         repbody->mbo_valid |= (OBD_MD_FLDIREA|OBD_MD_MEA);
1012                 }
1013                 if (ma->ma_valid & MA_LMV_DEF) {
1014                         /* Return -ENOTSUPP for old client */
1015                         if (!mdt_is_striped_client(req->rq_export))
1016                                 RETURN(-ENOTSUPP);
1017                         LASSERT(S_ISDIR(la->la_mode));
1018                         repbody->mbo_eadatasize = ma->ma_lmv_size;
1019                         repbody->mbo_valid |= (OBD_MD_FLDIREA |
1020                                                OBD_MD_DEFAULT_MEA);
1021                 }
1022         } else if (S_ISLNK(la->la_mode) &&
1023                    reqbody->mbo_valid & OBD_MD_LINKNAME) {
1024                 buffer->lb_buf = ma->ma_lmm;
1025                 /* eadatasize from client includes NULL-terminator, so
1026                  * there is no need to read it */
1027                 buffer->lb_len = reqbody->mbo_eadatasize - 1;
1028                 rc = mo_readlink(env, next, buffer);
1029                 if (unlikely(rc <= 0)) {
1030                         CERROR("%s: readlink failed for "DFID": rc = %d\n",
1031                                mdt_obd_name(info->mti_mdt),
1032                                PFID(mdt_object_fid(o)), rc);
1033                         rc = -EFAULT;
1034                 } else {
1035                         int print_limit = min_t(int, PAGE_CACHE_SIZE - 128, rc);
1036
1037                         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READLINK_EPROTO))
1038                                 rc -= 2;
1039                         repbody->mbo_valid |= OBD_MD_LINKNAME;
1040                         /* we need to report back size with NULL-terminator
1041                          * because client expects that */
1042                         repbody->mbo_eadatasize = rc + 1;
1043                         if (repbody->mbo_eadatasize != reqbody->mbo_eadatasize)
1044                                 CDEBUG(D_INODE, "%s: Read shorter symlink %d "
1045                                        "on "DFID ", expected %d\n",
1046                                        mdt_obd_name(info->mti_mdt),
1047                                        rc, PFID(mdt_object_fid(o)),
1048                                        reqbody->mbo_eadatasize - 1);
1049                         /* NULL terminate */
1050                         ((char *)ma->ma_lmm)[rc] = 0;
1051
1052                         /* If the total CDEBUG() size is larger than a page, it
1053                          * will print a warning to the console, avoid this by
1054                          * printing just the last part of the symlink. */
1055                         CDEBUG(D_INODE, "symlink dest %s%.*s, len = %d\n",
1056                                print_limit < rc ? "..." : "", print_limit,
1057                                (char *)ma->ma_lmm + rc - print_limit, rc);
1058                         rc = 0;
1059                 }
1060         }
1061
1062         if (reqbody->mbo_valid & OBD_MD_FLMODEASIZE) {
1063                 repbody->mbo_max_cookiesize = 0;
1064                 repbody->mbo_max_mdsize = info->mti_mdt->mdt_max_mdsize;
1065                 repbody->mbo_valid |= OBD_MD_FLMODEASIZE;
1066                 CDEBUG(D_INODE, "I am going to change the MAX_MD_SIZE & "
1067                        "MAX_COOKIE to : %d:%d\n", repbody->mbo_max_mdsize,
1068                        repbody->mbo_max_cookiesize);
1069         }
1070
1071         if (exp_connect_rmtclient(info->mti_exp) &&
1072             reqbody->mbo_valid & OBD_MD_FLRMTPERM) {
1073                 void *buf = req_capsule_server_get(pill, &RMF_ACL);
1074
1075                 /* mdt_getattr_lock only */
1076                 rc = mdt_pack_remote_perm(info, o, buf);
1077                 if (rc) {
1078                         repbody->mbo_valid &= ~OBD_MD_FLRMTPERM;
1079                         repbody->mbo_aclsize = 0;
1080                         RETURN(rc);
1081                 } else {
1082                         repbody->mbo_valid |= OBD_MD_FLRMTPERM;
1083                         repbody->mbo_aclsize = sizeof(struct mdt_remote_perm);
1084                 }
1085         }
1086 #ifdef CONFIG_FS_POSIX_ACL
1087         else if ((exp_connect_flags(req->rq_export) & OBD_CONNECT_ACL) &&
1088                  (reqbody->mbo_valid & OBD_MD_FLACL))
1089                 rc = mdt_pack_acl2body(info, repbody, o, nodemap);
1090 #endif
1091
1092         if (reqbody->mbo_valid & OBD_MD_FLMDSCAPA &&
1093             info->mti_mdt->mdt_lut.lut_mds_capa &&
1094             exp_connect_flags(info->mti_exp) & OBD_CONNECT_MDS_CAPA) {
1095                 struct lustre_capa *capa;
1096
1097                 capa = req_capsule_server_get(pill, &RMF_CAPA1);
1098                 LASSERT(capa);
1099                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
1100                 rc = mo_capa_get(env, next, capa, 0);
1101                 if (rc)
1102                         RETURN(rc);
1103                 repbody->mbo_valid |= OBD_MD_FLMDSCAPA;
1104         }
1105
1106 out:
1107         if (rc == 0)
1108                 mdt_counter_incr(req, LPROC_MDT_GETATTR);
1109
1110         RETURN(rc);
1111 }
1112
1113 static int mdt_renew_capa(struct mdt_thread_info *info)
1114 {
1115         struct mdt_object  *obj = info->mti_object;
1116         struct mdt_body    *body;
1117         struct lustre_capa *capa, *c;
1118         int rc;
1119         ENTRY;
1120
1121         /* if object doesn't exist, or server has disabled capability,
1122          * return directly, client will find body->valid OBD_MD_FLOSSCAPA
1123          * flag not set.
1124          */
1125         if (!obj || !info->mti_mdt->mdt_lut.lut_oss_capa ||
1126             !(exp_connect_flags(info->mti_exp) & OBD_CONNECT_OSS_CAPA))
1127                 RETURN(0);
1128
1129         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1130         LASSERT(body != NULL);
1131
1132         c = req_capsule_client_get(info->mti_pill, &RMF_CAPA1);
1133         LASSERT(c);
1134
1135         capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA2);
1136         LASSERT(capa);
1137
1138         *capa = *c;
1139         rc = mo_capa_get(info->mti_env, mdt_object_child(obj), capa, 1);
1140         if (rc == 0)
1141                 body->mbo_valid |= OBD_MD_FLOSSCAPA;
1142         RETURN(rc);
1143 }
1144
1145 static int mdt_getattr(struct tgt_session_info *tsi)
1146 {
1147         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
1148         struct mdt_object       *obj = info->mti_object;
1149         struct req_capsule      *pill = info->mti_pill;
1150         struct mdt_body         *reqbody;
1151         struct mdt_body         *repbody;
1152         int rc, rc2;
1153         ENTRY;
1154
1155         reqbody = req_capsule_client_get(pill, &RMF_MDT_BODY);
1156         LASSERT(reqbody);
1157
1158         if (reqbody->mbo_valid & OBD_MD_FLOSSCAPA) {
1159                 rc = req_capsule_server_pack(pill);
1160                 if (unlikely(rc))
1161                         RETURN(err_serious(rc));
1162                 rc = mdt_renew_capa(info);
1163                 GOTO(out_shrink, rc);
1164         }
1165
1166         LASSERT(obj != NULL);
1167         LASSERT(lu_object_assert_exists(&obj->mot_obj));
1168
1169         /* Unlike intent case where we need to pre-fill out buffers early on
1170          * in intent policy for ldlm reasons, here we can have a much better
1171          * guess at EA size by just reading it from disk.
1172          * Exceptions are readdir and (missing) directory striping */
1173         /* Readlink */
1174         if (reqbody->mbo_valid & OBD_MD_LINKNAME) {
1175                 /* No easy way to know how long is the symlink, but it cannot
1176                  * be more than PATH_MAX, so we allocate +1 */
1177                 rc = PATH_MAX + 1;
1178
1179         /* A special case for fs ROOT: getattr there might fetch
1180          * default EA for entire fs, not just for this dir!
1181          */
1182         } else if (lu_fid_eq(mdt_object_fid(obj),
1183                              &info->mti_mdt->mdt_md_root_fid) &&
1184                    (reqbody->mbo_valid & OBD_MD_FLDIREA) &&
1185                    (lustre_msg_get_opc(mdt_info_req(info)->rq_reqmsg) ==
1186                                                                  MDS_GETATTR)) {
1187                 /* Should the default strping be bigger, mdt_fix_reply
1188                  * will reallocate */
1189                 rc = DEF_REP_MD_SIZE;
1190         } else {
1191                 /* Read the actual EA size from disk */
1192                 rc = mdt_attr_get_eabuf_size(info, obj);
1193         }
1194
1195         if (rc < 0)
1196                 GOTO(out, rc = err_serious(rc));
1197
1198         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, rc);
1199
1200         rc = req_capsule_server_pack(pill);
1201         if (unlikely(rc != 0))
1202                 GOTO(out, rc = err_serious(rc));
1203
1204         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1205         LASSERT(repbody != NULL);
1206         repbody->mbo_eadatasize = 0;
1207         repbody->mbo_aclsize = 0;
1208
1209         if (reqbody->mbo_valid & OBD_MD_FLRMTPERM)
1210                 rc = mdt_init_ucred(info, reqbody);
1211         else
1212                 rc = mdt_check_ucred(info);
1213         if (unlikely(rc))
1214                 GOTO(out_shrink, rc);
1215
1216         info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
1217
1218         /*
1219          * Don't check capability at all, because rename might getattr for
1220          * remote obj, and at that time no capability is available.
1221          */
1222         mdt_set_capainfo(info, 1, &reqbody->mbo_fid1, BYPASS_CAPA);
1223         rc = mdt_getattr_internal(info, obj, 0);
1224         if (reqbody->mbo_valid & OBD_MD_FLRMTPERM)
1225                 mdt_exit_ucred(info);
1226         EXIT;
1227 out_shrink:
1228         mdt_client_compatibility(info);
1229         rc2 = mdt_fix_reply(info);
1230         if (rc == 0)
1231                 rc = rc2;
1232 out:
1233         mdt_thread_info_fini(info);
1234         return rc;
1235 }
1236
1237 /**
1238  * Exchange MOF_LOV_CREATED flags between two objects after a
1239  * layout swap. No assumption is made on whether o1 or o2 have
1240  * created objects or not.
1241  *
1242  * \param[in,out] o1    First swap layout object
1243  * \param[in,out] o2    Second swap layout object
1244  */
1245 static void mdt_swap_lov_flag(struct mdt_object *o1, struct mdt_object *o2)
1246 {
1247         __u64   o1_flags;
1248
1249         mutex_lock(&o1->mot_lov_mutex);
1250         mutex_lock(&o2->mot_lov_mutex);
1251
1252         o1_flags = o1->mot_flags;
1253         o1->mot_flags = (o1->mot_flags & ~MOF_LOV_CREATED) |
1254                         (o2->mot_flags & MOF_LOV_CREATED);
1255
1256         o2->mot_flags = (o2->mot_flags & ~MOF_LOV_CREATED) |
1257                         (o1_flags & MOF_LOV_CREATED);
1258
1259         mutex_unlock(&o2->mot_lov_mutex);
1260         mutex_unlock(&o1->mot_lov_mutex);
1261 }
1262
1263 static int mdt_swap_layouts(struct tgt_session_info *tsi)
1264 {
1265         struct mdt_thread_info  *info;
1266         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1267         struct obd_export       *exp = req->rq_export;
1268         struct mdt_object       *o1, *o2, *o;
1269         struct mdt_lock_handle  *lh1, *lh2;
1270         struct mdc_swap_layouts *msl;
1271         int                      rc;
1272         ENTRY;
1273
1274         /* client does not support layout lock, so layout swaping
1275          * is disabled.
1276          * FIXME: there is a problem for old clients which don't support
1277          * layout lock yet. If those clients have already opened the file
1278          * they won't be notified at all so that old layout may still be
1279          * used to do IO. This can be fixed after file release is landed by
1280          * doing exclusive open and taking full EX ibits lock. - Jinshan */
1281         if (!exp_connect_layout(exp))
1282                 RETURN(-EOPNOTSUPP);
1283
1284         info = tsi2mdt_info(tsi);
1285
1286         if (info->mti_dlm_req != NULL)
1287                 ldlm_request_cancel(req, info->mti_dlm_req, 0, LATF_SKIP);
1288
1289         if (req_capsule_get_size(info->mti_pill, &RMF_CAPA1, RCL_CLIENT))
1290                 mdt_set_capainfo(info, 0, &info->mti_body->mbo_fid1,
1291                                  req_capsule_client_get(info->mti_pill,
1292                                                         &RMF_CAPA1));
1293
1294         if (req_capsule_get_size(info->mti_pill, &RMF_CAPA2, RCL_CLIENT))
1295                 mdt_set_capainfo(info, 1, &info->mti_body->mbo_fid2,
1296                                  req_capsule_client_get(info->mti_pill,
1297                                                         &RMF_CAPA2));
1298
1299         o1 = info->mti_object;
1300         o = o2 = mdt_object_find(info->mti_env, info->mti_mdt,
1301                                 &info->mti_body->mbo_fid2);
1302         if (IS_ERR(o))
1303                 GOTO(out, rc = PTR_ERR(o));
1304
1305         if (mdt_object_remote(o) || !mdt_object_exists(o)) /* remote object */
1306                 GOTO(put, rc = -ENOENT);
1307
1308         rc = lu_fid_cmp(&info->mti_body->mbo_fid1, &info->mti_body->mbo_fid2);
1309         if (unlikely(rc == 0)) /* same file, you kidding me? no-op. */
1310                 GOTO(put, rc);
1311
1312         if (rc < 0)
1313                 swap(o1, o2);
1314
1315         /* permission check. Make sure the calling process having permission
1316          * to write both files. */
1317         rc = mo_permission(info->mti_env, NULL, mdt_object_child(o1), NULL,
1318                                 MAY_WRITE);
1319         if (rc < 0)
1320                 GOTO(put, rc);
1321
1322         rc = mo_permission(info->mti_env, NULL, mdt_object_child(o2), NULL,
1323                                 MAY_WRITE);
1324         if (rc < 0)
1325                 GOTO(put, rc);
1326
1327         msl = req_capsule_client_get(info->mti_pill, &RMF_SWAP_LAYOUTS);
1328         if (msl == NULL)
1329                 GOTO(put, rc = -EPROTO);
1330
1331         lh1 = &info->mti_lh[MDT_LH_NEW];
1332         mdt_lock_reg_init(lh1, LCK_EX);
1333         lh2 = &info->mti_lh[MDT_LH_OLD];
1334         mdt_lock_reg_init(lh2, LCK_EX);
1335
1336         rc = mdt_object_lock(info, o1, lh1, MDS_INODELOCK_LAYOUT |
1337                              MDS_INODELOCK_XATTR, MDT_LOCAL_LOCK);
1338         if (rc < 0)
1339                 GOTO(put, rc);
1340
1341         rc = mdt_object_lock(info, o2, lh2, MDS_INODELOCK_LAYOUT |
1342                              MDS_INODELOCK_XATTR, MDT_LOCAL_LOCK);
1343         if (rc < 0)
1344                 GOTO(unlock1, rc);
1345
1346         rc = mo_swap_layouts(info->mti_env, mdt_object_child(o1),
1347                              mdt_object_child(o2), msl->msl_flags);
1348         if (rc < 0)
1349                 GOTO(unlock2, rc);
1350
1351         mdt_swap_lov_flag(o1, o2);
1352
1353 unlock2:
1354         mdt_object_unlock(info, o2, lh2, rc);
1355 unlock1:
1356         mdt_object_unlock(info, o1, lh1, rc);
1357 put:
1358         mdt_object_put(info->mti_env, o);
1359 out:
1360         mdt_thread_info_fini(info);
1361         RETURN(rc);
1362 }
1363
1364 static int mdt_raw_lookup(struct mdt_thread_info *info,
1365                           struct mdt_object *parent,
1366                           const struct lu_name *lname,
1367                           struct ldlm_reply *ldlm_rep)
1368 {
1369         struct lu_fid   *child_fid = &info->mti_tmp_fid1;
1370         int              rc;
1371         ENTRY;
1372
1373         LASSERT(!info->mti_cross_ref);
1374
1375         /* Only got the fid of this obj by name */
1376         fid_zero(child_fid);
1377         rc = mdo_lookup(info->mti_env, mdt_object_child(info->mti_object),
1378                         lname, child_fid, &info->mti_spec);
1379         if (rc == 0) {
1380                 struct mdt_body *repbody;
1381
1382                 repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1383                 repbody->mbo_fid1 = *child_fid;
1384                 repbody->mbo_valid = OBD_MD_FLID;
1385                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1386         } else if (rc == -ENOENT) {
1387                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
1388         }
1389
1390         RETURN(rc);
1391 }
1392
1393 /*
1394  * UPDATE lock should be taken against parent, and be release before exit;
1395  * child_bits lock should be taken against child, and be returned back:
1396  *            (1)normal request should release the child lock;
1397  *            (2)intent request will grant the lock to client.
1398  */
1399 static int mdt_getattr_name_lock(struct mdt_thread_info *info,
1400                                  struct mdt_lock_handle *lhc,
1401                                  __u64 child_bits,
1402                                  struct ldlm_reply *ldlm_rep)
1403 {
1404         struct ptlrpc_request  *req       = mdt_info_req(info);
1405         struct mdt_body        *reqbody   = NULL;
1406         struct mdt_object      *parent    = info->mti_object;
1407         struct mdt_object      *child;
1408         struct lu_fid          *child_fid = &info->mti_tmp_fid1;
1409         struct lu_name         *lname     = NULL;
1410         struct mdt_lock_handle *lhp       = NULL;
1411         struct ldlm_lock       *lock;
1412         bool                    is_resent;
1413         bool                    try_layout;
1414         int                     ma_need = 0;
1415         int                     rc;
1416         ENTRY;
1417
1418         is_resent = lustre_handle_is_used(&lhc->mlh_reg_lh);
1419         LASSERT(ergo(is_resent,
1420                      lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT));
1421
1422         if (parent == NULL)
1423                 RETURN(-ENOENT);
1424
1425         if (info->mti_cross_ref) {
1426                 /* Only getattr on the child. Parent is on another node. */
1427                 mdt_set_disposition(info, ldlm_rep,
1428                                     DISP_LOOKUP_EXECD | DISP_LOOKUP_POS);
1429                 child = parent;
1430                 CDEBUG(D_INODE, "partial getattr_name child_fid = "DFID", "
1431                        "ldlm_rep = %p\n",
1432                        PFID(mdt_object_fid(child)), ldlm_rep);
1433
1434                 rc = mdt_check_resent_lock(info, child, lhc);
1435                 if (rc < 0) {
1436                         RETURN(rc);
1437                 } else if (rc > 0) {
1438                         mdt_lock_handle_init(lhc);
1439                         mdt_lock_reg_init(lhc, LCK_PR);
1440
1441                         /*
1442                          * Object's name is on another MDS, no lookup or layout
1443                          * lock is needed here but update lock is.
1444                          */
1445                         child_bits &= ~(MDS_INODELOCK_LOOKUP |
1446                                         MDS_INODELOCK_LAYOUT);
1447                         child_bits |= MDS_INODELOCK_PERM | MDS_INODELOCK_UPDATE;
1448
1449                         rc = mdt_object_lock(info, child, lhc, child_bits,
1450                                              MDT_LOCAL_LOCK);
1451                         if (rc < 0)
1452                                 RETURN(rc);
1453                 }
1454
1455                 /* Finally, we can get attr for child. */
1456                 if (!mdt_object_exists(child)) {
1457                         LU_OBJECT_DEBUG(D_INFO, info->mti_env,
1458                                         &child->mot_obj,
1459                                         "remote object doesn't exist.\n");
1460                         mdt_object_unlock(info, child, lhc, 1);
1461                         RETURN(-ENOENT);
1462                 }
1463
1464                 mdt_set_capainfo(info, 0, mdt_object_fid(child), BYPASS_CAPA);
1465                 rc = mdt_getattr_internal(info, child, 0);
1466                 if (unlikely(rc != 0))
1467                         mdt_object_unlock(info, child, lhc, 1);
1468
1469                 RETURN(rc);
1470         }
1471
1472         lname = &info->mti_name;
1473         mdt_name_unpack(info->mti_pill, &RMF_NAME, lname, MNF_FIX_ANON);
1474
1475         if (lu_name_is_valid(lname)) {
1476                 CDEBUG(D_INODE, "getattr with lock for "DFID"/"DNAME", "
1477                        "ldlm_rep = %p\n", PFID(mdt_object_fid(parent)),
1478                        PNAME(lname), ldlm_rep);
1479         } else {
1480                 reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1481                 if (unlikely(reqbody == NULL))
1482                         RETURN(err_serious(-EPROTO));
1483
1484                 *child_fid = reqbody->mbo_fid2;
1485
1486                 if (unlikely(!fid_is_sane(child_fid)))
1487                         RETURN(err_serious(-EINVAL));
1488
1489                 CDEBUG(D_INODE, "getattr with lock for "DFID"/"DFID", "
1490                        "ldlm_rep = %p\n",
1491                        PFID(mdt_object_fid(parent)),
1492                        PFID(&reqbody->mbo_fid2), ldlm_rep);
1493         }
1494
1495         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_EXECD);
1496
1497         if (unlikely(!mdt_object_exists(parent)) && lu_name_is_valid(lname)) {
1498                 LU_OBJECT_DEBUG(D_INODE, info->mti_env,
1499                                 &parent->mot_obj,
1500                                 "Parent doesn't exist!\n");
1501                 RETURN(-ESTALE);
1502         }
1503
1504         if (mdt_object_remote(parent)) {
1505                 CERROR("%s: parent "DFID" is on remote target\n",
1506                        mdt_obd_name(info->mti_mdt),
1507                        PFID(mdt_object_fid(parent)));
1508                 RETURN(-EIO);
1509         }
1510
1511         if (lu_name_is_valid(lname)) {
1512                 /* Always allow to lookup ".." */
1513                 if (unlikely(lname->ln_namelen == 2 &&
1514                              lname->ln_name[0] == '.' &&
1515                              lname->ln_name[1] == '.'))
1516                         info->mti_spec.sp_permitted = 1;
1517
1518                 if (info->mti_body->mbo_valid == OBD_MD_FLID) {
1519                         rc = mdt_raw_lookup(info, parent, lname, ldlm_rep);
1520
1521                         RETURN(rc);
1522                 }
1523
1524                 /* step 1: lock parent only if parent is a directory */
1525                 if (S_ISDIR(lu_object_attr(&parent->mot_obj))) {
1526                         lhp = &info->mti_lh[MDT_LH_PARENT];
1527                         mdt_lock_pdo_init(lhp, LCK_PR, lname);
1528                         rc = mdt_object_lock(info, parent, lhp,
1529                                              MDS_INODELOCK_UPDATE,
1530                                              MDT_LOCAL_LOCK);
1531                         if (unlikely(rc != 0))
1532                                 RETURN(rc);
1533                 }
1534
1535                 /* step 2: lookup child's fid by name */
1536                 fid_zero(child_fid);
1537                 rc = mdo_lookup(info->mti_env, mdt_object_child(parent), lname,
1538                                 child_fid, &info->mti_spec);
1539                 if (rc == -ENOENT)
1540                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
1541
1542                 if (rc != 0)
1543                         GOTO(out_parent, rc);
1544         }
1545
1546         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1547
1548         /*
1549          *step 3: find the child object by fid & lock it.
1550          *        regardless if it is local or remote.
1551          *
1552          *Note: LU-3240 (commit 762f2114d282a98ebfa4dbbeea9298a8088ad24e)
1553          *      set parent dir fid the same as child fid in getattr by fid case
1554          *      we should not lu_object_find() the object again, could lead
1555          *      to hung if there is a concurrent unlink destroyed the object.
1556          */
1557         if (lu_fid_eq(mdt_object_fid(parent), child_fid)) {
1558                 mdt_object_get(info->mti_env, parent);
1559                 child = parent;
1560         } else {
1561                 child = mdt_object_find(info->mti_env, info->mti_mdt,
1562                                         child_fid);
1563         }
1564
1565         if (unlikely(IS_ERR(child)))
1566                 GOTO(out_parent, rc = PTR_ERR(child));
1567
1568         rc = mdt_check_resent_lock(info, child, lhc);
1569         if (rc < 0) {
1570                 GOTO(out_child, rc);
1571         } else if (rc > 0) {
1572                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_RESEND, obd_timeout*2);
1573                 mdt_lock_handle_init(lhc);
1574                 mdt_lock_reg_init(lhc, LCK_PR);
1575                 try_layout = false;
1576
1577                 if (!mdt_object_exists(child)) {
1578                         LU_OBJECT_DEBUG(D_INODE, info->mti_env,
1579                                         &child->mot_obj,
1580                                         "Object doesn't exist!\n");
1581                         GOTO(out_child, rc = -ENOENT);
1582                 }
1583
1584                 if (!(child_bits & MDS_INODELOCK_UPDATE) &&
1585                       mdt_object_exists(child) && !mdt_object_remote(child)) {
1586                         struct md_attr *ma = &info->mti_attr;
1587
1588                         ma->ma_valid = 0;
1589                         ma->ma_need = MA_INODE;
1590                         rc = mdt_attr_get_complex(info, child, ma);
1591                         if (unlikely(rc != 0))
1592                                 GOTO(out_child, rc);
1593
1594                         /* If the file has not been changed for some time, we
1595                          * return not only a LOOKUP lock, but also an UPDATE
1596                          * lock and this might save us RPC on later STAT. For
1597                          * directories, it also let negative dentry cache start
1598                          * working for this dir. */
1599                         if (ma->ma_valid & MA_INODE &&
1600                             ma->ma_attr.la_valid & LA_CTIME &&
1601                             info->mti_mdt->mdt_namespace->ns_ctime_age_limit +
1602                                 ma->ma_attr.la_ctime < cfs_time_current_sec())
1603                                 child_bits |= MDS_INODELOCK_UPDATE;
1604                 }
1605
1606                 /* layout lock must be granted in a best-effort way
1607                  * for IT operations */
1608                 LASSERT(!(child_bits & MDS_INODELOCK_LAYOUT));
1609                 if (!OBD_FAIL_CHECK(OBD_FAIL_MDS_NO_LL_GETATTR) &&
1610                     exp_connect_layout(info->mti_exp) &&
1611                     S_ISREG(lu_object_attr(&child->mot_obj)) &&
1612                     !mdt_object_remote(child) && ldlm_rep != NULL) {
1613                         /* try to grant layout lock for regular file. */
1614                         try_layout = true;
1615                 }
1616
1617                 rc = 0;
1618                 if (try_layout) {
1619                         child_bits |= MDS_INODELOCK_LAYOUT;
1620                         /* try layout lock, it may fail to be granted due to
1621                          * contention at LOOKUP or UPDATE */
1622                         if (!mdt_object_lock_try(info, child, lhc, child_bits,
1623                                                  MDT_CROSS_LOCK)) {
1624                                 child_bits &= ~MDS_INODELOCK_LAYOUT;
1625                                 LASSERT(child_bits != 0);
1626                                 rc = mdt_object_lock(info, child, lhc,
1627                                                 child_bits, MDT_CROSS_LOCK);
1628                         } else {
1629                                 ma_need |= MA_LOV;
1630                         }
1631                 } else {
1632                         /* Do not enqueue the UPDATE lock from MDT(cross-MDT),
1633                          * client will enqueue the lock to the remote MDT */
1634                         if (mdt_object_remote(child))
1635                                 child_bits &= ~MDS_INODELOCK_UPDATE;
1636                         rc = mdt_object_lock(info, child, lhc, child_bits,
1637                                                 MDT_CROSS_LOCK);
1638                 }
1639                 if (unlikely(rc != 0))
1640                         GOTO(out_child, rc);
1641         }
1642
1643         lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1644         /* Get MA_SOM attributes if update lock is given. */
1645         if (lock &&
1646             lock->l_policy_data.l_inodebits.bits & MDS_INODELOCK_UPDATE &&
1647             S_ISREG(lu_object_attr(&mdt_object_child(child)->mo_lu)))
1648                 ma_need |= MA_SOM;
1649
1650         /* finally, we can get attr for child. */
1651         mdt_set_capainfo(info, 1, child_fid, BYPASS_CAPA);
1652         rc = mdt_getattr_internal(info, child, ma_need);
1653         if (unlikely(rc != 0)) {
1654                 mdt_object_unlock(info, child, lhc, 1);
1655         } else if (lock) {
1656                 /* Debugging code. */
1657                 LDLM_DEBUG(lock, "Returning lock to client");
1658                 LASSERTF(fid_res_name_eq(mdt_object_fid(child),
1659                                          &lock->l_resource->lr_name),
1660                          "Lock res_id: "DLDLMRES", fid: "DFID"\n",
1661                          PLDLMRES(lock->l_resource),
1662                          PFID(mdt_object_fid(child)));
1663                 if (mdt_object_exists(child) && !mdt_object_remote(child))
1664                         mdt_pack_size2body(info, child);
1665         }
1666         if (lock)
1667                 LDLM_LOCK_PUT(lock);
1668
1669         EXIT;
1670 out_child:
1671         mdt_object_put(info->mti_env, child);
1672 out_parent:
1673         if (lhp)
1674                 mdt_object_unlock(info, parent, lhp, 1);
1675         return rc;
1676 }
1677
1678 /* normal handler: should release the child lock */
1679 static int mdt_getattr_name(struct tgt_session_info *tsi)
1680 {
1681         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
1682         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_CHILD];
1683         struct mdt_body        *reqbody;
1684         struct mdt_body        *repbody;
1685         int rc, rc2;
1686         ENTRY;
1687
1688         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1689         LASSERT(reqbody != NULL);
1690         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1691         LASSERT(repbody != NULL);
1692
1693         info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
1694         repbody->mbo_eadatasize = 0;
1695         repbody->mbo_aclsize = 0;
1696
1697         rc = mdt_init_ucred(info, reqbody);
1698         if (unlikely(rc))
1699                 GOTO(out_shrink, rc);
1700
1701         rc = mdt_getattr_name_lock(info, lhc, MDS_INODELOCK_UPDATE, NULL);
1702         if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
1703                 ldlm_lock_decref(&lhc->mlh_reg_lh, lhc->mlh_reg_mode);
1704                 lhc->mlh_reg_lh.cookie = 0;
1705         }
1706         mdt_exit_ucred(info);
1707         EXIT;
1708 out_shrink:
1709         mdt_client_compatibility(info);
1710         rc2 = mdt_fix_reply(info);
1711         if (rc == 0)
1712                 rc = rc2;
1713         mdt_thread_info_fini(info);
1714         return rc;
1715 }
1716
1717 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
1718                          void *karg, void *uarg);
1719
1720 static int mdt_set_info(struct tgt_session_info *tsi)
1721 {
1722         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1723         char                    *key;
1724         void                    *val;
1725         int                      keylen, vallen, rc = 0;
1726
1727         ENTRY;
1728
1729         key = req_capsule_client_get(tsi->tsi_pill, &RMF_SETINFO_KEY);
1730         if (key == NULL) {
1731                 DEBUG_REQ(D_HA, req, "no set_info key");
1732                 RETURN(err_serious(-EFAULT));
1733         }
1734
1735         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_SETINFO_KEY,
1736                                       RCL_CLIENT);
1737
1738         val = req_capsule_client_get(tsi->tsi_pill, &RMF_SETINFO_VAL);
1739         if (val == NULL) {
1740                 DEBUG_REQ(D_HA, req, "no set_info val");
1741                 RETURN(err_serious(-EFAULT));
1742         }
1743
1744         vallen = req_capsule_get_size(tsi->tsi_pill, &RMF_SETINFO_VAL,
1745                                       RCL_CLIENT);
1746
1747         /* Swab any part of val you need to here */
1748         if (KEY_IS(KEY_READ_ONLY)) {
1749                 spin_lock(&req->rq_export->exp_lock);
1750                 if (*(__u32 *)val)
1751                         *exp_connect_flags_ptr(req->rq_export) |=
1752                                 OBD_CONNECT_RDONLY;
1753                 else
1754                         *exp_connect_flags_ptr(req->rq_export) &=
1755                                 ~OBD_CONNECT_RDONLY;
1756                 spin_unlock(&req->rq_export->exp_lock);
1757         } else if (KEY_IS(KEY_CHANGELOG_CLEAR)) {
1758                 struct changelog_setinfo *cs = val;
1759
1760                 if (vallen != sizeof(*cs)) {
1761                         CERROR("%s: bad changelog_clear setinfo size %d\n",
1762                                tgt_name(tsi->tsi_tgt), vallen);
1763                         RETURN(-EINVAL);
1764                 }
1765                 if (ptlrpc_req_need_swab(req)) {
1766                         __swab64s(&cs->cs_recno);
1767                         __swab32s(&cs->cs_id);
1768                 }
1769
1770                 rc = mdt_iocontrol(OBD_IOC_CHANGELOG_CLEAR, req->rq_export,
1771                                    vallen, val, NULL);
1772         } else {
1773                 RETURN(-EINVAL);
1774         }
1775         RETURN(rc);
1776 }
1777
1778 static int mdt_readpage(struct tgt_session_info *tsi)
1779 {
1780         struct mdt_thread_info  *info = mdt_th_info(tsi->tsi_env);
1781         struct mdt_object       *object = mdt_obj(tsi->tsi_corpus);
1782         struct lu_rdpg          *rdpg = &info->mti_u.rdpg.mti_rdpg;
1783         const struct mdt_body   *reqbody = tsi->tsi_mdt_body;
1784         struct mdt_body         *repbody;
1785         int                      rc;
1786         int                      i;
1787
1788         ENTRY;
1789
1790         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READPAGE_PACK))
1791                 RETURN(err_serious(-ENOMEM));
1792
1793         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_MDT_BODY);
1794         if (repbody == NULL || reqbody == NULL)
1795                 RETURN(err_serious(-EFAULT));
1796
1797         /*
1798          * prepare @rdpg before calling lower layers and transfer itself. Here
1799          * reqbody->size contains offset of where to start to read and
1800          * reqbody->nlink contains number bytes to read.
1801          */
1802         rdpg->rp_hash = reqbody->mbo_size;
1803         if (rdpg->rp_hash != reqbody->mbo_size) {
1804                 CERROR("Invalid hash: "LPX64" != "LPX64"\n",
1805                        rdpg->rp_hash, reqbody->mbo_size);
1806                 RETURN(-EFAULT);
1807         }
1808
1809         rdpg->rp_attrs = reqbody->mbo_mode;
1810         if (exp_connect_flags(tsi->tsi_exp) & OBD_CONNECT_64BITHASH)
1811                 rdpg->rp_attrs |= LUDA_64BITHASH;
1812         rdpg->rp_count  = min_t(unsigned int, reqbody->mbo_nlink,
1813                                 exp_max_brw_size(tsi->tsi_exp));
1814         rdpg->rp_npages = (rdpg->rp_count + PAGE_CACHE_SIZE - 1) >>
1815                           PAGE_CACHE_SHIFT;
1816         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1817         if (rdpg->rp_pages == NULL)
1818                 RETURN(-ENOMEM);
1819
1820         for (i = 0; i < rdpg->rp_npages; ++i) {
1821                 rdpg->rp_pages[i] = alloc_page(GFP_IOFS);
1822                 if (rdpg->rp_pages[i] == NULL)
1823                         GOTO(free_rdpg, rc = -ENOMEM);
1824         }
1825
1826         /* call lower layers to fill allocated pages with directory data */
1827         rc = mo_readpage(tsi->tsi_env, mdt_object_child(object), rdpg);
1828         if (rc < 0)
1829                 GOTO(free_rdpg, rc);
1830
1831         /* send pages to client */
1832         rc = tgt_sendpage(tsi, rdpg, rc);
1833
1834         EXIT;
1835 free_rdpg:
1836
1837         for (i = 0; i < rdpg->rp_npages; i++)
1838                 if (rdpg->rp_pages[i] != NULL)
1839                         __free_page(rdpg->rp_pages[i]);
1840         OBD_FREE(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1841
1842         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE))
1843                 RETURN(0);
1844
1845         return rc;
1846 }
1847
1848 static int mdt_reint_internal(struct mdt_thread_info *info,
1849                               struct mdt_lock_handle *lhc,
1850                               __u32 op)
1851 {
1852         struct req_capsule      *pill = info->mti_pill;
1853         struct mdt_body         *repbody;
1854         int                      rc = 0, rc2;
1855
1856         ENTRY;
1857
1858         rc = mdt_reint_unpack(info, op);
1859         if (rc != 0) {
1860                 CERROR("Can't unpack reint, rc %d\n", rc);
1861                 RETURN(err_serious(rc));
1862         }
1863
1864         /* for replay (no_create) lmm is not needed, client has it already */
1865         if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1866                 req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
1867                                      DEF_REP_MD_SIZE);
1868
1869         /* llog cookies are always 0, the field is kept for compatibility */
1870         if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
1871                 req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER, 0);
1872
1873         rc = req_capsule_server_pack(pill);
1874         if (rc != 0) {
1875                 CERROR("Can't pack response, rc %d\n", rc);
1876                 RETURN(err_serious(rc));
1877         }
1878
1879         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_SERVER)) {
1880                 repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1881                 LASSERT(repbody);
1882                 repbody->mbo_eadatasize = 0;
1883                 repbody->mbo_aclsize = 0;
1884         }
1885
1886         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_REINT_DELAY, 10);
1887
1888         /* for replay no cookkie / lmm need, because client have this already */
1889         if (info->mti_spec.no_create)
1890                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1891                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, 0);
1892
1893         rc = mdt_init_ucred_reint(info);
1894         if (rc)
1895                 GOTO(out_shrink, rc);
1896
1897         rc = mdt_fix_attr_ucred(info, op);
1898         if (rc != 0)
1899                 GOTO(out_ucred, rc = err_serious(rc));
1900
1901         if (mdt_check_resent(info, mdt_reconstruct, lhc)) {
1902                 DEBUG_REQ(D_INODE, mdt_info_req(info), "resent opt.");
1903                 rc = lustre_msg_get_status(mdt_info_req(info)->rq_repmsg);
1904                 GOTO(out_ucred, rc);
1905         }
1906         rc = mdt_reint_rec(info, lhc);
1907         EXIT;
1908 out_ucred:
1909         mdt_exit_ucred(info);
1910 out_shrink:
1911         mdt_client_compatibility(info);
1912         rc2 = mdt_fix_reply(info);
1913         if (rc == 0)
1914                 rc = rc2;
1915         return rc;
1916 }
1917
1918 static long mdt_reint_opcode(struct ptlrpc_request *req,
1919                              const struct req_format **fmt)
1920 {
1921         struct mdt_device       *mdt;
1922         struct mdt_rec_reint    *rec;
1923         long                     opc;
1924
1925         rec = req_capsule_client_get(&req->rq_pill, &RMF_REC_REINT);
1926         if (rec != NULL) {
1927                 opc = rec->rr_opcode;
1928                 DEBUG_REQ(D_INODE, req, "reint opt = %ld", opc);
1929                 if (opc < REINT_MAX && fmt[opc] != NULL)
1930                         req_capsule_extend(&req->rq_pill, fmt[opc]);
1931                 else {
1932                         mdt = mdt_exp2dev(req->rq_export);
1933                         CERROR("%s: Unsupported opcode '%ld' from client '%s':"
1934                                " rc = %d\n", req->rq_export->exp_obd->obd_name,
1935                                opc, mdt->mdt_ldlm_client->cli_name, -EFAULT);
1936                         opc = err_serious(-EFAULT);
1937                 }
1938         } else {
1939                 opc = err_serious(-EFAULT);
1940         }
1941         return opc;
1942 }
1943
1944 static int mdt_reint(struct tgt_session_info *tsi)
1945 {
1946         long opc;
1947         int  rc;
1948         static const struct req_format *reint_fmts[REINT_MAX] = {
1949                 [REINT_SETATTR]  = &RQF_MDS_REINT_SETATTR,
1950                 [REINT_CREATE]   = &RQF_MDS_REINT_CREATE,
1951                 [REINT_LINK]     = &RQF_MDS_REINT_LINK,
1952                 [REINT_UNLINK]   = &RQF_MDS_REINT_UNLINK,
1953                 [REINT_RENAME]   = &RQF_MDS_REINT_RENAME,
1954                 [REINT_OPEN]     = &RQF_MDS_REINT_OPEN,
1955                 [REINT_SETXATTR] = &RQF_MDS_REINT_SETXATTR,
1956                 [REINT_RMENTRY]  = &RQF_MDS_REINT_UNLINK,
1957                 [REINT_MIGRATE]  = &RQF_MDS_REINT_RENAME
1958         };
1959
1960         ENTRY;
1961
1962         opc = mdt_reint_opcode(tgt_ses_req(tsi), reint_fmts);
1963         if (opc >= 0) {
1964                 struct mdt_thread_info *info = tsi2mdt_info(tsi);
1965                 /*
1966                  * No lock possible here from client to pass it to reint code
1967                  * path.
1968                  */
1969                 rc = mdt_reint_internal(info, NULL, opc);
1970                 mdt_thread_info_fini(info);
1971         } else {
1972                 rc = opc;
1973         }
1974
1975         tsi->tsi_reply_fail_id = OBD_FAIL_MDS_REINT_NET_REP;
1976         RETURN(rc);
1977 }
1978
1979 /* this should sync the whole device */
1980 static int mdt_device_sync(const struct lu_env *env, struct mdt_device *mdt)
1981 {
1982         struct dt_device *dt = mdt->mdt_bottom;
1983         int rc;
1984         ENTRY;
1985
1986         rc = dt->dd_ops->dt_sync(env, dt);
1987         RETURN(rc);
1988 }
1989
1990 /* this should sync this object */
1991 static int mdt_object_sync(struct mdt_thread_info *info)
1992 {
1993         struct md_object *next;
1994         int rc;
1995         ENTRY;
1996
1997         if (!mdt_object_exists(info->mti_object)) {
1998                 CWARN("%s: non existing object "DFID": rc = %d\n",
1999                       mdt_obd_name(info->mti_mdt),
2000                       PFID(mdt_object_fid(info->mti_object)), -ESTALE);
2001                 RETURN(-ESTALE);
2002         }
2003         next = mdt_object_child(info->mti_object);
2004         rc = mo_object_sync(info->mti_env, next);
2005
2006         RETURN(rc);
2007 }
2008
2009 static int mdt_sync(struct tgt_session_info *tsi)
2010 {
2011         struct ptlrpc_request   *req = tgt_ses_req(tsi);
2012         struct req_capsule      *pill = tsi->tsi_pill;
2013         struct mdt_body         *body;
2014         int                      rc;
2015
2016         ENTRY;
2017
2018         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SYNC_PACK))
2019                 RETURN(err_serious(-ENOMEM));
2020
2021         if (fid_seq(&tsi->tsi_mdt_body->mbo_fid1) == 0) {
2022                 rc = mdt_device_sync(tsi->tsi_env, mdt_exp2dev(tsi->tsi_exp));
2023         } else {
2024                 struct mdt_thread_info *info = tsi2mdt_info(tsi);
2025
2026                 /* sync an object */
2027                 rc = mdt_object_sync(info);
2028                 if (rc == 0) {
2029                         const struct lu_fid *fid;
2030                         struct lu_attr *la = &info->mti_attr.ma_attr;
2031
2032                         info->mti_attr.ma_need = MA_INODE;
2033                         info->mti_attr.ma_valid = 0;
2034                         rc = mdt_attr_get_complex(info, info->mti_object,
2035                                                   &info->mti_attr);
2036                         if (rc == 0) {
2037                                 body = req_capsule_server_get(pill,
2038                                                               &RMF_MDT_BODY);
2039                                 fid = mdt_object_fid(info->mti_object);
2040                                 mdt_pack_attr2body(info, body, la, fid);
2041                         }
2042                 }
2043                 mdt_thread_info_fini(info);
2044         }
2045         if (rc == 0)
2046                 mdt_counter_incr(req, LPROC_MDT_SYNC);
2047
2048         RETURN(rc);
2049 }
2050
2051 /*
2052  * Handle quota control requests to consult current usage/limit, but also
2053  * to configure quota enforcement
2054  */
2055 static int mdt_quotactl(struct tgt_session_info *tsi)
2056 {
2057         struct obd_export       *exp  = tsi->tsi_exp;
2058         struct req_capsule      *pill = tsi->tsi_pill;
2059         struct obd_quotactl     *oqctl, *repoqc;
2060         int                      id, rc;
2061         struct mdt_device       *mdt = mdt_exp2dev(exp);
2062         struct lu_device        *qmt = mdt->mdt_qmt_dev;
2063         struct lu_nodemap       *nodemap = exp->exp_target_data.ted_nodemap;
2064         ENTRY;
2065
2066         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
2067         if (oqctl == NULL)
2068                 RETURN(err_serious(-EPROTO));
2069
2070         rc = req_capsule_server_pack(pill);
2071         if (rc)
2072                 RETURN(err_serious(rc));
2073
2074         switch (oqctl->qc_cmd) {
2075         case Q_QUOTACHECK:
2076         case LUSTRE_Q_INVALIDATE:
2077         case LUSTRE_Q_FINVALIDATE:
2078         case Q_QUOTAON:
2079         case Q_QUOTAOFF:
2080         case Q_INITQUOTA:
2081                 /* deprecated, not used any more */
2082                 RETURN(-EOPNOTSUPP);
2083                 /* master quotactl */
2084         case Q_SETINFO:
2085         case Q_SETQUOTA:
2086                 if (!nodemap_can_setquota(nodemap))
2087                         RETURN(-EPERM);
2088         case Q_GETINFO:
2089         case Q_GETQUOTA:
2090                 if (qmt == NULL)
2091                         RETURN(-EOPNOTSUPP);
2092                 /* slave quotactl */
2093         case Q_GETOINFO:
2094         case Q_GETOQUOTA:
2095                 break;
2096         default:
2097                 CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
2098                 RETURN(-EFAULT);
2099         }
2100
2101         /* map uid/gid for remote client */
2102         id = oqctl->qc_id;
2103         if (exp_connect_rmtclient(exp)) {
2104                 struct lustre_idmap_table *idmap;
2105
2106                 idmap = exp->exp_mdt_data.med_idmap;
2107
2108                 if (unlikely(oqctl->qc_cmd != Q_GETQUOTA &&
2109                              oqctl->qc_cmd != Q_GETINFO))
2110                         RETURN(-EPERM);
2111
2112                 if (oqctl->qc_type == USRQUOTA)
2113                         id = lustre_idmap_lookup_uid(NULL, idmap, 0,
2114                                                      oqctl->qc_id);
2115                 else if (oqctl->qc_type == GRPQUOTA)
2116                         id = lustre_idmap_lookup_gid(NULL, idmap, 0,
2117                                                      oqctl->qc_id);
2118                 else
2119                         RETURN(-EINVAL);
2120
2121                 if (id == CFS_IDMAP_NOTFOUND) {
2122                         CDEBUG(D_QUOTA, "no mapping for id %u\n", oqctl->qc_id);
2123                         RETURN(-EACCES);
2124                 }
2125         }
2126
2127         if (oqctl->qc_type == USRQUOTA)
2128                 id = nodemap_map_id(nodemap, NODEMAP_UID,
2129                                     NODEMAP_CLIENT_TO_FS, id);
2130         else if (oqctl->qc_type == GRPQUOTA)
2131                 id = nodemap_map_id(nodemap, NODEMAP_UID,
2132                                     NODEMAP_CLIENT_TO_FS, id);
2133
2134         repoqc = req_capsule_server_get(pill, &RMF_OBD_QUOTACTL);
2135         if (repoqc == NULL)
2136                 RETURN(err_serious(-EFAULT));
2137
2138         if (oqctl->qc_id != id)
2139                 swap(oqctl->qc_id, id);
2140
2141         switch (oqctl->qc_cmd) {
2142
2143         case Q_GETINFO:
2144         case Q_SETINFO:
2145         case Q_SETQUOTA:
2146         case Q_GETQUOTA:
2147                 /* forward quotactl request to QMT */
2148                 rc = qmt_hdls.qmth_quotactl(tsi->tsi_env, qmt, oqctl);
2149                 break;
2150
2151         case Q_GETOINFO:
2152         case Q_GETOQUOTA:
2153                 /* slave quotactl */
2154                 rc = lquotactl_slv(tsi->tsi_env, tsi->tsi_tgt->lut_bottom,
2155                                    oqctl);
2156                 break;
2157
2158         default:
2159                 CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
2160                 RETURN(-EFAULT);
2161         }
2162
2163         if (oqctl->qc_id != id)
2164                 swap(oqctl->qc_id, id);
2165
2166         *repoqc = *oqctl;
2167         RETURN(rc);
2168 }
2169
2170 /** clone llog ctxt from child (mdd)
2171  * This allows remote llog (replicator) access.
2172  * We can either pass all llog RPCs (eg mdt_llog_create) on to child where the
2173  * context was originally set up, or we can handle them directly.
2174  * I choose the latter, but that means I need any llog
2175  * contexts set up by child to be accessable by the mdt.  So we clone the
2176  * context into our context list here.
2177  */
2178 static int mdt_llog_ctxt_clone(const struct lu_env *env, struct mdt_device *mdt,
2179                                int idx)
2180 {
2181         struct md_device  *next = mdt->mdt_child;
2182         struct llog_ctxt *ctxt;
2183         int rc;
2184
2185         if (!llog_ctxt_null(mdt2obd_dev(mdt), idx))
2186                 return 0;
2187
2188         rc = next->md_ops->mdo_llog_ctxt_get(env, next, idx, (void **)&ctxt);
2189         if (rc || ctxt == NULL) {
2190                 return 0;
2191         }
2192
2193         rc = llog_group_set_ctxt(&mdt2obd_dev(mdt)->obd_olg, ctxt, idx);
2194         if (rc)
2195                 CERROR("Can't set mdt ctxt %d\n", rc);
2196
2197         return rc;
2198 }
2199
2200 static int mdt_llog_ctxt_unclone(const struct lu_env *env,
2201                                  struct mdt_device *mdt, int idx)
2202 {
2203         struct llog_ctxt *ctxt;
2204
2205         ctxt = llog_get_context(mdt2obd_dev(mdt), idx);
2206         if (ctxt == NULL)
2207                 return 0;
2208         /* Put once for the get we just did, and once for the clone */
2209         llog_ctxt_put(ctxt);
2210         llog_ctxt_put(ctxt);
2211         return 0;
2212 }
2213
2214 /*
2215  * sec context handlers
2216  */
2217 static int mdt_sec_ctx_handle(struct tgt_session_info *tsi)
2218 {
2219         int rc;
2220
2221         rc = mdt_handle_idmap(tsi);
2222         if (unlikely(rc)) {
2223                 struct ptlrpc_request   *req = tgt_ses_req(tsi);
2224                 __u32                    opc;
2225
2226                 opc = lustre_msg_get_opc(req->rq_reqmsg);
2227                 if (opc == SEC_CTX_INIT || opc == SEC_CTX_INIT_CONT)
2228                         sptlrpc_svc_ctx_invalidate(req);
2229         }
2230
2231         CFS_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, cfs_fail_val);
2232
2233         return rc;
2234 }
2235
2236 /*
2237  * quota request handlers
2238  */
2239 static int mdt_quota_dqacq(struct tgt_session_info *tsi)
2240 {
2241         struct mdt_device       *mdt = mdt_exp2dev(tsi->tsi_exp);
2242         struct lu_device        *qmt = mdt->mdt_qmt_dev;
2243         int                      rc;
2244         ENTRY;
2245
2246         if (qmt == NULL)
2247                 RETURN(err_serious(-EOPNOTSUPP));
2248
2249         rc = qmt_hdls.qmth_dqacq(tsi->tsi_env, qmt, tgt_ses_req(tsi));
2250         RETURN(rc);
2251 }
2252
2253 struct mdt_object *mdt_object_new(const struct lu_env *env,
2254                                   struct mdt_device *d,
2255                                   const struct lu_fid *f)
2256 {
2257         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
2258         struct lu_object *o;
2259         struct mdt_object *m;
2260         ENTRY;
2261
2262         CDEBUG(D_INFO, "Allocate object for "DFID"\n", PFID(f));
2263         o = lu_object_find(env, &d->mdt_lu_dev, f, &conf);
2264         if (unlikely(IS_ERR(o)))
2265                 m = (struct mdt_object *)o;
2266         else
2267                 m = mdt_obj(o);
2268         RETURN(m);
2269 }
2270
2271 struct mdt_object *mdt_object_find(const struct lu_env *env,
2272                                    struct mdt_device *d,
2273                                    const struct lu_fid *f)
2274 {
2275         struct lu_object *o;
2276         struct mdt_object *m;
2277         ENTRY;
2278
2279         CDEBUG(D_INFO, "Find object for "DFID"\n", PFID(f));
2280         o = lu_object_find(env, &d->mdt_lu_dev, f, NULL);
2281         if (unlikely(IS_ERR(o)))
2282                 m = (struct mdt_object *)o;
2283         else
2284                 m = mdt_obj(o);
2285
2286         RETURN(m);
2287 }
2288
2289 /**
2290  * Asyncronous commit for mdt device.
2291  *
2292  * Pass asynchonous commit call down the MDS stack.
2293  *
2294  * \param env environment
2295  * \param mdt the mdt device
2296  */
2297 static void mdt_device_commit_async(const struct lu_env *env,
2298                                     struct mdt_device *mdt)
2299 {
2300         struct dt_device *dt = mdt->mdt_bottom;
2301         int rc;
2302
2303         rc = dt->dd_ops->dt_commit_async(env, dt);
2304         if (unlikely(rc != 0))
2305                 CWARN("%s: async commit start failed: rc = %d\n",
2306                       mdt_obd_name(mdt), rc);
2307 }
2308
2309 /**
2310  * Mark the lock as "synchonous".
2311  *
2312  * Mark the lock to deffer transaction commit to the unlock time.
2313  *
2314  * \param lock the lock to mark as "synchonous"
2315  *
2316  * \see mdt_is_lock_sync
2317  * \see mdt_save_lock
2318  */
2319 static inline void mdt_set_lock_sync(struct ldlm_lock *lock)
2320 {
2321         lock->l_ast_data = (void*)1;
2322 }
2323
2324 /**
2325  * Check whehter the lock "synchonous" or not.
2326  *
2327  * \param lock the lock to check
2328  * \retval 1 the lock is "synchonous"
2329  * \retval 0 the lock isn't "synchronous"
2330  *
2331  * \see mdt_set_lock_sync
2332  * \see mdt_save_lock
2333  */
2334 static inline int mdt_is_lock_sync(struct ldlm_lock *lock)
2335 {
2336         return lock->l_ast_data != NULL;
2337 }
2338
2339 /**
2340  * Blocking AST for mdt locks.
2341  *
2342  * Starts transaction commit if in case of COS lock conflict or
2343  * deffers such a commit to the mdt_save_lock.
2344  *
2345  * \param lock the lock which blocks a request or cancelling lock
2346  * \param desc unused
2347  * \param data unused
2348  * \param flag indicates whether this cancelling or blocking callback
2349  * \retval 0
2350  * \see ldlm_blocking_ast_nocheck
2351  */
2352 int mdt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2353                      void *data, int flag)
2354 {
2355         struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
2356         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2357         int rc;
2358         ENTRY;
2359
2360         if (flag == LDLM_CB_CANCELING)
2361                 RETURN(0);
2362         lock_res_and_lock(lock);
2363         if (lock->l_blocking_ast != mdt_blocking_ast) {
2364                 unlock_res_and_lock(lock);
2365                 RETURN(0);
2366         }
2367         if (mdt_cos_is_enabled(mdt) &&
2368             lock->l_req_mode & (LCK_PW | LCK_EX) &&
2369             lock->l_blocking_lock != NULL &&
2370             lock->l_client_cookie != lock->l_blocking_lock->l_client_cookie) {
2371                 mdt_set_lock_sync(lock);
2372         }
2373         rc = ldlm_blocking_ast_nocheck(lock);
2374
2375         /* There is no lock conflict if l_blocking_lock == NULL,
2376          * it indicates a blocking ast sent from ldlm_lock_decref_internal
2377          * when the last reference to a local lock was released */
2378         if (lock->l_req_mode == LCK_COS && lock->l_blocking_lock != NULL) {
2379                 struct lu_env env;
2380
2381                 rc = lu_env_init(&env, LCT_LOCAL);
2382                 if (unlikely(rc != 0))
2383                         CWARN("%s: lu_env initialization failed, cannot "
2384                               "start asynchronous commit: rc = %d\n",
2385                               obd->obd_name, rc);
2386                 else
2387                         mdt_device_commit_async(&env, mdt);
2388                 lu_env_fini(&env);
2389         }
2390         RETURN(rc);
2391 }
2392
2393 /* Used for cross-MDT lock */
2394 int mdt_remote_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2395                             void *data, int flag)
2396 {
2397         struct lustre_handle lockh;
2398         int               rc;
2399
2400         switch (flag) {
2401         case LDLM_CB_BLOCKING:
2402                 ldlm_lock2handle(lock, &lockh);
2403                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
2404                 if (rc < 0) {
2405                         CDEBUG(D_INODE, "ldlm_cli_cancel: %d\n", rc);
2406                         RETURN(rc);
2407                 }
2408                 break;
2409         case LDLM_CB_CANCELING:
2410                 LDLM_DEBUG(lock, "Revoke remote lock\n");
2411                 break;
2412         default:
2413                 LBUG();
2414         }
2415         RETURN(0);
2416 }
2417
2418 int mdt_check_resent_lock(struct mdt_thread_info *info,
2419                           struct mdt_object *mo,
2420                           struct mdt_lock_handle *lhc)
2421 {
2422         /* the lock might already be gotten in ldlm_handle_enqueue() */
2423         if (unlikely(lustre_handle_is_used(&lhc->mlh_reg_lh))) {
2424                 struct ptlrpc_request *req = mdt_info_req(info);
2425                 struct ldlm_lock      *lock;
2426
2427                 lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
2428                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT);
2429                 if (lock == NULL) {
2430                         /* Lock is pinned by ldlm_handle_enqueue0() as it is
2431                          * a resend case, however, it could be already destroyed
2432                          * due to client eviction or a raced cancel RPC. */
2433                         LDLM_DEBUG_NOLOCK("Invalid lock handle "LPX64"\n",
2434                                           lhc->mlh_reg_lh.cookie);
2435                         RETURN(-ESTALE);
2436                 }
2437
2438                 if (!fid_res_name_eq(mdt_object_fid(mo),
2439                                      &lock->l_resource->lr_name)) {
2440                         CWARN("%s: Although resent, but still not "
2441                               "get child lock:"DFID"\n",
2442                               info->mti_exp->exp_obd->obd_name,
2443                               PFID(mdt_object_fid(mo)));
2444                         LDLM_LOCK_PUT(lock);
2445                         RETURN(-EPROTO);
2446                 }
2447                 LDLM_LOCK_PUT(lock);
2448                 return 0;
2449         }
2450         return 1;
2451 }
2452
2453 int mdt_remote_object_lock(struct mdt_thread_info *mti,
2454                            struct mdt_object *o, const struct lu_fid *fid,
2455                            struct lustre_handle *lh, ldlm_mode_t mode,
2456                            __u64 ibits)
2457 {
2458         struct ldlm_enqueue_info *einfo = &mti->mti_einfo;
2459         ldlm_policy_data_t *policy = &mti->mti_policy;
2460         struct ldlm_res_id *res_id = &mti->mti_res_id;
2461         int rc = 0;
2462         ENTRY;
2463
2464         LASSERT(mdt_object_remote(o));
2465
2466         LASSERT(ibits == MDS_INODELOCK_UPDATE);
2467
2468         fid_build_reg_res_name(fid, res_id);
2469
2470         memset(einfo, 0, sizeof(*einfo));
2471         einfo->ei_type = LDLM_IBITS;
2472         einfo->ei_mode = mode;
2473         einfo->ei_cb_bl = mdt_remote_blocking_ast;
2474         einfo->ei_cb_cp = ldlm_completion_ast;
2475         einfo->ei_enq_slave = 0;
2476         einfo->ei_res_id = res_id;
2477
2478         memset(policy, 0, sizeof(*policy));
2479         policy->l_inodebits.bits = ibits;
2480
2481         rc = mo_object_lock(mti->mti_env, mdt_object_child(o), lh, einfo,
2482                             policy);
2483         RETURN(rc);
2484 }
2485
2486 static int mdt_object_local_lock(struct mdt_thread_info *info,
2487                                  struct mdt_object *o,
2488                                  struct mdt_lock_handle *lh, __u64 ibits,
2489                                  bool nonblock, int locality)
2490 {
2491         struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
2492         ldlm_policy_data_t *policy = &info->mti_policy;
2493         struct ldlm_res_id *res_id = &info->mti_res_id;
2494         __u64 dlmflags;
2495         int rc;
2496         ENTRY;
2497
2498         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2499         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2500         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
2501         LASSERT(lh->mlh_type != MDT_NUL_LOCK);
2502
2503         /* Only enqueue LOOKUP lock for remote object */
2504         if (mdt_object_remote(o))
2505                 LASSERT(ibits == MDS_INODELOCK_LOOKUP);
2506
2507         if (lh->mlh_type == MDT_PDO_LOCK) {
2508                 /* check for exists after object is locked */
2509                 if (mdt_object_exists(o) == 0) {
2510                         /* Non-existent object shouldn't have PDO lock */
2511                         RETURN(-ESTALE);
2512                 } else {
2513                         /* Non-dir object shouldn't have PDO lock */
2514                         if (!S_ISDIR(lu_object_attr(&o->mot_obj)))
2515                                 RETURN(-ENOTDIR);
2516                 }
2517         }
2518
2519         memset(policy, 0, sizeof(*policy));
2520         fid_build_reg_res_name(mdt_object_fid(o), res_id);
2521
2522         dlmflags = LDLM_FL_ATOMIC_CB;
2523         if (nonblock)
2524                 dlmflags |= LDLM_FL_BLOCK_NOWAIT;
2525
2526         /*
2527          * Take PDO lock on whole directory and build correct @res_id for lock
2528          * on part of directory.
2529          */
2530         if (lh->mlh_pdo_hash != 0) {
2531                 LASSERT(lh->mlh_type == MDT_PDO_LOCK);
2532                 mdt_lock_pdo_mode(info, o, lh);
2533                 if (lh->mlh_pdo_mode != LCK_NL) {
2534                         /*
2535                          * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
2536                          * is never going to be sent to client and we do not
2537                          * want it slowed down due to possible cancels.
2538                          */
2539                         policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
2540                         rc = mdt_fid_lock(ns, &lh->mlh_pdo_lh, lh->mlh_pdo_mode,
2541                                           policy, res_id, dlmflags,
2542                                           info->mti_exp == NULL ? NULL :
2543                                           &info->mti_exp->exp_handle.h_cookie);
2544                         if (unlikely(rc != 0))
2545                                 GOTO(out_unlock, rc);
2546                 }
2547
2548                 /*
2549                  * Finish res_id initializing by name hash marking part of
2550                  * directory which is taking modification.
2551                  */
2552                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
2553         }
2554
2555         policy->l_inodebits.bits = ibits;
2556
2557         /*
2558          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
2559          * going to be sent to client. If it is - mdt_intent_policy() path will
2560          * fix it up and turn FL_LOCAL flag off.
2561          */
2562         rc = mdt_fid_lock(ns, &lh->mlh_reg_lh, lh->mlh_reg_mode, policy,
2563                           res_id, LDLM_FL_LOCAL_ONLY | dlmflags,
2564                           info->mti_exp == NULL ? NULL :
2565                           &info->mti_exp->exp_handle.h_cookie);
2566 out_unlock:
2567         if (rc != 0)
2568                 mdt_object_unlock(info, o, lh, 1);
2569         else if (unlikely(OBD_FAIL_PRECHECK(OBD_FAIL_MDS_PDO_LOCK)) &&
2570                    lh->mlh_pdo_hash != 0 &&
2571                    (lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX))
2572                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_PDO_LOCK, 15);
2573
2574         RETURN(rc);
2575 }
2576
2577 static int
2578 mdt_object_lock_internal(struct mdt_thread_info *info, struct mdt_object *o,
2579                          struct mdt_lock_handle *lh, __u64 ibits,
2580                          bool nonblock, int locality)
2581 {
2582         int rc;
2583         ENTRY;
2584
2585         if (!mdt_object_remote(o))
2586                 return mdt_object_local_lock(info, o, lh, ibits, nonblock,
2587                                              locality);
2588
2589         if (locality == MDT_LOCAL_LOCK) {
2590                 CERROR("%s: try to get local lock for remote object"
2591                        DFID".\n", mdt_obd_name(info->mti_mdt),
2592                        PFID(mdt_object_fid(o)));
2593                 RETURN(-EPROTO);
2594         }
2595
2596         /* XXX do not support PERM/LAYOUT/XATTR lock for remote object yet */
2597         ibits &= ~(MDS_INODELOCK_PERM | MDS_INODELOCK_LAYOUT |
2598                    MDS_INODELOCK_XATTR);
2599         if (ibits & MDS_INODELOCK_UPDATE) {
2600                 /* Sigh, PDO needs to enqueue 2 locks right now, but
2601                  * enqueue RPC can only request 1 lock, to avoid extra
2602                  * RPC, so it will instead enqueue EX lock for remote
2603                  * object anyway XXX*/
2604                 if (lh->mlh_type == MDT_PDO_LOCK &&
2605                     lh->mlh_pdo_hash != 0) {
2606                         CDEBUG(D_INFO, "%s: "DFID" convert PDO lock to"
2607                                "EX lock.\n", mdt_obd_name(info->mti_mdt),
2608                                PFID(mdt_object_fid(o)));
2609                         lh->mlh_pdo_hash = 0;
2610                         lh->mlh_rreg_mode = LCK_EX;
2611                         lh->mlh_type = MDT_REG_LOCK;
2612                 }
2613                 rc = mdt_remote_object_lock(info, o, mdt_object_fid(o),
2614                                             &lh->mlh_rreg_lh,
2615                                             lh->mlh_rreg_mode,
2616                                             MDS_INODELOCK_UPDATE);
2617                 if (rc != ELDLM_OK)
2618                         RETURN(rc);
2619         }
2620
2621         /* Only enqueue LOOKUP lock for remote object */
2622         if (ibits & MDS_INODELOCK_LOOKUP) {
2623                 rc = mdt_object_local_lock(info, o, lh,
2624                                            MDS_INODELOCK_LOOKUP,
2625                                            nonblock, locality);
2626                 if (rc != ELDLM_OK)
2627                         RETURN(rc);
2628         }
2629
2630         RETURN(0);
2631 }
2632
2633 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
2634                     struct mdt_lock_handle *lh, __u64 ibits, int locality)
2635 {
2636         return mdt_object_lock_internal(info, o, lh, ibits, false, locality);
2637 }
2638
2639 int mdt_object_lock_try(struct mdt_thread_info *info, struct mdt_object *o,
2640                         struct mdt_lock_handle *lh, __u64 ibits, int locality)
2641 {
2642         struct mdt_lock_handle tmp = *lh;
2643         int rc;
2644
2645         rc = mdt_object_lock_internal(info, o, &tmp, ibits, true, locality);
2646         if (rc == 0)
2647                 *lh = tmp;
2648
2649         return rc == 0;
2650 }
2651
2652 /**
2653  * Save a lock within request object.
2654  *
2655  * Keep the lock referenced until whether client ACK or transaction
2656  * commit happens or release the lock immediately depending on input
2657  * parameters. If COS is ON, a write lock is converted to COS lock
2658  * before saving.
2659  *
2660  * \param info thead info object
2661  * \param h lock handle
2662  * \param mode lock mode
2663  * \param decref force immediate lock releasing
2664  */
2665 static
2666 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
2667                    ldlm_mode_t mode, int decref)
2668 {
2669         ENTRY;
2670
2671         if (lustre_handle_is_used(h)) {
2672                 if (decref || !info->mti_has_trans ||
2673                     !(mode & (LCK_PW | LCK_EX))){
2674                         mdt_fid_unlock(h, mode);
2675                 } else {
2676                         struct mdt_device *mdt = info->mti_mdt;
2677                         struct ldlm_lock *lock = ldlm_handle2lock(h);
2678                         struct ptlrpc_request *req = mdt_info_req(info);
2679                         int no_ack = 0;
2680
2681                         LASSERTF(lock != NULL, "no lock for cookie "LPX64"\n",
2682                                  h->cookie);
2683                         /* there is no request if mdt_object_unlock() is called
2684                          * from mdt_export_cleanup()->mdt_add_dirty_flag() */
2685                         if (likely(req != NULL)) {
2686                                 CDEBUG(D_HA, "request = %p reply state = %p"
2687                                        " transno = "LPD64"\n", req,
2688                                        req->rq_reply_state, req->rq_transno);
2689                                 if (mdt_cos_is_enabled(mdt)) {
2690                                         no_ack = 1;
2691                                         ldlm_lock_downgrade(lock, LCK_COS);
2692                                         mode = LCK_COS;
2693                                 }
2694                                 ptlrpc_save_lock(req, h, mode, no_ack);
2695                         } else {
2696                                 ldlm_lock_decref(h, mode);
2697                         }
2698                         if (mdt_is_lock_sync(lock)) {
2699                                 CDEBUG(D_HA, "found sync-lock,"
2700                                        " async commit started\n");
2701                                 mdt_device_commit_async(info->mti_env,
2702                                                         mdt);
2703                         }
2704                         LDLM_LOCK_PUT(lock);
2705                 }
2706                 h->cookie = 0ull;
2707         }
2708
2709         EXIT;
2710 }
2711
2712 /**
2713  * Unlock mdt object.
2714  *
2715  * Immeditely release the regular lock and the PDO lock or save the
2716  * lock in reqeuest and keep them referenced until client ACK or
2717  * transaction commit.
2718  *
2719  * \param info thread info object
2720  * \param o mdt object
2721  * \param lh mdt lock handle referencing regular and PDO locks
2722  * \param decref force immediate lock releasing
2723  */
2724 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
2725                        struct mdt_lock_handle *lh, int decref)
2726 {
2727         ENTRY;
2728
2729         mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
2730         mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
2731
2732         if (lustre_handle_is_used(&lh->mlh_rreg_lh))
2733                 ldlm_lock_decref(&lh->mlh_rreg_lh, lh->mlh_rreg_mode);
2734
2735         EXIT;
2736 }
2737
2738 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
2739                                         const struct lu_fid *f,
2740                                         struct mdt_lock_handle *lh,
2741                                         __u64 ibits)
2742 {
2743         struct mdt_object *o;
2744
2745         o = mdt_object_find(info->mti_env, info->mti_mdt, f);
2746         if (!IS_ERR(o)) {
2747                 int rc;
2748
2749                 rc = mdt_object_lock(info, o, lh, ibits,
2750                                      MDT_LOCAL_LOCK);
2751                 if (rc != 0) {
2752                         mdt_object_put(info->mti_env, o);
2753                         o = ERR_PTR(rc);
2754                 }
2755         }
2756         return o;
2757 }
2758
2759 void mdt_object_unlock_put(struct mdt_thread_info * info,
2760                            struct mdt_object * o,
2761                            struct mdt_lock_handle *lh,
2762                            int decref)
2763 {
2764         mdt_object_unlock(info, o, lh, decref);
2765         mdt_object_put(info->mti_env, o);
2766 }
2767
2768 /*
2769  * Generic code handling requests that have struct mdt_body passed in:
2770  *
2771  *  - extract mdt_body from request and save it in @info, if present;
2772  *
2773  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
2774  *  @info;
2775  *
2776  *  - if HABEO_CORPUS flag is set for this request type check whether object
2777  *  actually exists on storage (lu_object_exists()).
2778  *
2779  */
2780 static int mdt_body_unpack(struct mdt_thread_info *info, __u32 flags)
2781 {
2782         const struct mdt_body    *body;
2783         struct mdt_object        *obj;
2784         const struct lu_env      *env;
2785         struct req_capsule       *pill;
2786         int                       rc;
2787         ENTRY;
2788
2789         env = info->mti_env;
2790         pill = info->mti_pill;
2791
2792         body = info->mti_body = req_capsule_client_get(pill, &RMF_MDT_BODY);
2793         if (body == NULL)
2794                 RETURN(-EFAULT);
2795
2796         if (!(body->mbo_valid & OBD_MD_FLID))
2797                 RETURN(0);
2798
2799         if (!fid_is_sane(&body->mbo_fid1)) {
2800                 CERROR("Invalid fid: "DFID"\n", PFID(&body->mbo_fid1));
2801                 RETURN(-EINVAL);
2802         }
2803
2804         /*
2805          * Do not get size or any capa fields before we check that request
2806          * contains capa actually. There are some requests which do not, for
2807          * instance MDS_IS_SUBDIR.
2808          */
2809         if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2810             req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT))
2811                 mdt_set_capainfo(info, 0, &body->mbo_fid1,
2812                                  req_capsule_client_get(pill, &RMF_CAPA1));
2813
2814         obj = mdt_object_find(env, info->mti_mdt, &body->mbo_fid1);
2815         if (!IS_ERR(obj)) {
2816                 if ((flags & HABEO_CORPUS) &&
2817                     !mdt_object_exists(obj)) {
2818                         mdt_object_put(env, obj);
2819                         /* for capability renew ENOENT will be handled in
2820                          * mdt_renew_capa */
2821                         if (body->mbo_valid & OBD_MD_FLOSSCAPA)
2822                                 rc = 0;
2823                         else
2824                                 rc = -ENOENT;
2825                 } else {
2826                         info->mti_object = obj;
2827                         rc = 0;
2828                 }
2829         } else
2830                 rc = PTR_ERR(obj);
2831
2832         RETURN(rc);
2833 }
2834
2835 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags)
2836 {
2837         struct req_capsule *pill = info->mti_pill;
2838         int rc;
2839         ENTRY;
2840
2841         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT))
2842                 rc = mdt_body_unpack(info, flags);
2843         else
2844                 rc = 0;
2845
2846         if (rc == 0 && (flags & HABEO_REFERO)) {
2847                 /* Pack reply. */
2848                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
2849                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
2850                                              DEF_REP_MD_SIZE);
2851                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
2852                         req_capsule_set_size(pill, &RMF_LOGCOOKIES,
2853                                              RCL_SERVER, 0);
2854
2855                 rc = req_capsule_server_pack(pill);
2856         }
2857         RETURN(rc);
2858 }
2859
2860 static int mdt_init_capa_ctxt(const struct lu_env *env, struct mdt_device *m)
2861 {
2862         struct md_device *next = m->mdt_child;
2863
2864         return next->md_ops->mdo_init_capa_ctxt(env, next,
2865                                                 m->mdt_lut.lut_mds_capa,
2866                                                 m->mdt_capa_timeout,
2867                                                 m->mdt_capa_alg,
2868                                                 m->mdt_capa_keys);
2869 }
2870
2871 void mdt_lock_handle_init(struct mdt_lock_handle *lh)
2872 {
2873         lh->mlh_type = MDT_NUL_LOCK;
2874         lh->mlh_reg_lh.cookie = 0ull;
2875         lh->mlh_reg_mode = LCK_MINMODE;
2876         lh->mlh_pdo_lh.cookie = 0ull;
2877         lh->mlh_pdo_mode = LCK_MINMODE;
2878         lh->mlh_rreg_lh.cookie = 0ull;
2879         lh->mlh_rreg_mode = LCK_MINMODE;
2880 }
2881
2882 void mdt_lock_handle_fini(struct mdt_lock_handle *lh)
2883 {
2884         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2885         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2886 }
2887
2888 /*
2889  * Initialize fields of struct mdt_thread_info. Other fields are left in
2890  * uninitialized state, because it's too expensive to zero out whole
2891  * mdt_thread_info (> 1K) on each request arrival.
2892  */
2893 void mdt_thread_info_init(struct ptlrpc_request *req,
2894                           struct mdt_thread_info *info)
2895 {
2896         int i;
2897
2898         info->mti_pill = &req->rq_pill;
2899
2900         /* lock handle */
2901         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2902                 mdt_lock_handle_init(&info->mti_lh[i]);
2903
2904         /* mdt device: it can be NULL while CONNECT */
2905         if (req->rq_export) {
2906                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
2907                 info->mti_exp = req->rq_export;
2908         } else
2909                 info->mti_mdt = NULL;
2910         info->mti_env = req->rq_svc_thread->t_env;
2911         info->mti_transno = lustre_msg_get_transno(req->rq_reqmsg);
2912
2913         memset(&info->mti_attr, 0, sizeof(info->mti_attr));
2914         info->mti_big_buf = LU_BUF_NULL;
2915         info->mti_body = NULL;
2916         info->mti_object = NULL;
2917         info->mti_dlm_req = NULL;
2918         info->mti_has_trans = 0;
2919         info->mti_cross_ref = 0;
2920         info->mti_opdata = 0;
2921         info->mti_big_lmm_used = 0;
2922
2923         info->mti_spec.no_create = 0;
2924         info->mti_spec.sp_rm_entry = 0;
2925         info->mti_spec.sp_permitted = 0;
2926
2927         info->mti_spec.u.sp_ea.eadata = NULL;
2928         info->mti_spec.u.sp_ea.eadatalen = 0;
2929 }
2930
2931 void mdt_thread_info_fini(struct mdt_thread_info *info)
2932 {
2933         int i;
2934
2935         if (info->mti_object != NULL) {
2936                 mdt_object_put(info->mti_env, info->mti_object);
2937                 info->mti_object = NULL;
2938         }
2939
2940         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2941                 mdt_lock_handle_fini(&info->mti_lh[i]);
2942         info->mti_env = NULL;
2943         info->mti_pill = NULL;
2944         info->mti_exp = NULL;
2945
2946         if (unlikely(info->mti_big_buf.lb_buf != NULL))
2947                 lu_buf_free(&info->mti_big_buf);
2948 }
2949
2950 struct mdt_thread_info *tsi2mdt_info(struct tgt_session_info *tsi)
2951 {
2952         struct mdt_thread_info  *mti;
2953         struct lustre_capa      *lc;
2954
2955         mti = mdt_th_info(tsi->tsi_env);
2956         LASSERT(mti != NULL);
2957
2958         mdt_thread_info_init(tgt_ses_req(tsi), mti);
2959         if (tsi->tsi_corpus != NULL) {
2960                 struct req_capsule *pill = tsi->tsi_pill;
2961
2962                 mti->mti_object = mdt_obj(tsi->tsi_corpus);
2963                 lu_object_get(tsi->tsi_corpus);
2964
2965                 /*
2966                  * XXX: must be part of tgt_mdt_body_unpack but moved here
2967                  * due to mdt_set_capainfo().
2968                  */
2969                 if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2970                     req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT) > 0) {
2971                         lc = req_capsule_client_get(pill, &RMF_CAPA1);
2972                         mdt_set_capainfo(mti, 0, &tsi->tsi_mdt_body->mbo_fid1,
2973                                          lc);
2974                 }
2975         }
2976         mti->mti_body = tsi->tsi_mdt_body;
2977         mti->mti_dlm_req = tsi->tsi_dlm_req;
2978
2979         return mti;
2980 }
2981
2982 static int mdt_tgt_connect(struct tgt_session_info *tsi)
2983 {
2984         struct ptlrpc_request   *req = tgt_ses_req(tsi);
2985         int                      rc;
2986
2987         ENTRY;
2988
2989         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_DELAY_CONDITIONAL) &&
2990             cfs_fail_val ==
2991             tsi2mdt_info(tsi)->mti_mdt->mdt_seq_site.ss_node_id)
2992                 schedule_timeout_and_set_state(TASK_UNINTERRUPTIBLE,
2993                         msecs_to_jiffies(3 * MSEC_PER_SEC));
2994
2995         rc = tgt_connect(tsi);
2996         if (rc != 0)
2997                 RETURN(rc);
2998
2999         rc = mdt_init_idmap(tsi);
3000         if (rc != 0)
3001                 GOTO(err, rc);
3002         RETURN(0);
3003 err:
3004         obd_disconnect(class_export_get(req->rq_export));
3005         return rc;
3006 }
3007
3008 enum mdt_it_code {
3009         MDT_IT_OPEN,
3010         MDT_IT_OCREAT,
3011         MDT_IT_CREATE,
3012         MDT_IT_GETATTR,
3013         MDT_IT_READDIR,
3014         MDT_IT_LOOKUP,
3015         MDT_IT_UNLINK,
3016         MDT_IT_TRUNC,
3017         MDT_IT_GETXATTR,
3018         MDT_IT_LAYOUT,
3019         MDT_IT_QUOTA,
3020         MDT_IT_NR
3021 };
3022
3023 static int mdt_intent_getattr(enum mdt_it_code opcode,
3024                               struct mdt_thread_info *info,
3025                               struct ldlm_lock **,
3026                               __u64);
3027
3028 static int mdt_intent_getxattr(enum mdt_it_code opcode,
3029                                 struct mdt_thread_info *info,
3030                                 struct ldlm_lock **lockp,
3031                                 __u64 flags);
3032
3033 static int mdt_intent_layout(enum mdt_it_code opcode,
3034                              struct mdt_thread_info *info,
3035                              struct ldlm_lock **,
3036                              __u64);
3037 static int mdt_intent_reint(enum mdt_it_code opcode,
3038                             struct mdt_thread_info *info,
3039                             struct ldlm_lock **,
3040                             __u64);
3041
3042 static struct mdt_it_flavor {
3043         const struct req_format *it_fmt;
3044         __u32                    it_flags;
3045         int                    (*it_act)(enum mdt_it_code ,
3046                                          struct mdt_thread_info *,
3047                                          struct ldlm_lock **,
3048                                          __u64);
3049         long                     it_reint;
3050 } mdt_it_flavor[] = {
3051         [MDT_IT_OPEN]     = {
3052                 .it_fmt   = &RQF_LDLM_INTENT,
3053                 /*.it_flags = HABEO_REFERO,*/
3054                 .it_flags = 0,
3055                 .it_act   = mdt_intent_reint,
3056                 .it_reint = REINT_OPEN
3057         },
3058         [MDT_IT_OCREAT]   = {
3059                 .it_fmt   = &RQF_LDLM_INTENT,
3060                 /*
3061                  * OCREAT is not a MUTABOR request as if the file
3062                  * already exists.
3063                  * We do the extra check of OBD_CONNECT_RDONLY in
3064                  * mdt_reint_open() when we really need to create
3065                  * the object.
3066                  */
3067                 .it_flags = 0,
3068                 .it_act   = mdt_intent_reint,
3069                 .it_reint = REINT_OPEN
3070         },
3071         [MDT_IT_CREATE]   = {
3072                 .it_fmt   = &RQF_LDLM_INTENT,
3073                 .it_flags = MUTABOR,
3074                 .it_act   = mdt_intent_reint,
3075                 .it_reint = REINT_CREATE
3076         },
3077         [MDT_IT_GETATTR]  = {
3078                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3079                 .it_flags = HABEO_REFERO,
3080                 .it_act   = mdt_intent_getattr
3081         },
3082         [MDT_IT_READDIR]  = {
3083                 .it_fmt   = NULL,
3084                 .it_flags = 0,
3085                 .it_act   = NULL
3086         },
3087         [MDT_IT_LOOKUP]   = {
3088                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3089                 .it_flags = HABEO_REFERO,
3090                 .it_act   = mdt_intent_getattr
3091         },
3092         [MDT_IT_UNLINK]   = {
3093                 .it_fmt   = &RQF_LDLM_INTENT_UNLINK,
3094                 .it_flags = MUTABOR,
3095                 .it_act   = NULL,
3096                 .it_reint = REINT_UNLINK
3097         },
3098         [MDT_IT_TRUNC]    = {
3099                 .it_fmt   = NULL,
3100                 .it_flags = MUTABOR,
3101                 .it_act   = NULL
3102         },
3103         [MDT_IT_GETXATTR] = {
3104                 .it_fmt   = &RQF_LDLM_INTENT_GETXATTR,
3105                 .it_flags = HABEO_CORPUS,
3106                 .it_act   = mdt_intent_getxattr
3107         },
3108         [MDT_IT_LAYOUT] = {
3109                 .it_fmt   = &RQF_LDLM_INTENT_LAYOUT,
3110                 .it_flags = 0,
3111                 .it_act   = mdt_intent_layout
3112         }
3113 };
3114
3115 static int
3116 mdt_intent_lock_replace(struct mdt_thread_info *info,
3117                         struct ldlm_lock **lockp,
3118                         struct mdt_lock_handle *lh,
3119                         __u64 flags)
3120 {
3121         struct ptlrpc_request  *req = mdt_info_req(info);
3122         struct ldlm_lock       *lock = *lockp;
3123         struct ldlm_lock       *new_lock;
3124
3125         /* If possible resent found a lock, @lh is set to its handle */
3126         new_lock = ldlm_handle2lock_long(&lh->mlh_reg_lh, 0);
3127
3128         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY)) {
3129                 lh->mlh_reg_lh.cookie = 0;
3130                 RETURN(0);
3131         }
3132
3133         LASSERTF(new_lock != NULL,
3134                  "lockh "LPX64"\n", lh->mlh_reg_lh.cookie);
3135
3136         /*
3137          * If we've already given this lock to a client once, then we should
3138          * have no readers or writers.  Otherwise, we should have one reader
3139          * _or_ writer ref (which will be zeroed below) before returning the
3140          * lock to a client.
3141          */
3142         if (new_lock->l_export == req->rq_export) {
3143                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
3144         } else {
3145                 LASSERT(new_lock->l_export == NULL);
3146                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
3147         }
3148
3149         *lockp = new_lock;
3150
3151         if (new_lock->l_export == req->rq_export) {
3152                 /*
3153                  * Already gave this to the client, which means that we
3154                  * reconstructed a reply.
3155                  */
3156                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
3157                         MSG_RESENT);
3158
3159                 LDLM_LOCK_RELEASE(new_lock);
3160                 lh->mlh_reg_lh.cookie = 0;
3161                 RETURN(ELDLM_LOCK_REPLACED);
3162         }
3163
3164         /*
3165          * Fixup the lock to be given to the client.
3166          */
3167         lock_res_and_lock(new_lock);
3168         /* Zero new_lock->l_readers and new_lock->l_writers without triggering
3169          * possible blocking AST. */
3170         while (new_lock->l_readers > 0) {
3171                 lu_ref_del(&new_lock->l_reference, "reader", new_lock);
3172                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3173                 new_lock->l_readers--;
3174         }
3175         while (new_lock->l_writers > 0) {
3176                 lu_ref_del(&new_lock->l_reference, "writer", new_lock);
3177                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3178                 new_lock->l_writers--;
3179         }
3180
3181         new_lock->l_export = class_export_lock_get(req->rq_export, new_lock);
3182         new_lock->l_blocking_ast = lock->l_blocking_ast;
3183         new_lock->l_completion_ast = lock->l_completion_ast;
3184         new_lock->l_remote_handle = lock->l_remote_handle;
3185         new_lock->l_flags &= ~LDLM_FL_LOCAL;
3186
3187         unlock_res_and_lock(new_lock);
3188
3189         cfs_hash_add(new_lock->l_export->exp_lock_hash,
3190                      &new_lock->l_remote_handle,
3191                      &new_lock->l_exp_hash);
3192
3193         LDLM_LOCK_RELEASE(new_lock);
3194         lh->mlh_reg_lh.cookie = 0;
3195
3196         RETURN(ELDLM_LOCK_REPLACED);
3197 }
3198
3199 static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
3200                                     struct ldlm_lock *new_lock,
3201                                     struct mdt_lock_handle *lh,
3202                                     __u64 flags)
3203 {
3204         struct ptlrpc_request  *req = mdt_info_req(info);
3205         struct ldlm_request    *dlmreq;
3206
3207         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
3208                 return;
3209
3210         dlmreq = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
3211
3212         /* Check if this is a resend case (MSG_RESENT is set on RPC) and a
3213          * lock was found by ldlm_handle_enqueue(); if so @lh must be
3214          * initialized. */
3215         if (flags & LDLM_FL_RESENT) {
3216                 lh->mlh_reg_lh.cookie = new_lock->l_handle.h_cookie;
3217                 lh->mlh_reg_mode = new_lock->l_granted_mode;
3218
3219                 LDLM_DEBUG(new_lock, "Restoring lock cookie");
3220                 DEBUG_REQ(D_DLMTRACE, req, "restoring lock cookie "LPX64,
3221                           lh->mlh_reg_lh.cookie);
3222                 return;
3223         }
3224
3225         /*
3226          * If the xid matches, then we know this is a resent request, and allow
3227          * it. (It's probably an OPEN, for which we don't send a lock.
3228          */
3229         if (req_xid_is_last(req))
3230                 return;
3231
3232         /*
3233          * This remote handle isn't enqueued, so we never received or processed
3234          * this request.  Clear MSG_RESENT, because it can be handled like any
3235          * normal request now.
3236          */
3237         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
3238
3239         DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle "LPX64,
3240                   dlmreq->lock_handle[0].cookie);
3241 }
3242
3243 static int mdt_intent_getxattr(enum mdt_it_code opcode,
3244                                 struct mdt_thread_info *info,
3245                                 struct ldlm_lock **lockp,
3246                                 __u64 flags)
3247 {
3248         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3249         struct ldlm_reply      *ldlm_rep = NULL;
3250         int rc, grc;
3251
3252         /*
3253          * Initialize lhc->mlh_reg_lh either from a previously granted lock
3254          * (for the resend case) or a new lock. Below we will use it to
3255          * replace the original lock.
3256          */
3257         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3258         if (!lustre_handle_is_used(&lhc->mlh_reg_lh)) {
3259                 mdt_lock_reg_init(lhc, (*lockp)->l_req_mode);
3260                 rc = mdt_object_lock(info, info->mti_object, lhc,
3261                                         MDS_INODELOCK_XATTR,
3262                                         MDT_LOCAL_LOCK);
3263                 if (rc)
3264                         return rc;
3265         }
3266
3267         grc = mdt_getxattr(info);
3268
3269         rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
3270
3271         if (mdt_info_req(info)->rq_repmsg != NULL)
3272                 ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3273         if (ldlm_rep == NULL)
3274                 RETURN(err_serious(-EFAULT));
3275
3276         ldlm_rep->lock_policy_res2 = grc;
3277
3278         return rc;
3279 }
3280
3281 static int mdt_intent_getattr(enum mdt_it_code opcode,
3282                               struct mdt_thread_info *info,
3283                               struct ldlm_lock **lockp,
3284                               __u64 flags)
3285 {
3286         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3287         __u64                   child_bits;
3288         struct ldlm_reply      *ldlm_rep;
3289         struct mdt_body        *reqbody;
3290         struct mdt_body        *repbody;
3291         int                     rc, rc2;
3292         ENTRY;
3293
3294         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
3295         LASSERT(reqbody);
3296
3297         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
3298         LASSERT(repbody);
3299
3300         info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
3301         repbody->mbo_eadatasize = 0;
3302         repbody->mbo_aclsize = 0;
3303
3304         switch (opcode) {
3305         case MDT_IT_LOOKUP:
3306                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_PERM;
3307                 break;
3308         case MDT_IT_GETATTR:
3309                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE |
3310                              MDS_INODELOCK_PERM;
3311                 break;
3312         default:
3313                 CERROR("Unsupported intent (%d)\n", opcode);
3314                 GOTO(out_shrink, rc = -EINVAL);
3315         }
3316
3317         rc = mdt_init_ucred(info, reqbody);
3318         if (rc)
3319                 GOTO(out_shrink, rc);
3320
3321         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3322         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
3323
3324         /* Get lock from request for possible resent case. */
3325         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3326
3327         rc = mdt_getattr_name_lock(info, lhc, child_bits, ldlm_rep);
3328         ldlm_rep->lock_policy_res2 = clear_serious(rc);
3329
3330         if (mdt_get_disposition(ldlm_rep, DISP_LOOKUP_NEG))
3331                 ldlm_rep->lock_policy_res2 = 0;
3332         if (!mdt_get_disposition(ldlm_rep, DISP_LOOKUP_POS) ||
3333             ldlm_rep->lock_policy_res2) {
3334                 lhc->mlh_reg_lh.cookie = 0ull;
3335                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
3336         }
3337
3338         rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
3339         EXIT;
3340 out_ucred:
3341         mdt_exit_ucred(info);
3342 out_shrink:
3343         mdt_client_compatibility(info);
3344         rc2 = mdt_fix_reply(info);
3345         if (rc == 0)
3346                 rc = rc2;
3347         return rc;
3348 }
3349
3350 static int mdt_intent_layout(enum mdt_it_code opcode,
3351                              struct mdt_thread_info *info,
3352                              struct ldlm_lock **lockp,
3353                              __u64 flags)
3354 {
3355         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_LAYOUT];
3356         struct layout_intent *layout;
3357         struct lu_fid *fid;
3358         struct mdt_object *obj = NULL;
3359         int rc = 0;
3360         ENTRY;
3361
3362         if (opcode != MDT_IT_LAYOUT) {
3363                 CERROR("%s: Unknown intent (%d)\n", mdt_obd_name(info->mti_mdt),
3364                         opcode);
3365                 RETURN(-EINVAL);
3366         }
3367
3368         fid = &info->mti_tmp_fid2;
3369         fid_extract_from_res_name(fid, &(*lockp)->l_resource->lr_name);
3370
3371         /* Get lock from request for possible resent case. */
3372         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3373
3374         obj = mdt_object_find(info->mti_env, info->mti_mdt, fid);
3375         if (IS_ERR(obj))
3376                 RETURN(PTR_ERR(obj));
3377
3378         if (mdt_object_exists(obj) && !mdt_object_remote(obj)) {
3379                 /* get the length of lsm */
3380                 rc = mdt_attr_get_eabuf_size(info, obj);
3381                 if (rc < 0) {
3382                         mdt_object_put(info->mti_env, obj);
3383                         RETURN(rc);
3384                 }
3385
3386                 if (rc > info->mti_mdt->mdt_max_mdsize)
3387                         info->mti_mdt->mdt_max_mdsize = rc;
3388         }
3389
3390         mdt_object_put(info->mti_env, obj);
3391
3392         (*lockp)->l_lvb_type = LVB_T_LAYOUT;
3393         req_capsule_set_size(info->mti_pill, &RMF_DLM_LVB, RCL_SERVER, rc);
3394         rc = req_capsule_server_pack(info->mti_pill);
3395         if (rc != 0)
3396                 RETURN(-EINVAL);
3397
3398         if (lustre_handle_is_used(&lhc->mlh_reg_lh))
3399                 rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
3400
3401         layout = req_capsule_client_get(info->mti_pill, &RMF_LAYOUT_INTENT);
3402         LASSERT(layout != NULL);
3403         if (layout->li_opc == LAYOUT_INTENT_ACCESS)
3404                 /* return to normal/resent ldlm handling */
3405                 RETURN(rc);
3406
3407         CERROR("%s: Unsupported layout intent (%d)\n",
3408                 mdt_obd_name(info->mti_mdt), layout->li_opc);
3409         RETURN(-EINVAL);
3410 }
3411
3412 static int mdt_intent_reint(enum mdt_it_code opcode,
3413                             struct mdt_thread_info *info,
3414                             struct ldlm_lock **lockp,
3415                             __u64 flags)
3416 {
3417         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3418         struct ldlm_reply      *rep = NULL;
3419         long                    opc;
3420         int                     rc;
3421
3422         static const struct req_format *intent_fmts[REINT_MAX] = {
3423                 [REINT_CREATE]  = &RQF_LDLM_INTENT_CREATE,
3424                 [REINT_OPEN]    = &RQF_LDLM_INTENT_OPEN
3425         };
3426
3427         ENTRY;
3428
3429         opc = mdt_reint_opcode(mdt_info_req(info), intent_fmts);
3430         if (opc < 0)
3431                 RETURN(opc);
3432
3433         if (mdt_it_flavor[opcode].it_reint != opc) {
3434                 CERROR("Reint code %ld doesn't match intent: %d\n",
3435                        opc, opcode);
3436                 RETURN(err_serious(-EPROTO));
3437         }
3438
3439         /* Get lock from request for possible resent case. */
3440         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3441
3442         rc = mdt_reint_internal(info, lhc, opc);
3443
3444         /* Check whether the reply has been packed successfully. */
3445         if (mdt_info_req(info)->rq_repmsg != NULL)
3446                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3447         if (rep == NULL)
3448                 RETURN(err_serious(-EFAULT));
3449
3450         /* MDC expects this in any case */
3451         if (rc != 0)
3452                 mdt_set_disposition(info, rep, DISP_LOOKUP_EXECD);
3453
3454         /* the open lock or the lock for cross-ref object should be
3455          * returned to the client */
3456         if (lustre_handle_is_used(&lhc->mlh_reg_lh) &&
3457             (rc == 0 || rc == -MDT_EREMOTE_OPEN)) {
3458                 rep->lock_policy_res2 = 0;
3459                 rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
3460                 RETURN(rc);
3461         }
3462
3463         rep->lock_policy_res2 = clear_serious(rc);
3464
3465         if (rep->lock_policy_res2 == -ENOENT &&
3466             mdt_get_disposition(rep, DISP_LOOKUP_NEG))
3467                 rep->lock_policy_res2 = 0;
3468
3469         lhc->mlh_reg_lh.cookie = 0ull;
3470         if (rc == -ENOTCONN || rc == -ENODEV ||
3471             rc == -EOVERFLOW) { /**< if VBR failure then return error */
3472                 /*
3473                  * If it is the disconnect error (ENODEV & ENOCONN), the error
3474                  * will be returned by rq_status, and client at ptlrpc layer
3475                  * will detect this, then disconnect, reconnect the import
3476                  * immediately, instead of impacting the following the rpc.
3477                  */
3478                 RETURN(rc);
3479         }
3480         /*
3481          * For other cases, the error will be returned by intent, and client
3482          * will retrieve the result from intent.
3483          */
3484         RETURN(ELDLM_LOCK_ABORTED);
3485 }
3486
3487 static int mdt_intent_code(long itcode)
3488 {
3489         int rc;
3490
3491         switch(itcode) {
3492         case IT_OPEN:
3493                 rc = MDT_IT_OPEN;
3494                 break;
3495         case IT_OPEN|IT_CREAT:
3496                 rc = MDT_IT_OCREAT;
3497                 break;
3498         case IT_CREAT:
3499                 rc = MDT_IT_CREATE;
3500                 break;
3501         case IT_READDIR:
3502                 rc = MDT_IT_READDIR;
3503                 break;
3504         case IT_GETATTR:
3505                 rc = MDT_IT_GETATTR;
3506                 break;
3507         case IT_LOOKUP:
3508                 rc = MDT_IT_LOOKUP;
3509                 break;
3510         case IT_UNLINK:
3511                 rc = MDT_IT_UNLINK;
3512                 break;
3513         case IT_TRUNC:
3514                 rc = MDT_IT_TRUNC;
3515                 break;
3516         case IT_GETXATTR:
3517                 rc = MDT_IT_GETXATTR;
3518                 break;
3519         case IT_LAYOUT:
3520                 rc = MDT_IT_LAYOUT;
3521                 break;
3522         case IT_QUOTA_DQACQ:
3523         case IT_QUOTA_CONN:
3524                 rc = MDT_IT_QUOTA;
3525                 break;
3526         default:
3527                 CERROR("Unknown intent opcode: %ld\n", itcode);
3528                 rc = -EINVAL;
3529                 break;
3530         }
3531         return rc;
3532 }
3533
3534 static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
3535                           struct ldlm_lock **lockp, __u64 flags)
3536 {
3537         struct req_capsule      *pill = info->mti_pill;
3538         struct ptlrpc_request   *req = mdt_info_req(info);
3539         struct mdt_it_flavor    *flv;
3540         int opc;
3541         int rc;
3542         ENTRY;
3543
3544         opc = mdt_intent_code(itopc);
3545         if (opc < 0)
3546                 RETURN(-EINVAL);
3547
3548         if (opc == MDT_IT_QUOTA) {
3549                 struct lu_device *qmt = info->mti_mdt->mdt_qmt_dev;
3550
3551                 if (qmt == NULL)
3552                         RETURN(-EOPNOTSUPP);
3553
3554                 (*lockp)->l_lvb_type = LVB_T_LQUOTA;
3555                 /* pass the request to quota master */
3556                 rc = qmt_hdls.qmth_intent_policy(info->mti_env, qmt,
3557                                                  mdt_info_req(info), lockp,
3558                                                  flags);
3559                 RETURN(rc);
3560         }
3561
3562         flv = &mdt_it_flavor[opc];
3563         if (flv->it_fmt != NULL)
3564                 req_capsule_extend(pill, flv->it_fmt);
3565
3566         rc = mdt_unpack_req_pack_rep(info, flv->it_flags);
3567         if (rc < 0)
3568                 RETURN(rc);
3569
3570         if (flv->it_flags & MUTABOR &&
3571             exp_connect_flags(req->rq_export) & OBD_CONNECT_RDONLY)
3572                 RETURN(-EROFS);
3573
3574         if (flv->it_act != NULL) {
3575                 struct ldlm_reply *rep;
3576
3577                 /* execute policy */
3578                 rc = flv->it_act(opc, info, lockp, flags);
3579
3580                 /* Check whether the reply has been packed successfully. */
3581                 if (req->rq_repmsg != NULL) {
3582                         rep = req_capsule_server_get(info->mti_pill,
3583                                                      &RMF_DLM_REP);
3584                         rep->lock_policy_res2 =
3585                                 ptlrpc_status_hton(rep->lock_policy_res2);
3586                 }
3587         }
3588
3589         RETURN(rc);
3590 }
3591
3592 static int mdt_intent_policy(struct ldlm_namespace *ns,
3593                              struct ldlm_lock **lockp, void *req_cookie,
3594                              ldlm_mode_t mode, __u64 flags, void *data)
3595 {
3596         struct tgt_session_info *tsi;
3597         struct mdt_thread_info  *info;
3598         struct ptlrpc_request   *req  =  req_cookie;
3599         struct ldlm_intent      *it;
3600         struct req_capsule      *pill;
3601         int rc;
3602
3603         ENTRY;
3604
3605         LASSERT(req != NULL);
3606
3607         tsi = tgt_ses_info(req->rq_svc_thread->t_env);
3608
3609         info = tsi2mdt_info(tsi);
3610         LASSERT(info != NULL);
3611         pill = info->mti_pill;
3612         LASSERT(pill->rc_req == req);
3613
3614         if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
3615                 req_capsule_extend(pill, &RQF_LDLM_INTENT_BASIC);
3616                 it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
3617                 if (it != NULL) {
3618                         rc = mdt_intent_opc(it->opc, info, lockp, flags);
3619                         if (rc == 0)
3620                                 rc = ELDLM_OK;
3621
3622                         /* Lock without inodebits makes no sense and will oops
3623                          * later in ldlm. Let's check it now to see if we have
3624                          * ibits corrupted somewhere in mdt_intent_opc().
3625                          * The case for client miss to set ibits has been
3626                          * processed by others. */
3627                         LASSERT(ergo(info->mti_dlm_req->lock_desc.l_resource.\
3628                                         lr_type == LDLM_IBITS,
3629                                      info->mti_dlm_req->lock_desc.\
3630                                         l_policy_data.l_inodebits.bits != 0));
3631                 } else
3632                         rc = err_serious(-EFAULT);
3633         } else {
3634                 /* No intent was provided */
3635                 LASSERT(pill->rc_fmt == &RQF_LDLM_ENQUEUE);
3636                 req_capsule_set_size(pill, &RMF_DLM_LVB, RCL_SERVER, 0);
3637                 rc = req_capsule_server_pack(pill);
3638                 if (rc)
3639                         rc = err_serious(rc);
3640         }
3641         mdt_thread_info_fini(info);
3642         RETURN(rc);
3643 }
3644
3645 static void mdt_deregister_seq_exp(struct mdt_device *mdt)
3646 {
3647         struct seq_server_site  *ss = mdt_seq_site(mdt);
3648
3649         if (ss->ss_node_id == 0)
3650                 return;
3651
3652         if (ss->ss_client_seq != NULL) {
3653                 lustre_deregister_lwp_item(&ss->ss_client_seq->lcs_exp);
3654                 ss->ss_client_seq->lcs_exp = NULL;
3655         }
3656
3657         if (ss->ss_server_fld != NULL) {
3658                 lustre_deregister_lwp_item(&ss->ss_server_fld->lsf_control_exp);
3659                 ss->ss_server_fld->lsf_control_exp = NULL;
3660         }
3661 }
3662
3663 static void mdt_seq_fini_cli(struct mdt_device *mdt)
3664 {
3665         struct seq_server_site *ss = mdt_seq_site(mdt);
3666
3667         if (ss == NULL)
3668                 return;
3669
3670         if (ss->ss_server_seq != NULL)
3671                 seq_server_set_cli(NULL, ss->ss_server_seq, NULL);
3672 }
3673
3674 static int mdt_seq_fini(const struct lu_env *env, struct mdt_device *mdt)
3675 {
3676         mdt_seq_fini_cli(mdt);
3677         mdt_deregister_seq_exp(mdt);
3678
3679         return seq_site_fini(env, mdt_seq_site(mdt));
3680 }
3681
3682 /**
3683  * It will retrieve its FLDB entries from MDT0, and it only happens
3684  * when upgrading existent FS to 2.6 or when local FLDB is corrupted,
3685  * and it needs to refresh FLDB from the MDT0.
3686  **/
3687 static int mdt_register_lwp_callback(void *data)
3688 {
3689         struct lu_env           env;
3690         struct mdt_device       *mdt = data;
3691         struct lu_server_fld    *fld = mdt_seq_site(mdt)->ss_server_fld;
3692         int                     rc;
3693         ENTRY;
3694
3695         LASSERT(mdt_seq_site(mdt)->ss_node_id != 0);
3696
3697         if (!likely(fld->lsf_new))
3698                 RETURN(0);
3699
3700         rc = lu_env_init(&env, LCT_MD_THREAD);
3701         if (rc) {
3702                 CERROR("%s: cannot init env: rc = %d\n", mdt_obd_name(mdt), rc);
3703                 RETURN(rc);
3704         }
3705
3706         rc = fld_update_from_controller(&env, fld);
3707         if (rc != 0) {
3708                 CERROR("%s: cannot update controller: rc = %d\n",
3709                        mdt_obd_name(mdt), rc);
3710                 GOTO(out, rc);
3711         }
3712 out:
3713         lu_env_fini(&env);
3714         RETURN(rc);
3715 }
3716
3717 static int mdt_register_seq_exp(struct mdt_device *mdt)
3718 {
3719         struct seq_server_site  *ss = mdt_seq_site(mdt);
3720         char                    *lwp_name = NULL;
3721         int                     rc;
3722
3723         if (ss->ss_node_id == 0)
3724                 return 0;
3725
3726         OBD_ALLOC(lwp_name, MAX_OBD_NAME);
3727         if (lwp_name == NULL)
3728                 GOTO(out_free, rc = -ENOMEM);
3729
3730         rc = tgt_name2lwp_name(mdt_obd_name(mdt), lwp_name, MAX_OBD_NAME, 0);
3731         if (rc != 0)
3732                 GOTO(out_free, rc);
3733
3734         rc = lustre_register_lwp_item(lwp_name, &ss->ss_client_seq->lcs_exp,
3735                                       NULL, NULL);
3736         if (rc != 0)
3737                 GOTO(out_free, rc);
3738
3739         rc = lustre_register_lwp_item(lwp_name,
3740                                       &ss->ss_server_fld->lsf_control_exp,
3741                                       mdt_register_lwp_callback, mdt);
3742         if (rc != 0) {
3743                 lustre_deregister_lwp_item(&ss->ss_client_seq->lcs_exp);
3744                 ss->ss_client_seq->lcs_exp = NULL;
3745                 GOTO(out_free, rc);
3746         }
3747 out_free:
3748         if (lwp_name != NULL)
3749                 OBD_FREE(lwp_name, MAX_OBD_NAME);
3750
3751         return rc;
3752 }
3753
3754 /*
3755  * Init client sequence manager which is used by local MDS to talk to sequence
3756  * controller on remote node.
3757  */
3758 static int mdt_seq_init_cli(const struct lu_env *env, struct mdt_device *mdt)
3759 {
3760         struct seq_server_site  *ss = mdt_seq_site(mdt);
3761         int                     rc;
3762         char                    *prefix;
3763         ENTRY;
3764
3765         /* check if this is adding the first MDC and controller is not yet
3766          * initialized. */
3767         OBD_ALLOC_PTR(ss->ss_client_seq);
3768         if (ss->ss_client_seq == NULL)
3769                 RETURN(-ENOMEM);
3770
3771         OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3772         if (prefix == NULL) {
3773                 OBD_FREE_PTR(ss->ss_client_seq);
3774                 ss->ss_client_seq = NULL;
3775                 RETURN(-ENOMEM);
3776         }
3777
3778         /* Note: seq_client_fini will be called in seq_site_fini */
3779         snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s", mdt_obd_name(mdt));
3780         rc = seq_client_init(ss->ss_client_seq, NULL, LUSTRE_SEQ_METADATA,
3781                              prefix, ss->ss_node_id == 0 ?  ss->ss_control_seq :
3782                                                             NULL);
3783         OBD_FREE(prefix, MAX_OBD_NAME + 5);
3784         if (rc != 0) {
3785                 OBD_FREE_PTR(ss->ss_client_seq);
3786                 ss->ss_client_seq = NULL;
3787                 RETURN(rc);
3788         }
3789
3790         rc = seq_server_set_cli(env, ss->ss_server_seq, ss->ss_client_seq);
3791
3792         RETURN(rc);
3793 }
3794
3795 static int mdt_seq_init(const struct lu_env *env, struct mdt_device *mdt)
3796 {
3797         struct seq_server_site  *ss;
3798         int                     rc;
3799         ENTRY;
3800
3801         ss = mdt_seq_site(mdt);
3802         /* init sequence controller server(MDT0) */
3803         if (ss->ss_node_id == 0) {
3804                 OBD_ALLOC_PTR(ss->ss_control_seq);
3805                 if (ss->ss_control_seq == NULL)
3806                         RETURN(-ENOMEM);
3807
3808                 rc = seq_server_init(env, ss->ss_control_seq, mdt->mdt_bottom,
3809                                      mdt_obd_name(mdt), LUSTRE_SEQ_CONTROLLER,
3810                                      ss);
3811                 if (rc)
3812                         GOTO(out_seq_fini, rc);
3813         }
3814
3815         /* Init normal sequence server */
3816         OBD_ALLOC_PTR(ss->ss_server_seq);
3817         if (ss->ss_server_seq == NULL)
3818                 GOTO(out_seq_fini, rc = -ENOMEM);
3819
3820         rc = seq_server_init(env, ss->ss_server_seq, mdt->mdt_bottom,
3821                              mdt_obd_name(mdt), LUSTRE_SEQ_SERVER, ss);
3822         if (rc)
3823                 GOTO(out_seq_fini, rc);
3824
3825         /* init seq client for seq server to talk to seq controller(MDT0) */
3826         rc = mdt_seq_init_cli(env, mdt);
3827         if (rc != 0)
3828                 GOTO(out_seq_fini, rc);
3829
3830         if (ss->ss_node_id != 0)
3831                 /* register controler export through lwp */
3832                 rc = mdt_register_seq_exp(mdt);
3833
3834         EXIT;
3835 out_seq_fini:
3836         if (rc)
3837                 mdt_seq_fini(env, mdt);
3838
3839         return rc;
3840 }
3841
3842 /*
3843  * FLD wrappers
3844  */
3845 static int mdt_fld_fini(const struct lu_env *env,
3846                         struct mdt_device *m)
3847 {
3848         struct seq_server_site *ss = mdt_seq_site(m);
3849         ENTRY;
3850
3851         if (ss && ss->ss_server_fld) {
3852                 fld_server_fini(env, ss->ss_server_fld);
3853                 OBD_FREE_PTR(ss->ss_server_fld);
3854                 ss->ss_server_fld = NULL;
3855         }
3856
3857         RETURN(0);
3858 }
3859
3860 static int mdt_fld_init(const struct lu_env *env,
3861                         const char *uuid,
3862                         struct mdt_device *m)
3863 {
3864         struct seq_server_site *ss;
3865         int rc;
3866         ENTRY;
3867
3868         ss = mdt_seq_site(m);
3869
3870         OBD_ALLOC_PTR(ss->ss_server_fld);
3871         if (ss->ss_server_fld == NULL)
3872                 RETURN(rc = -ENOMEM);
3873
3874         rc = fld_server_init(env, ss->ss_server_fld, m->mdt_bottom, uuid,
3875                              LU_SEQ_RANGE_MDT);
3876         if (rc) {
3877                 OBD_FREE_PTR(ss->ss_server_fld);
3878                 ss->ss_server_fld = NULL;
3879                 RETURN(rc);
3880         }
3881
3882         RETURN(0);
3883 }
3884
3885 static void mdt_stack_pre_fini(const struct lu_env *env,
3886                            struct mdt_device *m, struct lu_device *top)
3887 {
3888         struct lustre_cfg_bufs  *bufs;
3889         struct lustre_cfg       *lcfg;
3890         struct mdt_thread_info  *info;
3891         ENTRY;
3892
3893         LASSERT(top);
3894
3895         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3896         LASSERT(info != NULL);
3897
3898         bufs = &info->mti_u.bufs;
3899
3900         LASSERT(m->mdt_child_exp);
3901         LASSERT(m->mdt_child_exp->exp_obd);
3902
3903         /* process cleanup, pass mdt obd name to get obd umount flags */
3904         /* XXX: this is needed because all layers are referenced by
3905          * objects (some of them are pinned by osd, for example *
3906          * the proper solution should be a model where object used
3907          * by osd only doesn't have mdt/mdd slices -bzzz */
3908         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
3909         lustre_cfg_bufs_set_string(bufs, 1, NULL);
3910         lcfg = lustre_cfg_new(LCFG_PRE_CLEANUP, bufs);
3911         if (lcfg == NULL)
3912                 RETURN_EXIT;
3913
3914         top->ld_ops->ldo_process_config(env, top, lcfg);
3915         lustre_cfg_free(lcfg);
3916         EXIT;
3917 }
3918
3919 static void mdt_stack_fini(const struct lu_env *env,
3920                            struct mdt_device *m, struct lu_device *top)
3921 {
3922         struct obd_device       *obd = mdt2obd_dev(m);
3923         struct lustre_cfg_bufs  *bufs;
3924         struct lustre_cfg       *lcfg;
3925         struct mdt_thread_info  *info;
3926         char                     flags[3] = "";
3927         ENTRY;
3928
3929         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3930         LASSERT(info != NULL);
3931
3932         lu_dev_del_linkage(top->ld_site, top);
3933
3934         lu_site_purge(env, top->ld_site, -1);
3935
3936         bufs = &info->mti_u.bufs;
3937         /* process cleanup, pass mdt obd name to get obd umount flags */
3938         /* another purpose is to let all layers to release their objects */
3939         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
3940         if (obd->obd_force)
3941                 strcat(flags, "F");
3942         if (obd->obd_fail)
3943                 strcat(flags, "A");
3944         lustre_cfg_bufs_set_string(bufs, 1, flags);
3945         lcfg = lustre_cfg_new(LCFG_CLEANUP, bufs);
3946         if (lcfg == NULL)
3947                 RETURN_EXIT;
3948
3949         LASSERT(top);
3950         top->ld_ops->ldo_process_config(env, top, lcfg);
3951         lustre_cfg_free(lcfg);
3952
3953         lu_site_purge(env, top->ld_site, -1);
3954
3955         m->mdt_child = NULL;
3956         m->mdt_bottom = NULL;
3957
3958         obd_disconnect(m->mdt_child_exp);
3959         m->mdt_child_exp = NULL;
3960
3961         obd_disconnect(m->mdt_bottom_exp);
3962         m->mdt_child_exp = NULL;
3963 }
3964
3965 static int mdt_connect_to_next(const struct lu_env *env, struct mdt_device *m,
3966                                const char *next, struct obd_export **exp)
3967 {
3968         struct obd_connect_data *data = NULL;
3969         struct obd_device       *obd;
3970         int                      rc;
3971         ENTRY;
3972
3973         OBD_ALLOC_PTR(data);
3974         if (data == NULL)
3975                 GOTO(out, rc = -ENOMEM);
3976
3977         obd = class_name2obd(next);
3978         if (obd == NULL) {
3979                 CERROR("%s: can't locate next device: %s\n",
3980                        mdt_obd_name(m), next);
3981                 GOTO(out, rc = -ENOTCONN);
3982         }
3983
3984         data->ocd_connect_flags = OBD_CONNECT_VERSION;
3985         data->ocd_version = LUSTRE_VERSION_CODE;
3986
3987         rc = obd_connect(NULL, exp, obd, &obd->obd_uuid, data, NULL);
3988         if (rc) {
3989                 CERROR("%s: cannot connect to next dev %s (%d)\n",
3990                        mdt_obd_name(m), next, rc);
3991                 GOTO(out, rc);
3992         }
3993
3994 out:
3995         if (data)
3996                 OBD_FREE_PTR(data);
3997         RETURN(rc);
3998 }
3999
4000 static int mdt_stack_init(const struct lu_env *env, struct mdt_device *mdt,
4001                           struct lustre_cfg *cfg)
4002 {
4003         char                   *dev = lustre_cfg_string(cfg, 0);
4004         int                     rc, name_size, uuid_size;
4005         char                   *name, *uuid, *p;
4006         struct lustre_cfg_bufs *bufs;
4007         struct lustre_cfg      *lcfg;
4008         struct obd_device      *obd;
4009         struct lustre_profile  *lprof;
4010         struct lu_site         *site;
4011         ENTRY;
4012
4013         /* in 1.8 we had the only device in the stack - MDS.
4014          * 2.0 introduces MDT, MDD, OSD; MDT starts others internally.
4015          * in 2.3 OSD is instantiated by obd_mount.c, so we need
4016          * to generate names and setup MDT, MDD. MDT will be using
4017          * generated name to connect to MDD. for MDD the next device
4018          * will be LOD with name taken from so called "profile" which
4019          * is generated by mount_option line
4020          *
4021          * 1.8 MGS generates config. commands like this:
4022          *   #06 (104)mount_option 0:  1:lustre-MDT0000  2:lustre-mdtlov
4023          *   #08 (120)setup   0:lustre-MDT0000  1:dev 2:type 3:lustre-MDT0000
4024          * 2.0 MGS generates config. commands like this:
4025          *   #07 (112)mount_option 0:  1:lustre-MDT0000  2:lustre-MDT0000-mdtlov
4026          *   #08 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4027          *                    3:lustre-MDT0000-mdtlov  4:f
4028          *
4029          * we generate MDD name from MDT one, just replacing T with D
4030          *
4031          * after all the preparations, the logical equivalent will be
4032          *   #01 (160)setup   0:lustre-MDD0000  1:lustre-MDD0000_UUID  2:0
4033          *                    3:lustre-MDT0000-mdtlov  4:f
4034          *   #02 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4035          *                    3:lustre-MDD0000  4:f
4036          *
4037          *  notice we build the stack from down to top: MDD first, then MDT */
4038
4039         name_size = MAX_OBD_NAME;
4040         uuid_size = MAX_OBD_NAME;
4041
4042         OBD_ALLOC(name, name_size);
4043         OBD_ALLOC(uuid, uuid_size);
4044         if (name == NULL || uuid == NULL)
4045                 GOTO(cleanup_mem, rc = -ENOMEM);
4046
4047         OBD_ALLOC_PTR(bufs);
4048         if (!bufs)
4049                 GOTO(cleanup_mem, rc = -ENOMEM);
4050
4051         strcpy(name, dev);
4052         p = strstr(name, "-MDT");
4053         if (p == NULL)
4054                 GOTO(free_bufs, rc = -ENOMEM);
4055         p[3] = 'D';
4056
4057         snprintf(uuid, MAX_OBD_NAME, "%s_UUID", name);
4058
4059         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
4060         if (lprof == NULL || lprof->lp_dt == NULL) {
4061                 CERROR("can't find the profile: %s\n",
4062                        lustre_cfg_string(cfg, 0));
4063                 GOTO(free_bufs, rc = -EINVAL);
4064         }
4065
4066         lustre_cfg_bufs_reset(bufs, name);
4067         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_MDD_NAME);
4068         lustre_cfg_bufs_set_string(bufs, 2, uuid);
4069         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4070
4071         lcfg = lustre_cfg_new(LCFG_ATTACH, bufs);
4072         if (lcfg == NULL)
4073                 GOTO(free_bufs, rc = -ENOMEM);
4074
4075         rc = class_attach(lcfg);
4076         if (rc)
4077                 GOTO(lcfg_cleanup, rc);
4078
4079         obd = class_name2obd(name);
4080         if (!obd) {
4081                 CERROR("Can not find obd %s (%s in config)\n",
4082                        MDD_OBD_NAME, lustre_cfg_string(cfg, 0));
4083                 GOTO(lcfg_cleanup, rc = -EINVAL);
4084         }
4085
4086         lustre_cfg_free(lcfg);
4087
4088         lustre_cfg_bufs_reset(bufs, name);
4089         lustre_cfg_bufs_set_string(bufs, 1, uuid);
4090         lustre_cfg_bufs_set_string(bufs, 2, dev);
4091         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4092
4093         lcfg = lustre_cfg_new(LCFG_SETUP, bufs);
4094         if (lcfg == NULL)
4095                 GOTO(class_detach, rc = -ENOMEM);
4096
4097         rc = class_setup(obd, lcfg);
4098         if (rc)
4099                 GOTO(class_detach, rc);
4100
4101         /* connect to MDD we just setup */
4102         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_child_exp);
4103         if (rc)
4104                 GOTO(class_detach, rc);
4105
4106         site = mdt->mdt_child_exp->exp_obd->obd_lu_dev->ld_site;
4107         LASSERT(site);
4108         LASSERT(mdt_lu_site(mdt) == NULL);
4109         mdt->mdt_lu_dev.ld_site = site;
4110         site->ls_top_dev = &mdt->mdt_lu_dev;
4111         mdt->mdt_child = lu2md_dev(mdt->mdt_child_exp->exp_obd->obd_lu_dev);
4112
4113         /* now connect to bottom OSD */
4114         snprintf(name, MAX_OBD_NAME, "%s-osd", dev);
4115         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_bottom_exp);
4116         if (rc)
4117                 GOTO(class_detach, rc);
4118         mdt->mdt_bottom =
4119                 lu2dt_dev(mdt->mdt_bottom_exp->exp_obd->obd_lu_dev);
4120
4121         rc = lu_env_refill((struct lu_env *)env);
4122         if (rc != 0)
4123                 CERROR("Failure to refill session: '%d'\n", rc);
4124
4125         lu_dev_add_linkage(site, &mdt->mdt_lu_dev);
4126
4127         EXIT;
4128 class_detach:
4129         if (rc)
4130                 class_detach(obd, lcfg);
4131 lcfg_cleanup:
4132         lustre_cfg_free(lcfg);
4133 free_bufs:
4134         OBD_FREE_PTR(bufs);
4135 cleanup_mem:
4136         if (name)
4137                 OBD_FREE(name, name_size);
4138         if (uuid)
4139                 OBD_FREE(uuid, uuid_size);
4140         RETURN(rc);
4141 }
4142
4143 /* setup quota master target on MDT0 */
4144 static int mdt_quota_init(const struct lu_env *env, struct mdt_device *mdt,
4145                           struct lustre_cfg *cfg)
4146 {
4147         struct obd_device       *obd;
4148         char                    *dev = lustre_cfg_string(cfg, 0);
4149         char                    *qmtname, *uuid, *p;
4150         struct lustre_cfg_bufs  *bufs;
4151         struct lustre_cfg       *lcfg;
4152         struct lustre_profile   *lprof;
4153         struct obd_connect_data *data;
4154         int                      rc;
4155         ENTRY;
4156
4157         LASSERT(mdt->mdt_qmt_exp == NULL);
4158         LASSERT(mdt->mdt_qmt_dev == NULL);
4159
4160         /* quota master is on MDT0 only for now */
4161         if (mdt->mdt_seq_site.ss_node_id != 0)
4162                 RETURN(0);
4163
4164         /* MGS generates config commands which look as follows:
4165          *   #01 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4166          *                    3:lustre-MDT0000-mdtlov  4:f
4167          *
4168          * We generate the QMT name from the MDT one, just replacing MD with QM
4169          * after all the preparations, the logical equivalent will be:
4170          *   #01 (160)setup   0:lustre-QMT0000  1:lustre-QMT0000_UUID  2:0
4171          *                    3:lustre-MDT0000-osd  4:f */
4172         OBD_ALLOC(qmtname, MAX_OBD_NAME);
4173         OBD_ALLOC(uuid, UUID_MAX);
4174         OBD_ALLOC_PTR(bufs);
4175         OBD_ALLOC_PTR(data);
4176         if (qmtname == NULL || uuid == NULL || bufs == NULL || data == NULL)
4177                 GOTO(cleanup_mem, rc = -ENOMEM);
4178
4179         strcpy(qmtname, dev);
4180         p = strstr(qmtname, "-MDT");
4181         if (p == NULL)
4182                 GOTO(cleanup_mem, rc = -ENOMEM);
4183         /* replace MD with QM */
4184         p[1] = 'Q';
4185         p[2] = 'M';
4186
4187         snprintf(uuid, UUID_MAX, "%s_UUID", qmtname);
4188
4189         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
4190         if (lprof == NULL || lprof->lp_dt == NULL) {
4191                 CERROR("can't find profile for %s\n",
4192                        lustre_cfg_string(cfg, 0));
4193                 GOTO(cleanup_mem, rc = -EINVAL);
4194         }
4195
4196         lustre_cfg_bufs_reset(bufs, qmtname);
4197         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_QMT_NAME);
4198         lustre_cfg_bufs_set_string(bufs, 2, uuid);
4199         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4200
4201         lcfg = lustre_cfg_new(LCFG_ATTACH, bufs);
4202         if (lcfg == NULL)
4203                 GOTO(cleanup_mem, rc = -ENOMEM);
4204
4205         rc = class_attach(lcfg);
4206         if (rc)
4207                 GOTO(lcfg_cleanup, rc);
4208
4209         obd = class_name2obd(qmtname);
4210         if (!obd) {
4211                 CERROR("Can not find obd %s (%s in config)\n", qmtname,
4212                        lustre_cfg_string(cfg, 0));
4213                 GOTO(lcfg_cleanup, rc = -EINVAL);
4214         }
4215
4216         lustre_cfg_free(lcfg);
4217
4218         lustre_cfg_bufs_reset(bufs, qmtname);
4219         lustre_cfg_bufs_set_string(bufs, 1, uuid);
4220         lustre_cfg_bufs_set_string(bufs, 2, dev);
4221
4222         /* for quota, the next device should be the OSD device */
4223         lustre_cfg_bufs_set_string(bufs, 3,
4224                                    mdt->mdt_bottom->dd_lu_dev.ld_obd->obd_name);
4225
4226         lcfg = lustre_cfg_new(LCFG_SETUP, bufs);
4227         if (lcfg == NULL)
4228                 GOTO(class_detach, rc = -ENOMEM);
4229
4230         rc = class_setup(obd, lcfg);
4231         if (rc)
4232                 GOTO(class_detach, rc);
4233
4234         mdt->mdt_qmt_dev = obd->obd_lu_dev;
4235
4236         /* configure local quota objects */
4237         rc = mdt->mdt_qmt_dev->ld_ops->ldo_prepare(env,
4238                                                    &mdt->mdt_lu_dev,
4239                                                    mdt->mdt_qmt_dev);
4240         if (rc)
4241                 GOTO(class_cleanup, rc);
4242
4243         /* connect to quota master target */
4244         data->ocd_connect_flags = OBD_CONNECT_VERSION;
4245         data->ocd_version = LUSTRE_VERSION_CODE;
4246         rc = obd_connect(NULL, &mdt->mdt_qmt_exp, obd, &obd->obd_uuid,
4247                          data, NULL);
4248         if (rc) {
4249                 CERROR("cannot connect to quota master device %s (%d)\n",
4250                        qmtname, rc);
4251                 GOTO(class_cleanup, rc);
4252         }
4253
4254         EXIT;
4255 class_cleanup:
4256         if (rc) {
4257                 class_manual_cleanup(obd);
4258                 mdt->mdt_qmt_dev = NULL;
4259         }
4260 class_detach:
4261         if (rc)
4262                 class_detach(obd, lcfg);
4263 lcfg_cleanup:
4264         lustre_cfg_free(lcfg);
4265 cleanup_mem:
4266         if (bufs)
4267                 OBD_FREE_PTR(bufs);
4268         if (qmtname)
4269                 OBD_FREE(qmtname, MAX_OBD_NAME);
4270         if (uuid)
4271                 OBD_FREE(uuid, UUID_MAX);
4272         if (data)
4273                 OBD_FREE_PTR(data);
4274         return rc;
4275 }
4276
4277 /* Shutdown quota master target associated with mdt */
4278 static void mdt_quota_fini(const struct lu_env *env, struct mdt_device *mdt)
4279 {
4280         ENTRY;
4281
4282         if (mdt->mdt_qmt_exp == NULL)
4283                 RETURN_EXIT;
4284         LASSERT(mdt->mdt_qmt_dev != NULL);
4285
4286         /* the qmt automatically shuts down when the mdt disconnects */
4287         obd_disconnect(mdt->mdt_qmt_exp);
4288         mdt->mdt_qmt_exp = NULL;
4289         mdt->mdt_qmt_dev = NULL;
4290         EXIT;
4291 }
4292
4293 /* mdt_getxattr() is used from mdt_intent_getxattr(), use this wrapper
4294  * for now. This will be removed along with converting rest of MDT code
4295  * to use tgt_session_info */
4296 static int mdt_tgt_getxattr(struct tgt_session_info *tsi)
4297 {
4298         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
4299         int                      rc;
4300
4301         rc = mdt_getxattr(info);
4302
4303         mdt_thread_info_fini(info);
4304         return rc;
4305 }
4306
4307 static struct tgt_handler mdt_tgt_handlers[] = {
4308 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4309                 0,                      MDS_CONNECT,    mdt_tgt_connect,
4310                 &RQF_CONNECT, LUSTRE_OBD_VERSION),
4311 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4312                 0,                      MDS_DISCONNECT, tgt_disconnect,
4313                 &RQF_MDS_DISCONNECT, LUSTRE_OBD_VERSION),
4314 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4315                 HABEO_REFERO,           MDS_SET_INFO,   mdt_set_info,
4316                 &RQF_OBD_SET_INFO, LUSTRE_MDS_VERSION),
4317 TGT_MDT_HDL(0,                          MDS_GET_INFO,   mdt_get_info),
4318 TGT_MDT_HDL(0           | HABEO_REFERO, MDS_GETSTATUS,  mdt_getstatus),
4319 TGT_MDT_HDL(HABEO_CORPUS,               MDS_GETATTR,    mdt_getattr),
4320 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_GETATTR_NAME,
4321                                                         mdt_getattr_name),
4322 TGT_MDT_HDL(HABEO_CORPUS,               MDS_GETXATTR,   mdt_tgt_getxattr),
4323 TGT_MDT_HDL(0           | HABEO_REFERO, MDS_STATFS,     mdt_statfs),
4324 TGT_MDT_HDL(0           | MUTABOR,      MDS_REINT,      mdt_reint),
4325 TGT_MDT_HDL(HABEO_CORPUS,               MDS_CLOSE,      mdt_close),
4326 TGT_MDT_HDL(HABEO_CORPUS,               MDS_DONE_WRITING,
4327                                                         mdt_done_writing),
4328 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_READPAGE,   mdt_readpage),
4329 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_SYNC,       mdt_sync),
4330 TGT_MDT_HDL(0,                          MDS_QUOTACTL,   mdt_quotactl),
4331 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_PROGRESS,
4332                                                         mdt_hsm_progress),
4333 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_CT_REGISTER,
4334                                                         mdt_hsm_ct_register),
4335 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_CT_UNREGISTER,
4336                                                         mdt_hsm_ct_unregister),
4337 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_STATE_GET,
4338                                                         mdt_hsm_state_get),
4339 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_STATE_SET,
4340                                                         mdt_hsm_state_set),
4341 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_ACTION, mdt_hsm_action),
4342 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_REQUEST,
4343                                                         mdt_hsm_request),
4344 TGT_MDT_HDL(HABEO_CLAVIS | HABEO_CORPUS | HABEO_REFERO | MUTABOR,
4345             MDS_SWAP_LAYOUTS,
4346             mdt_swap_layouts),
4347 };
4348
4349 static struct tgt_handler mdt_sec_ctx_ops[] = {
4350 TGT_SEC_HDL_VAR(0,                      SEC_CTX_INIT,     mdt_sec_ctx_handle),
4351 TGT_SEC_HDL_VAR(0,                      SEC_CTX_INIT_CONT,mdt_sec_ctx_handle),
4352 TGT_SEC_HDL_VAR(0,                      SEC_CTX_FINI,     mdt_sec_ctx_handle)
4353 };
4354
4355 static struct tgt_handler mdt_quota_ops[] = {
4356 TGT_QUOTA_HDL(HABEO_REFERO,             QUOTA_DQACQ,      mdt_quota_dqacq),
4357 };
4358
4359 static struct tgt_opc_slice mdt_common_slice[] = {
4360         {
4361                 .tos_opc_start  = MDS_FIRST_OPC,
4362                 .tos_opc_end    = MDS_LAST_OPC,
4363                 .tos_hs         = mdt_tgt_handlers
4364         },
4365         {
4366                 .tos_opc_start  = OBD_FIRST_OPC,
4367                 .tos_opc_end    = OBD_LAST_OPC,
4368                 .tos_hs         = tgt_obd_handlers
4369         },
4370         {
4371                 .tos_opc_start  = LDLM_FIRST_OPC,
4372                 .tos_opc_end    = LDLM_LAST_OPC,
4373                 .tos_hs         = tgt_dlm_handlers
4374         },
4375         {
4376                 .tos_opc_start  = SEC_FIRST_OPC,
4377                 .tos_opc_end    = SEC_LAST_OPC,
4378                 .tos_hs         = mdt_sec_ctx_ops
4379         },
4380         {
4381                 .tos_opc_start  = OUT_UPDATE_FIRST_OPC,
4382                 .tos_opc_end    = OUT_UPDATE_LAST_OPC,
4383                 .tos_hs         = tgt_out_handlers
4384         },
4385         {
4386                 .tos_opc_start  = FLD_FIRST_OPC,
4387                 .tos_opc_end    = FLD_LAST_OPC,
4388                 .tos_hs         = fld_handlers
4389         },
4390         {
4391                 .tos_opc_start  = SEQ_FIRST_OPC,
4392                 .tos_opc_end    = SEQ_LAST_OPC,
4393                 .tos_hs         = seq_handlers
4394         },
4395         {
4396                 .tos_opc_start  = QUOTA_DQACQ,
4397                 .tos_opc_end    = QUOTA_LAST_OPC,
4398                 .tos_hs         = mdt_quota_ops
4399         },
4400         {
4401                 .tos_opc_start  = LLOG_FIRST_OPC,
4402                 .tos_opc_end    = LLOG_LAST_OPC,
4403                 .tos_hs         = tgt_llog_handlers
4404         },
4405         {
4406                 .tos_opc_start  = LFSCK_FIRST_OPC,
4407                 .tos_opc_end    = LFSCK_LAST_OPC,
4408                 .tos_hs         = tgt_lfsck_handlers
4409         },
4410
4411         {
4412                 .tos_hs         = NULL
4413         }
4414 };
4415
4416 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
4417 {
4418         struct md_device        *next = m->mdt_child;
4419         struct lu_device        *d    = &m->mdt_lu_dev;
4420         struct obd_device       *obd  = mdt2obd_dev(m);
4421         struct lfsck_stop        stop;
4422         ENTRY;
4423
4424         stop.ls_status = LS_PAUSED;
4425         stop.ls_flags = 0;
4426         next->md_ops->mdo_iocontrol(env, next, OBD_IOC_STOP_LFSCK, 0, &stop);
4427
4428         target_recovery_fini(obd);
4429         ping_evictor_stop();
4430         mdt_stack_pre_fini(env, m, md2lu_dev(m->mdt_child));
4431
4432         if (m->mdt_opts.mo_coordinator)
4433                 mdt_hsm_cdt_stop(m);
4434
4435         mdt_hsm_cdt_fini(m);
4436
4437         mdt_llog_ctxt_unclone(env, m, LLOG_AGENT_ORIG_CTXT);
4438         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4439         obd_exports_barrier(obd);
4440         obd_zombie_barrier();
4441
4442         mdt_procfs_fini(m);
4443
4444         tgt_fini(env, &m->mdt_lut);
4445         mdt_fs_cleanup(env, m);
4446         upcall_cache_cleanup(m->mdt_identity_cache);
4447         m->mdt_identity_cache = NULL;
4448
4449         if (m->mdt_namespace != NULL) {
4450                 ldlm_namespace_free(m->mdt_namespace, NULL,
4451                                     d->ld_obd->obd_force);
4452                 d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
4453         }
4454
4455         mdt_quota_fini(env, m);
4456
4457         cfs_free_nidlist(&m->mdt_squash.rsi_nosquash_nids);
4458
4459         mdt_seq_fini(env, m);
4460         mdt_fld_fini(env, m);
4461
4462         next->md_ops->mdo_init_capa_ctxt(env, next, 0, 0, 0, NULL);
4463         cfs_timer_disarm(&m->mdt_ck_timer);
4464         mdt_ck_thread_stop(m);
4465
4466         /*
4467          * Finish the stack
4468          */
4469         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4470
4471         LASSERT(atomic_read(&d->ld_ref) == 0);
4472
4473         server_put_mount(mdt_obd_name(m), true);
4474
4475         EXIT;
4476 }
4477
4478 static int mdt_postrecov(const struct lu_env *, struct mdt_device *);
4479
4480 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
4481                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
4482 {
4483         struct mdt_thread_info    *info;
4484         struct obd_device         *obd;
4485         const char                *dev = lustre_cfg_string(cfg, 0);
4486         const char                *num = lustre_cfg_string(cfg, 2);
4487         struct lustre_mount_info  *lmi = NULL;
4488         struct lustre_sb_info     *lsi;
4489         struct lu_site            *s;
4490         struct seq_server_site    *ss_site;
4491         const char                *identity_upcall = "NONE";
4492         struct md_device          *next;
4493         int                        rc;
4494         long                       node_id;
4495         mntopt_t                   mntopts;
4496         ENTRY;
4497
4498         lu_device_init(&m->mdt_lu_dev, ldt);
4499         /*
4500          * Environment (env) might be missing mdt_thread_key values at that
4501          * point, if device is allocated when mdt_thread_key is in QUIESCENT
4502          * mode.
4503          *
4504          * Usually device allocation path doesn't use module key values, but
4505          * mdt has to do a lot of work here, so allocate key value.
4506          */
4507         rc = lu_env_refill((struct lu_env *)env);
4508         if (rc != 0)
4509                 RETURN(rc);
4510
4511         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4512         LASSERT(info != NULL);
4513
4514         obd = class_name2obd(dev);
4515         LASSERT(obd != NULL);
4516
4517         m->mdt_max_mdsize = MAX_MD_SIZE; /* 4 stripes */
4518
4519         m->mdt_som_conf = 0;
4520
4521         m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
4522
4523         /* default is coordinator off, it is started through conf_param
4524          * or /proc */
4525         m->mdt_opts.mo_coordinator = 0;
4526
4527         lmi = server_get_mount(dev);
4528         if (lmi == NULL) {
4529                 CERROR("Cannot get mount info for %s!\n", dev);
4530                 RETURN(-EFAULT);
4531         } else {
4532                 lsi = s2lsi(lmi->lmi_sb);
4533                 /* CMD is supported only in IAM mode */
4534                 LASSERT(num);
4535                 node_id = simple_strtol(num, NULL, 10);
4536                 obd->u.obt.obt_magic = OBT_MAGIC;
4537         }
4538
4539         spin_lock_init(&m->mdt_ioepoch_lock);
4540         m->mdt_capa_timeout = CAPA_TIMEOUT;
4541         m->mdt_capa_alg = CAPA_HMAC_ALG_SHA1;
4542         m->mdt_ck_timeout = CAPA_KEY_TIMEOUT;
4543         m->mdt_squash.rsi_uid = 0;
4544         m->mdt_squash.rsi_gid = 0;
4545         INIT_LIST_HEAD(&m->mdt_squash.rsi_nosquash_nids);
4546         init_rwsem(&m->mdt_squash.rsi_sem);
4547         spin_lock_init(&m->mdt_osfs_lock);
4548         m->mdt_osfs_age = cfs_time_shift_64(-1000);
4549         m->mdt_enable_remote_dir = 0;
4550         m->mdt_enable_remote_dir_gid = 0;
4551
4552         m->mdt_lu_dev.ld_ops = &mdt_lu_ops;
4553         m->mdt_lu_dev.ld_obd = obd;
4554         /* Set this lu_device to obd for error handling purposes. */
4555         obd->obd_lu_dev = &m->mdt_lu_dev;
4556
4557         /* init the stack */
4558         rc = mdt_stack_init((struct lu_env *)env, m, cfg);
4559         if (rc) {
4560                 CERROR("%s: Can't init device stack, rc %d\n",
4561                        mdt_obd_name(m), rc);
4562                 GOTO(err_lmi, rc);
4563         }
4564
4565         s = mdt_lu_site(m);
4566         ss_site = mdt_seq_site(m);
4567         s->ld_seq_site = ss_site;
4568         ss_site->ss_lu = s;
4569
4570         /* set server index */
4571         ss_site->ss_node_id = node_id;
4572
4573         /* failover is the default
4574          * FIXME: we do not failout mds0/mgs, which may cause some problems.
4575          * assumed whose ss_node_id == 0 XXX
4576          * */
4577         obd->obd_replayable = 1;
4578         /* No connection accepted until configurations will finish */
4579         obd->obd_no_conn = 1;
4580
4581         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
4582                 char *str = lustre_cfg_string(cfg, 4);
4583                 if (strchr(str, 'n')) {
4584                         CWARN("%s: recovery disabled\n", mdt_obd_name(m));
4585                         obd->obd_replayable = 0;
4586                 }
4587         }
4588
4589         rc = mdt_fld_init(env, mdt_obd_name(m), m);
4590         if (rc)
4591                 GOTO(err_fini_stack, rc);
4592
4593         rc = mdt_seq_init(env, m);
4594         if (rc)
4595                 GOTO(err_fini_fld, rc);
4596
4597         snprintf(info->mti_u.ns_name, sizeof(info->mti_u.ns_name), "%s-%s",
4598                  LUSTRE_MDT_NAME, obd->obd_uuid.uuid);
4599         m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
4600                                               LDLM_NAMESPACE_SERVER,
4601                                               LDLM_NAMESPACE_GREEDY,
4602                                               LDLM_NS_TYPE_MDT);
4603         if (m->mdt_namespace == NULL)
4604                 GOTO(err_fini_seq, rc = -ENOMEM);
4605
4606         m->mdt_namespace->ns_lvbp = m;
4607         m->mdt_namespace->ns_lvbo = &mdt_lvbo;
4608
4609         ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
4610         /* set obd_namespace for compatibility with old code */
4611         obd->obd_namespace = m->mdt_namespace;
4612
4613         cfs_timer_init(&m->mdt_ck_timer, mdt_ck_timer_callback, m);
4614
4615         rc = mdt_hsm_cdt_init(m);
4616         if (rc != 0) {
4617                 CERROR("%s: error initializing coordinator, rc %d\n",
4618                        mdt_obd_name(m), rc);
4619                 GOTO(err_free_ns, rc);
4620         }
4621
4622         rc = mdt_ck_thread_start(m);
4623         if (rc)
4624                 GOTO(err_free_hsm, rc);
4625
4626         rc = tgt_init(env, &m->mdt_lut, obd, m->mdt_bottom, mdt_common_slice,
4627                       OBD_FAIL_MDS_ALL_REQUEST_NET,
4628                       OBD_FAIL_MDS_ALL_REPLY_NET);
4629         if (rc)
4630                 GOTO(err_capa, rc);
4631
4632         rc = mdt_fs_setup(env, m, obd, lsi);
4633         if (rc)
4634                 GOTO(err_tgt, rc);
4635
4636         tgt_adapt_sptlrpc_conf(&m->mdt_lut, 1);
4637
4638         next = m->mdt_child;
4639         rc = next->md_ops->mdo_iocontrol(env, next, OBD_IOC_GET_MNTOPT, 0,
4640                                          &mntopts);
4641         if (rc)
4642                 GOTO(err_fs_cleanup, rc);
4643
4644         if (mntopts & MNTOPT_USERXATTR)
4645                 m->mdt_opts.mo_user_xattr = 1;
4646         else
4647                 m->mdt_opts.mo_user_xattr = 0;
4648
4649         rc = next->md_ops->mdo_maxeasize_get(env, next, &m->mdt_max_ea_size);
4650         if (rc)
4651                 GOTO(err_fs_cleanup, rc);
4652
4653         if (mntopts & MNTOPT_ACL)
4654                 m->mdt_opts.mo_acl = 1;
4655         else
4656                 m->mdt_opts.mo_acl = 0;
4657
4658         /* XXX: to support suppgid for ACL, we enable identity_upcall
4659          * by default, otherwise, maybe got unexpected -EACCESS. */
4660         if (m->mdt_opts.mo_acl)
4661                 identity_upcall = MDT_IDENTITY_UPCALL_PATH;
4662
4663         m->mdt_identity_cache = upcall_cache_init(mdt_obd_name(m),
4664                                                 identity_upcall,
4665                                                 &mdt_identity_upcall_cache_ops);
4666         if (IS_ERR(m->mdt_identity_cache)) {
4667                 rc = PTR_ERR(m->mdt_identity_cache);
4668                 m->mdt_identity_cache = NULL;
4669                 GOTO(err_fs_cleanup, rc);
4670         }
4671
4672         rc = mdt_procfs_init(m, dev);
4673         if (rc) {
4674                 CERROR("Can't init MDT lprocfs, rc %d\n", rc);
4675                 GOTO(err_recovery, rc);
4676         }
4677
4678         rc = mdt_quota_init(env, m, cfg);
4679         if (rc)
4680                 GOTO(err_procfs, rc);
4681
4682         m->mdt_ldlm_client = &mdt2obd_dev(m)->obd_ldlm_client;
4683         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
4684                            "mdt_ldlm_client", m->mdt_ldlm_client);
4685
4686         ping_evictor_start();
4687
4688         /* recovery will be started upon mdt_prepare()
4689          * when the whole stack is complete and ready
4690          * to serve the requests */
4691
4692         mdt_init_capa_ctxt(env, m);
4693
4694         /* Reduce the initial timeout on an MDS because it doesn't need such
4695          * a long timeout as an OST does. Adaptive timeouts will adjust this
4696          * value appropriately. */
4697         if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
4698                 ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
4699
4700         RETURN(0);
4701 err_procfs:
4702         mdt_procfs_fini(m);
4703 err_recovery:
4704         target_recovery_fini(obd);
4705         upcall_cache_cleanup(m->mdt_identity_cache);
4706         m->mdt_identity_cache = NULL;
4707 err_fs_cleanup:
4708         mdt_fs_cleanup(env, m);
4709 err_tgt:
4710         tgt_fini(env, &m->mdt_lut);
4711 err_capa:
4712         cfs_timer_disarm(&m->mdt_ck_timer);
4713         mdt_ck_thread_stop(m);
4714 err_free_hsm:
4715         mdt_hsm_cdt_fini(m);
4716 err_free_ns:
4717         ldlm_namespace_free(m->mdt_namespace, NULL, 0);
4718         obd->obd_namespace = m->mdt_namespace = NULL;
4719 err_fini_seq:
4720         mdt_seq_fini(env, m);
4721 err_fini_fld:
4722         mdt_fld_fini(env, m);
4723 err_fini_stack:
4724         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4725 err_lmi:
4726         if (lmi)
4727                 server_put_mount(dev, true);
4728         return(rc);
4729 }
4730
4731 /* For interoperability, the left element is old parameter, the right one
4732  * is the new version of the parameter, if some parameter is deprecated,
4733  * the new version should be set as NULL. */
4734 static struct cfg_interop_param mdt_interop_param[] = {
4735         { "mdt.group_upcall",   NULL },
4736         { "mdt.quota_type",     NULL },
4737         { "mdd.quota_type",     NULL },
4738         { "mdt.rootsquash",     "mdt.root_squash" },
4739         { "mdt.nosquash_nid",   "mdt.nosquash_nids" },
4740         { NULL }
4741 };
4742
4743 /* used by MGS to process specific configurations */
4744 static int mdt_process_config(const struct lu_env *env,
4745                               struct lu_device *d, struct lustre_cfg *cfg)
4746 {
4747         struct mdt_device *m = mdt_dev(d);
4748         struct md_device *md_next = m->mdt_child;
4749         struct lu_device *next = md2lu_dev(md_next);
4750         int rc;
4751         ENTRY;
4752
4753         switch (cfg->lcfg_command) {
4754         case LCFG_PARAM: {
4755                 struct obd_device          *obd = d->ld_obd;
4756
4757                 /* For interoperability */
4758                 struct cfg_interop_param   *ptr = NULL;
4759                 struct lustre_cfg          *old_cfg = NULL;
4760                 char                       *param = NULL;
4761
4762                 param = lustre_cfg_string(cfg, 1);
4763                 if (param == NULL) {
4764                         CERROR("param is empty\n");
4765                         rc = -EINVAL;
4766                         break;
4767                 }
4768
4769                 ptr = class_find_old_param(param, mdt_interop_param);
4770                 if (ptr != NULL) {
4771                         if (ptr->new_param == NULL) {
4772                                 rc = 0;
4773                                 CWARN("For interoperability, skip this %s."
4774                                       " It is obsolete.\n", ptr->old_param);
4775                                 break;
4776                         }
4777
4778                         CWARN("Found old param %s, changed it to %s.\n",
4779                               ptr->old_param, ptr->new_param);
4780
4781                         old_cfg = cfg;
4782                         cfg = lustre_cfg_rename(old_cfg, ptr->new_param);
4783                         if (IS_ERR(cfg)) {
4784                                 rc = PTR_ERR(cfg);
4785                                 break;
4786                         }
4787                 }
4788
4789                 rc = class_process_proc_param(PARAM_MDT, obd->obd_vars,
4790                                               cfg, obd);
4791                 if (rc > 0 || rc == -ENOSYS) {
4792                         /* is it an HSM var ? */
4793                         rc = class_process_proc_param(PARAM_HSM,
4794                                                       hsm_cdt_get_proc_vars(),
4795                                                       cfg, obd);
4796                         if (rc > 0 || rc == -ENOSYS)
4797                                 /* we don't understand; pass it on */
4798                                 rc = next->ld_ops->ldo_process_config(env, next,
4799                                                                       cfg);
4800                 }
4801
4802                 if (old_cfg != NULL)
4803                         lustre_cfg_free(cfg);
4804
4805                 break;
4806         }
4807         default:
4808                 /* others are passed further */
4809                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
4810                 break;
4811         }
4812         RETURN(rc);
4813 }
4814
4815 static struct lu_object *mdt_object_alloc(const struct lu_env *env,
4816                                           const struct lu_object_header *hdr,
4817                                           struct lu_device *d)
4818 {
4819         struct mdt_object *mo;
4820
4821         ENTRY;
4822
4823         OBD_SLAB_ALLOC_PTR_GFP(mo, mdt_object_kmem, GFP_NOFS);
4824         if (mo != NULL) {
4825                 struct lu_object *o;
4826                 struct lu_object_header *h;
4827
4828                 o = &mo->mot_obj;
4829                 h = &mo->mot_header;
4830                 lu_object_header_init(h);
4831                 lu_object_init(o, h, d);
4832                 lu_object_add_top(h, o);
4833                 o->lo_ops = &mdt_obj_ops;
4834                 mutex_init(&mo->mot_ioepoch_mutex);
4835                 mutex_init(&mo->mot_lov_mutex);
4836                 init_rwsem(&mo->mot_open_sem);
4837                 RETURN(o);
4838         }
4839         RETURN(NULL);
4840 }
4841
4842 static int mdt_object_init(const struct lu_env *env, struct lu_object *o,
4843                            const struct lu_object_conf *unused)
4844 {
4845         struct mdt_device *d = mdt_dev(o->lo_dev);
4846         struct lu_device  *under;
4847         struct lu_object  *below;
4848         int                rc = 0;
4849         ENTRY;
4850
4851         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
4852                PFID(lu_object_fid(o)));
4853
4854         under = &d->mdt_child->md_lu_dev;
4855         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
4856         if (below != NULL) {
4857                 lu_object_add(o, below);
4858         } else
4859                 rc = -ENOMEM;
4860
4861         RETURN(rc);
4862 }
4863
4864 static void mdt_object_free(const struct lu_env *env, struct lu_object *o)
4865 {
4866         struct mdt_object *mo = mdt_obj(o);
4867         struct lu_object_header *h;
4868         ENTRY;
4869
4870         h = o->lo_header;
4871         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
4872                PFID(lu_object_fid(o)));
4873
4874         LASSERT(atomic_read(&mo->mot_open_count) == 0);
4875         LASSERT(atomic_read(&mo->mot_lease_count) == 0);
4876
4877         lu_object_fini(o);
4878         lu_object_header_fini(h);
4879         OBD_SLAB_FREE_PTR(mo, mdt_object_kmem);
4880
4881         EXIT;
4882 }
4883
4884 static int mdt_object_print(const struct lu_env *env, void *cookie,
4885                             lu_printer_t p, const struct lu_object *o)
4886 {
4887         struct mdt_object *mdto = mdt_obj((struct lu_object *)o);
4888         return (*p)(env, cookie, LUSTRE_MDT_NAME"-object@%p(ioepoch="LPU64" "
4889                     "flags="LPX64", epochcount=%d, writecount=%d)",
4890                     mdto, mdto->mot_ioepoch, mdto->mot_flags,
4891                     mdto->mot_ioepoch_count, mdto->mot_writecount);
4892 }
4893
4894 static int mdt_prepare(const struct lu_env *env,
4895                 struct lu_device *pdev,
4896                 struct lu_device *cdev)
4897 {
4898         struct mdt_device *mdt = mdt_dev(cdev);
4899         struct lu_device *next = &mdt->mdt_child->md_lu_dev;
4900         struct obd_device *obd = cdev->ld_obd;
4901         int rc;
4902
4903         ENTRY;
4904
4905         LASSERT(obd);
4906
4907         rc = next->ld_ops->ldo_prepare(env, cdev, next);
4908         if (rc)
4909                 RETURN(rc);
4910
4911         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_CHANGELOG_ORIG_CTXT);
4912         if (rc)
4913                 RETURN(rc);
4914
4915         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_AGENT_ORIG_CTXT);
4916         if (rc)
4917                 RETURN(rc);
4918
4919         rc = lfsck_register_namespace(env, mdt->mdt_bottom, mdt->mdt_namespace);
4920         /* The LFSCK instance is registered just now, so it must be there when
4921          * register the namespace to such instance. */
4922         LASSERTF(rc == 0, "register namespace failed: rc = %d\n", rc);
4923
4924         if (mdt->mdt_seq_site.ss_node_id == 0) {
4925                 rc = mdt->mdt_child->md_ops->mdo_root_get(env, mdt->mdt_child,
4926                                                          &mdt->mdt_md_root_fid);
4927                 if (rc)
4928                         RETURN(rc);
4929         }
4930
4931         LASSERT(!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state));
4932         target_recovery_init(&mdt->mdt_lut, tgt_request_handle);
4933         set_bit(MDT_FL_CFGLOG, &mdt->mdt_state);
4934         LASSERT(obd->obd_no_conn);
4935         spin_lock(&obd->obd_dev_lock);
4936         obd->obd_no_conn = 0;
4937         spin_unlock(&obd->obd_dev_lock);
4938
4939         if (obd->obd_recovering == 0)
4940                 mdt_postrecov(env, mdt);
4941
4942         RETURN(rc);
4943 }
4944
4945 const struct lu_device_operations mdt_lu_ops = {
4946         .ldo_object_alloc   = mdt_object_alloc,
4947         .ldo_process_config = mdt_process_config,
4948         .ldo_prepare        = mdt_prepare,
4949 };
4950
4951 static const struct lu_object_operations mdt_obj_ops = {
4952         .loo_object_init    = mdt_object_init,
4953         .loo_object_free    = mdt_object_free,
4954         .loo_object_print   = mdt_object_print
4955 };
4956
4957 static int mdt_obd_set_info_async(const struct lu_env *env,
4958                                   struct obd_export *exp,
4959                                   __u32 keylen, void *key,
4960                                   __u32 vallen, void *val,
4961                                   struct ptlrpc_request_set *set)
4962 {
4963         int rc;
4964
4965         ENTRY;
4966
4967         if (KEY_IS(KEY_SPTLRPC_CONF)) {
4968                 rc = tgt_adapt_sptlrpc_conf(class_exp2tgt(exp), 0);
4969                 RETURN(rc);
4970         }
4971
4972         RETURN(0);
4973 }
4974
4975 /**
4976  * Match client and server connection feature flags.
4977  *
4978  * Compute the compatibility flags for a connection request based on
4979  * features mutually supported by client and server.
4980  *
4981  * The obd_export::exp_connect_data.ocd_connect_flags field in \a exp
4982  * must not be updated here, otherwise a partially initialized value may
4983  * be exposed. After the connection request is successfully processed,
4984  * the top-level MDT connect request handler atomically updates the export
4985  * connect flags from the obd_connect_data::ocd_connect_flags field of the
4986  * reply. \see mdt_connect().
4987  *
4988  * \param exp   the obd_export associated with this client/target pair
4989  * \param mdt   the target device for the connection
4990  * \param data  stores data for this connect request
4991  *
4992  * \retval 0       success
4993  * \retval -EPROTO \a data unexpectedly has zero obd_connect_data::ocd_brw_size
4994  * \retval -EBADE  client and server feature requirements are incompatible
4995  */
4996 static int mdt_connect_internal(struct obd_export *exp,
4997                                 struct mdt_device *mdt,
4998                                 struct obd_connect_data *data)
4999 {
5000         LASSERT(data != NULL);
5001
5002         data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
5003         data->ocd_ibits_known &= MDS_INODELOCK_FULL;
5004
5005         if (!(data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
5006             !(data->ocd_connect_flags & OBD_CONNECT_IBITS)) {
5007                 CWARN("%s: client %s does not support ibits lock, either "
5008                       "very old or an invalid client: flags "LPX64"\n",
5009                       mdt_obd_name(mdt), exp->exp_client_uuid.uuid,
5010                       data->ocd_connect_flags);
5011                 return -EBADE;
5012         }
5013
5014         if (!mdt->mdt_opts.mo_acl)
5015                 data->ocd_connect_flags &= ~OBD_CONNECT_ACL;
5016
5017         if (!mdt->mdt_opts.mo_user_xattr)
5018                 data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
5019
5020         if (!mdt->mdt_som_conf)
5021                 data->ocd_connect_flags &= ~OBD_CONNECT_SOM;
5022
5023         if (data->ocd_connect_flags & OBD_CONNECT_BRW_SIZE) {
5024                 data->ocd_brw_size = min(data->ocd_brw_size,
5025                                          (__u32)MD_MAX_BRW_SIZE);
5026                 if (data->ocd_brw_size == 0) {
5027                         CERROR("%s: cli %s/%p ocd_connect_flags: "LPX64
5028                                " ocd_version: %x ocd_grant: %d "
5029                                "ocd_index: %u ocd_brw_size is "
5030                                "unexpectedly zero, network data "
5031                                "corruption? Refusing connection of this"
5032                                " client\n",
5033                                mdt_obd_name(mdt),
5034                                exp->exp_client_uuid.uuid,
5035                                exp, data->ocd_connect_flags, data->ocd_version,
5036                                data->ocd_grant, data->ocd_index);
5037                         return -EPROTO;
5038                 }
5039         }
5040
5041         /* NB: Disregard the rule against updating
5042          * exp_connect_data.ocd_connect_flags in this case, since
5043          * tgt_client_new() needs to know if this is a lightweight
5044          * connection, and it is safe to expose this flag before
5045          * connection processing completes. */
5046         if (data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) {
5047                 spin_lock(&exp->exp_lock);
5048                 *exp_connect_flags_ptr(exp) |= OBD_CONNECT_LIGHTWEIGHT;
5049                 spin_unlock(&exp->exp_lock);
5050         }
5051
5052         data->ocd_version = LUSTRE_VERSION_CODE;
5053
5054         if ((data->ocd_connect_flags & OBD_CONNECT_FID) == 0) {
5055                 CWARN("%s: MDS requires FID support, but client not\n",
5056                       mdt_obd_name(mdt));
5057                 return -EBADE;
5058         }
5059
5060         if (mdt->mdt_som_conf &&
5061             !(data->ocd_connect_flags & (OBD_CONNECT_LIGHTWEIGHT |
5062                                          OBD_CONNECT_MDS_MDS |
5063                                          OBD_CONNECT_SOM))) {
5064                 CWARN("%s: MDS has SOM enabled, but client does not support "
5065                       "it\n", mdt_obd_name(mdt));
5066                 return -EBADE;
5067         }
5068
5069         if (OCD_HAS_FLAG(data, PINGLESS)) {
5070                 if (ptlrpc_pinger_suppress_pings()) {
5071                         spin_lock(&exp->exp_obd->obd_dev_lock);
5072                         list_del_init(&exp->exp_obd_chain_timed);
5073                         spin_unlock(&exp->exp_obd->obd_dev_lock);
5074                 } else {
5075                         data->ocd_connect_flags &= ~OBD_CONNECT_PINGLESS;
5076                 }
5077         }
5078
5079         data->ocd_max_easize = mdt->mdt_max_ea_size;
5080
5081         return 0;
5082 }
5083
5084 static int mdt_ctxt_add_dirty_flag(struct lu_env *env,
5085                                    struct mdt_thread_info *info,
5086                                    struct mdt_file_data *mfd)
5087 {
5088         struct lu_context ses;
5089         int rc;
5090         ENTRY;
5091
5092         rc = lu_context_init(&ses, LCT_SERVER_SESSION);
5093         if (rc)
5094                 RETURN(rc);
5095
5096         env->le_ses = &ses;
5097         lu_context_enter(&ses);
5098
5099         mdt_ucred(info)->uc_valid = UCRED_OLD;
5100         rc = mdt_add_dirty_flag(info, mfd->mfd_object, &info->mti_attr);
5101
5102         lu_context_exit(&ses);
5103         lu_context_fini(&ses);
5104         env->le_ses = NULL;
5105
5106         RETURN(rc);
5107 }
5108
5109 static int mdt_export_cleanup(struct obd_export *exp)
5110 {
5111         struct list_head         closing_list;
5112         struct mdt_export_data  *med = &exp->exp_mdt_data;
5113         struct obd_device       *obd = exp->exp_obd;
5114         struct mdt_device       *mdt;
5115         struct mdt_thread_info  *info;
5116         struct lu_env            env;
5117         struct mdt_file_data    *mfd, *n;
5118         int rc = 0;
5119         ENTRY;
5120
5121         INIT_LIST_HEAD(&closing_list);
5122         spin_lock(&med->med_open_lock);
5123         while (!list_empty(&med->med_open_head)) {
5124                 struct list_head *tmp = med->med_open_head.next;
5125                 mfd = list_entry(tmp, struct mdt_file_data, mfd_list);
5126
5127                 /* Remove mfd handle so it can't be found again.
5128                  * We are consuming the mfd_list reference here. */
5129                 class_handle_unhash(&mfd->mfd_handle);
5130                 list_move_tail(&mfd->mfd_list, &closing_list);
5131         }
5132         spin_unlock(&med->med_open_lock);
5133         mdt = mdt_dev(obd->obd_lu_dev);
5134         LASSERT(mdt != NULL);
5135
5136         rc = lu_env_init(&env, LCT_MD_THREAD);
5137         if (rc)
5138                 RETURN(rc);
5139
5140         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5141         LASSERT(info != NULL);
5142         memset(info, 0, sizeof *info);
5143         info->mti_env = &env;
5144         info->mti_mdt = mdt;
5145         info->mti_exp = exp;
5146
5147         if (!list_empty(&closing_list)) {
5148                 struct md_attr *ma = &info->mti_attr;
5149
5150                 /* Close any open files (which may also cause orphan
5151                  * unlinking). */
5152                 list_for_each_entry_safe(mfd, n, &closing_list, mfd_list) {
5153                         list_del_init(&mfd->mfd_list);
5154                         ma->ma_need = ma->ma_valid = 0;
5155
5156                         /* This file is being closed due to an eviction, it
5157                          * could have been modified and now dirty regarding to
5158                          * HSM archive, check this!
5159                          * The logic here is to mark a file dirty if there's a
5160                          * chance it was dirtied before the client was evicted,
5161                          * so that we don't have to wait for a release attempt
5162                          * before finding out the file was actually dirty and
5163                          * fail the release. Aggressively marking it dirty here
5164                          * will cause the policy engine to attempt to
5165                          * re-archive it; when rearchiving, we can compare the
5166                          * current version to the HSM data_version and make the
5167                          * archive request into a noop if it's not actually
5168                          * dirty.
5169                          */
5170                         if (mfd->mfd_mode & (FMODE_WRITE|MDS_FMODE_TRUNC))
5171                                 rc = mdt_ctxt_add_dirty_flag(&env, info, mfd);
5172
5173                         /* Don't unlink orphan on failover umount, LU-184 */
5174                         if (exp->exp_flags & OBD_OPT_FAILOVER) {
5175                                 ma->ma_valid = MA_FLAGS;
5176                                 ma->ma_attr_flags |= MDS_KEEP_ORPHAN;
5177                         }
5178                         mdt_mfd_close(info, mfd);
5179                 }
5180         }
5181         info->mti_mdt = NULL;
5182         /* cleanup client slot early */
5183         /* Do not erase record for recoverable client. */
5184         if (!(exp->exp_flags & OBD_OPT_FAILOVER) || exp->exp_failed)
5185                 tgt_client_del(&env, exp);
5186         lu_env_fini(&env);
5187
5188         RETURN(rc);
5189 }
5190
5191 static int mdt_obd_disconnect(struct obd_export *exp)
5192 {
5193         int rc;
5194         ENTRY;
5195
5196         LASSERT(exp);
5197         class_export_get(exp);
5198
5199         nodemap_del_member(exp);
5200         rc = server_disconnect_export(exp);
5201         if (rc != 0)
5202                 CDEBUG(D_IOCTL, "server disconnect error: rc = %d\n", rc);
5203
5204         rc = mdt_export_cleanup(exp);
5205         class_export_put(exp);
5206         RETURN(rc);
5207 }
5208
5209 /* mds_connect copy */
5210 static int mdt_obd_connect(const struct lu_env *env,
5211                            struct obd_export **exp, struct obd_device *obd,
5212                            struct obd_uuid *cluuid,
5213                            struct obd_connect_data *data,
5214                            void *localdata)
5215 {
5216         struct obd_export       *lexp;
5217         struct lustre_handle    conn = { 0 };
5218         struct mdt_device       *mdt;
5219         int                      rc;
5220         lnet_nid_t              *client_nid = localdata;
5221         ENTRY;
5222
5223         LASSERT(env != NULL);
5224         if (!exp || !obd || !cluuid)
5225                 RETURN(-EINVAL);
5226
5227         mdt = mdt_dev(obd->obd_lu_dev);
5228
5229         /*
5230          * first, check whether the stack is ready to handle requests
5231          * XXX: probably not very appropriate method is used now
5232          *      at some point we should find a better one
5233          */
5234         if (!test_bit(MDT_FL_SYNCED, &mdt->mdt_state) && data != NULL &&
5235             !(data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT)) {
5236                 rc = obd_get_info(env, mdt->mdt_child_exp,
5237                                   sizeof(KEY_OSP_CONNECTED),
5238                                   KEY_OSP_CONNECTED, NULL, NULL, NULL);
5239                 if (rc)
5240                         RETURN(-EAGAIN);
5241                 set_bit(MDT_FL_SYNCED, &mdt->mdt_state);
5242         }
5243
5244         rc = class_connect(&conn, obd, cluuid);
5245         if (rc)
5246                 RETURN(rc);
5247
5248         lexp = class_conn2export(&conn);
5249         LASSERT(lexp != NULL);
5250
5251         rc = mdt_connect_internal(lexp, mdt, data);
5252         if (rc == 0) {
5253                 struct lsd_client_data *lcd = lexp->exp_target_data.ted_lcd;
5254
5255                 LASSERT(lcd);
5256                 memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
5257                 rc = tgt_client_new(env, lexp);
5258                 if (rc == 0) {
5259                         rc = nodemap_add_member(*client_nid, lexp);
5260                         if (rc != 0 && rc != -EEXIST)
5261                                 goto out;
5262
5263                         mdt_export_stats_init(obd, lexp, localdata);
5264                 }
5265
5266                 /* For phase I, sync for cross-ref operation. */
5267                 spin_lock(&lexp->exp_lock);
5268                 lexp->exp_keep_sync = 1;
5269                 spin_unlock(&lexp->exp_lock);
5270         }
5271 out:
5272         if (rc != 0) {
5273                 class_disconnect(lexp);
5274                 *exp = NULL;
5275         } else {
5276                 *exp = lexp;
5277         }
5278
5279         RETURN(rc);
5280 }
5281
5282 static int mdt_obd_reconnect(const struct lu_env *env,
5283                              struct obd_export *exp, struct obd_device *obd,
5284                              struct obd_uuid *cluuid,
5285                              struct obd_connect_data *data,
5286                              void *localdata)
5287 {
5288         lnet_nid_t             *client_nid = localdata;
5289         int                     rc;
5290         ENTRY;
5291
5292         if (exp == NULL || obd == NULL || cluuid == NULL)
5293                 RETURN(-EINVAL);
5294
5295         rc = mdt_connect_internal(exp, mdt_dev(obd->obd_lu_dev), data);
5296         if (rc == 0) {
5297                 rc = nodemap_add_member(*client_nid, exp);
5298                 if (rc == 0 || rc == -EEXIST)
5299                         mdt_export_stats_init(obd, exp, localdata);
5300         }
5301
5302         RETURN(rc);
5303 }
5304
5305 /* FIXME: Can we avoid using these two interfaces? */
5306 static int mdt_init_export(struct obd_export *exp)
5307 {
5308         struct mdt_export_data *med = &exp->exp_mdt_data;
5309         int                     rc;
5310         ENTRY;
5311
5312         INIT_LIST_HEAD(&med->med_open_head);
5313         spin_lock_init(&med->med_open_lock);
5314         mutex_init(&med->med_idmap_mutex);
5315         med->med_idmap = NULL;
5316         spin_lock(&exp->exp_lock);
5317         exp->exp_connecting = 1;
5318         spin_unlock(&exp->exp_lock);
5319
5320         /* self-export doesn't need client data and ldlm initialization */
5321         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5322                                      &exp->exp_client_uuid)))
5323                 RETURN(0);
5324
5325         rc = tgt_client_alloc(exp);
5326         if (rc)
5327                 GOTO(err, rc);
5328
5329         rc = ldlm_init_export(exp);
5330         if (rc)
5331                 GOTO(err_free, rc);
5332
5333         RETURN(rc);
5334
5335 err_free:
5336         tgt_client_free(exp);
5337 err:
5338         CERROR("%s: Failed to initialize export: rc = %d\n",
5339                exp->exp_obd->obd_name, rc);
5340         return rc;
5341 }
5342
5343 static int mdt_destroy_export(struct obd_export *exp)
5344 {
5345         ENTRY;
5346
5347         if (exp_connect_rmtclient(exp))
5348                 mdt_cleanup_idmap(&exp->exp_mdt_data);
5349
5350         target_destroy_export(exp);
5351         /* destroy can be called from failed obd_setup, so
5352          * checking uuid is safer than obd_self_export */
5353         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5354                                      &exp->exp_client_uuid)))
5355                 RETURN(0);
5356
5357         ldlm_destroy_export(exp);
5358         tgt_client_free(exp);
5359
5360         LASSERT(list_empty(&exp->exp_outstanding_replies));
5361         LASSERT(list_empty(&exp->exp_mdt_data.med_open_head));
5362
5363         RETURN(0);
5364 }
5365
5366 int mdt_links_read(struct mdt_thread_info *info, struct mdt_object *mdt_obj,
5367                    struct linkea_data *ldata)
5368 {
5369         int rc;
5370
5371         LASSERT(ldata->ld_buf->lb_buf != NULL);
5372
5373         if (!mdt_object_exists(mdt_obj))
5374                 return -ENODATA;
5375
5376         rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5377                           ldata->ld_buf, XATTR_NAME_LINK);
5378         if (rc == -ERANGE) {
5379                 /* Buf was too small, figure out what we need. */
5380                 lu_buf_free(ldata->ld_buf);
5381                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5382                                   ldata->ld_buf, XATTR_NAME_LINK);
5383                 if (rc < 0)
5384                         return rc;
5385                 ldata->ld_buf = lu_buf_check_and_alloc(ldata->ld_buf, rc);
5386                 if (ldata->ld_buf->lb_buf == NULL)
5387                         return -ENOMEM;
5388                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5389                                   ldata->ld_buf, XATTR_NAME_LINK);
5390         }
5391         if (rc < 0)
5392                 return rc;
5393
5394         return linkea_init(ldata);
5395 }
5396
5397 /**
5398  * Given an MDT object, try to look up the full path to the object.
5399  * Part of the MDT layer implementation of lfs fid2path.
5400  *
5401  * \param[in]     info  Per-thread common data shared by MDT level handlers.
5402  * \param[in]     obj   Object to do path lookup of
5403  * \param[in,out] fp    User-provided struct to store path information
5404  *
5405  * \retval 0 Lookup successful, path information stored in fp
5406  * \retval -EAGAIN Lookup failed, usually because object is being moved
5407  * \retval negative errno if there was a problem
5408  */
5409 static int mdt_path_current(struct mdt_thread_info *info,
5410                             struct mdt_object *obj,
5411                             struct getinfo_fid2path *fp)
5412 {
5413         struct mdt_device       *mdt = info->mti_mdt;
5414         struct mdt_object       *mdt_obj;
5415         struct link_ea_header   *leh;
5416         struct link_ea_entry    *lee;
5417         struct lu_name          *tmpname = &info->mti_name;
5418         struct lu_fid           *tmpfid = &info->mti_tmp_fid1;
5419         struct lu_buf           *buf = &info->mti_big_buf;
5420         char                    *ptr;
5421         int                     reclen;
5422         struct linkea_data      ldata = { NULL };
5423         int                     rc = 0;
5424         bool                    first = true;
5425         ENTRY;
5426
5427         /* temp buffer for path element, the buffer will be finally freed
5428          * in mdt_thread_info_fini */
5429         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
5430         if (buf->lb_buf == NULL)
5431                 RETURN(-ENOMEM);
5432
5433         ldata.ld_buf = buf;
5434         ptr = fp->gf_path + fp->gf_pathlen - 1;
5435         *ptr = 0;
5436         --ptr;
5437         *tmpfid = fp->gf_fid = *mdt_object_fid(obj);
5438
5439         /* root FID only exists on MDT0, and fid2path should also ends at MDT0,
5440          * so checking root_fid can only happen on MDT0. */
5441         while (!lu_fid_eq(&mdt->mdt_md_root_fid, &fp->gf_fid)) {
5442                 struct lu_buf           lmv_buf;
5443
5444                 mdt_obj = mdt_object_find(info->mti_env, mdt, tmpfid);
5445                 if (IS_ERR(mdt_obj))
5446                         GOTO(out, rc = PTR_ERR(mdt_obj));
5447
5448                 if (!mdt_object_exists(mdt_obj)) {
5449                         mdt_object_put(info->mti_env, mdt_obj);
5450                         GOTO(out, rc = -ENOENT);
5451                 }
5452
5453                 if (mdt_object_remote(mdt_obj)) {
5454                         mdt_object_put(info->mti_env, mdt_obj);
5455                         GOTO(remote_out, rc = -EREMOTE);
5456                 }
5457
5458                 rc = mdt_links_read(info, mdt_obj, &ldata);
5459                 if (rc != 0) {
5460                         mdt_object_put(info->mti_env, mdt_obj);
5461                         GOTO(out, rc);
5462                 }
5463
5464                 leh = buf->lb_buf;
5465                 lee = (struct link_ea_entry *)(leh + 1); /* link #0 */
5466                 linkea_entry_unpack(lee, &reclen, tmpname, tmpfid);
5467                 /* If set, use link #linkno for path lookup, otherwise use
5468                    link #0.  Only do this for the final path element. */
5469                 if (first && fp->gf_linkno < leh->leh_reccount) {
5470                         int count;
5471                         for (count = 0; count < fp->gf_linkno; count++) {
5472                                 lee = (struct link_ea_entry *)
5473                                      ((char *)lee + reclen);
5474                                 linkea_entry_unpack(lee, &reclen, tmpname,
5475                                                     tmpfid);
5476                         }
5477                         if (fp->gf_linkno < leh->leh_reccount - 1)
5478                                 /* indicate to user there are more links */
5479                                 fp->gf_linkno++;
5480                 }
5481
5482                 lmv_buf.lb_buf = info->mti_xattr_buf;
5483                 lmv_buf.lb_len = sizeof(info->mti_xattr_buf);
5484                 /* Check if it is slave stripes */
5485                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5486                                   &lmv_buf, XATTR_NAME_LMV);
5487                 mdt_object_put(info->mti_env, mdt_obj);
5488                 if (rc > 0) {
5489                         union lmv_mds_md *lmm = lmv_buf.lb_buf;
5490
5491                         /* For slave stripes, get its master */
5492                         if (le32_to_cpu(lmm->lmv_magic) == LMV_MAGIC_STRIPE) {
5493                                 fp->gf_fid = *tmpfid;
5494                                 continue;
5495                         }
5496                 } else if (rc < 0 && rc != -ENODATA) {
5497                         GOTO(out, rc);
5498                 }
5499
5500                 rc = 0;
5501
5502                 /* Pack the name in the end of the buffer */
5503                 ptr -= tmpname->ln_namelen;
5504                 if (ptr - 1 <= fp->gf_path)
5505                         GOTO(out, rc = -EOVERFLOW);
5506                 strncpy(ptr, tmpname->ln_name, tmpname->ln_namelen);
5507                 *(--ptr) = '/';
5508
5509                 /* keep the last resolved fid to the client, so the
5510                  * client will build the left path on another MDT for
5511                  * remote object */
5512                 fp->gf_fid = *tmpfid;
5513
5514                 first = false;
5515         }
5516
5517 remote_out:
5518         ptr++; /* skip leading / */
5519         memmove(fp->gf_path, ptr, fp->gf_path + fp->gf_pathlen - ptr);
5520
5521 out:
5522         RETURN(rc);
5523 }
5524
5525 /**
5526  * Given an MDT object, use mdt_path_current to get the path.
5527  * Essentially a wrapper to retry mdt_path_current a set number of times
5528  * if -EAGAIN is returned (usually because an object is being moved).
5529  *
5530  * Part of the MDT layer implementation of lfs fid2path.
5531  *
5532  * \param[in]     info  Per-thread common data shared by mdt level handlers.
5533  * \param[in]     obj   Object to do path lookup of
5534  * \param[in,out] fp    User-provided struct for arguments and to store path
5535  *                      information
5536  *
5537  * \retval 0 Lookup successful, path information stored in fp
5538  * \retval negative errno if there was a problem
5539  */
5540 static int mdt_path(struct mdt_thread_info *info, struct mdt_object *obj,
5541                     struct getinfo_fid2path *fp)
5542 {
5543         struct mdt_device       *mdt = info->mti_mdt;
5544         int                     tries = 3;
5545         int                     rc = -EAGAIN;
5546         ENTRY;
5547
5548         if (fp->gf_pathlen < 3)
5549                 RETURN(-EOVERFLOW);
5550
5551         if (lu_fid_eq(&mdt->mdt_md_root_fid, mdt_object_fid(obj))) {
5552                 fp->gf_path[0] = '\0';
5553                 RETURN(0);
5554         }
5555
5556         /* Retry multiple times in case file is being moved */
5557         while (tries-- && rc == -EAGAIN)
5558                 rc = mdt_path_current(info, obj, fp);
5559
5560         RETURN(rc);
5561 }
5562
5563 /**
5564  * Get the full path of the provided FID, as of changelog record recno.
5565  *
5566  * This checks sanity and looks up object for user provided FID
5567  * before calling the actual path lookup code.
5568  *
5569  * Part of the MDT layer implementation of lfs fid2path.
5570  *
5571  * \param[in]     info  Per-thread common data shared by mdt level handlers.
5572  * \param[in,out] fp    User-provided struct for arguments and to store path
5573  *                      information
5574  *
5575  * \retval 0 Lookup successful, path information and recno stored in fp
5576  * \retval -ENOENT, object does not exist
5577  * \retval negative errno if there was a problem
5578  */
5579 static int mdt_fid2path(struct mdt_thread_info *info,
5580                         struct getinfo_fid2path *fp)
5581 {
5582         struct mdt_device *mdt = info->mti_mdt;
5583         struct mdt_object *obj;
5584         int    rc;
5585         ENTRY;
5586
5587         CDEBUG(D_IOCTL, "path get "DFID" from "LPU64" #%d\n",
5588                 PFID(&fp->gf_fid), fp->gf_recno, fp->gf_linkno);
5589
5590         if (!fid_is_sane(&fp->gf_fid))
5591                 RETURN(-EINVAL);
5592
5593         if (!fid_is_namespace_visible(&fp->gf_fid)) {
5594                 CWARN("%s: "DFID" is invalid, sequence should be "
5595                       ">= "LPX64"\n", mdt_obd_name(mdt),
5596                       PFID(&fp->gf_fid), (__u64)FID_SEQ_NORMAL);
5597                 RETURN(-EINVAL);
5598         }
5599
5600         obj = mdt_object_find(info->mti_env, mdt, &fp->gf_fid);
5601         if (IS_ERR(obj)) {
5602                 rc = PTR_ERR(obj);
5603                 CDEBUG(D_IOCTL, "cannot find "DFID": rc = %d\n",
5604                        PFID(&fp->gf_fid), rc);
5605                 RETURN(rc);
5606         }
5607
5608         if (mdt_object_remote(obj))
5609                 rc = -EREMOTE;
5610         else if (!mdt_object_exists(obj))
5611                 rc = -ENOENT;
5612         else
5613                 rc = 0;
5614
5615         if (rc < 0) {
5616                 mdt_object_put(info->mti_env, obj);
5617                 CDEBUG(D_IOCTL, "nonlocal object "DFID": rc = %d\n",
5618                        PFID(&fp->gf_fid), rc);
5619                 RETURN(rc);
5620         }
5621
5622         rc = mdt_path(info, obj, fp);
5623
5624         CDEBUG(D_INFO, "fid "DFID", path %s recno "LPX64" linkno %u\n",
5625                PFID(&fp->gf_fid), fp->gf_path, fp->gf_recno, fp->gf_linkno);
5626
5627         mdt_object_put(info->mti_env, obj);
5628
5629         RETURN(rc);
5630 }
5631
5632 static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key,
5633                             void *val, int vallen)
5634 {
5635         struct getinfo_fid2path *fpout, *fpin;
5636         int rc = 0;
5637
5638         fpin = key + cfs_size_round(sizeof(KEY_FID2PATH));
5639         fpout = val;
5640
5641         if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
5642                 lustre_swab_fid2path(fpin);
5643
5644         memcpy(fpout, fpin, sizeof(*fpin));
5645         if (fpout->gf_pathlen != vallen - sizeof(*fpin))
5646                 RETURN(-EINVAL);
5647
5648         rc = mdt_fid2path(info, fpout);
5649         RETURN(rc);
5650 }
5651
5652 int mdt_get_info(struct tgt_session_info *tsi)
5653 {
5654         char    *key;
5655         int      keylen;
5656         __u32   *vallen;
5657         void    *valout;
5658         int      rc;
5659
5660         ENTRY;
5661
5662         key = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_KEY);
5663         if (key == NULL) {
5664                 CDEBUG(D_IOCTL, "No GETINFO key\n");
5665                 RETURN(err_serious(-EFAULT));
5666         }
5667         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_GETINFO_KEY,
5668                                       RCL_CLIENT);
5669
5670         vallen = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_VALLEN);
5671         if (vallen == NULL) {
5672                 CDEBUG(D_IOCTL, "%s: cannot get RMF_GETINFO_VALLEN buffer\n",
5673                                 tgt_name(tsi->tsi_tgt));
5674                 RETURN(err_serious(-EFAULT));
5675         }
5676
5677         req_capsule_set_size(tsi->tsi_pill, &RMF_GETINFO_VAL, RCL_SERVER,
5678                              *vallen);
5679         rc = req_capsule_server_pack(tsi->tsi_pill);
5680         if (rc)
5681                 RETURN(err_serious(rc));
5682
5683         valout = req_capsule_server_get(tsi->tsi_pill, &RMF_GETINFO_VAL);
5684         if (valout == NULL) {
5685                 CDEBUG(D_IOCTL, "%s: cannot get get-info RPC out buffer\n",
5686                                 tgt_name(tsi->tsi_tgt));
5687                 RETURN(err_serious(-EFAULT));
5688         }
5689
5690         if (KEY_IS(KEY_FID2PATH)) {
5691                 struct mdt_thread_info  *info = tsi2mdt_info(tsi);
5692
5693                 rc = mdt_rpc_fid2path(info, key, valout, *vallen);
5694                 mdt_thread_info_fini(info);
5695         } else {
5696                 rc = -EINVAL;
5697         }
5698         RETURN(rc);
5699 }
5700
5701 /* Pass the ioc down */
5702 static int mdt_ioc_child(struct lu_env *env, struct mdt_device *mdt,
5703                          unsigned int cmd, int len, void *data)
5704 {
5705         struct lu_context ioctl_session;
5706         struct md_device *next = mdt->mdt_child;
5707         int rc;
5708         ENTRY;
5709
5710         rc = lu_context_init(&ioctl_session, LCT_SERVER_SESSION);
5711         if (rc)
5712                 RETURN(rc);
5713         ioctl_session.lc_thread = (struct ptlrpc_thread *)current;
5714         lu_context_enter(&ioctl_session);
5715         env->le_ses = &ioctl_session;
5716
5717         LASSERT(next->md_ops->mdo_iocontrol);
5718         rc = next->md_ops->mdo_iocontrol(env, next, cmd, len, data);
5719
5720         lu_context_exit(&ioctl_session);
5721         lu_context_fini(&ioctl_session);
5722         RETURN(rc);
5723 }
5724
5725 static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
5726 {
5727         struct obd_ioctl_data *data = karg;
5728         struct lu_fid *fid;
5729         __u64 version;
5730         struct mdt_object *obj;
5731         struct mdt_lock_handle  *lh;
5732         int rc;
5733         ENTRY;
5734
5735         if (data->ioc_inlbuf1 == NULL || data->ioc_inllen1 != sizeof(*fid) ||
5736             data->ioc_inlbuf2 == NULL || data->ioc_inllen2 != sizeof(version))
5737                 RETURN(-EINVAL);
5738
5739         fid = (struct lu_fid *)data->ioc_inlbuf1;
5740
5741         if (!fid_is_sane(fid))
5742                 RETURN(-EINVAL);
5743
5744         CDEBUG(D_IOCTL, "getting version for "DFID"\n", PFID(fid));
5745
5746         lh = &mti->mti_lh[MDT_LH_PARENT];
5747         mdt_lock_reg_init(lh, LCK_CR);
5748
5749         obj = mdt_object_find_lock(mti, fid, lh, MDS_INODELOCK_UPDATE);
5750         if (IS_ERR(obj))
5751                 RETURN(PTR_ERR(obj));
5752
5753         if (mdt_object_remote(obj)) {
5754                 rc = -EREMOTE;
5755                 /**
5756                  * before calling version get the correct MDS should be
5757                  * fid, this is error to find remote object here
5758                  */
5759                 CERROR("nonlocal object "DFID"\n", PFID(fid));
5760         } else if (!mdt_object_exists(obj)) {
5761                 *(__u64 *)data->ioc_inlbuf2 = ENOENT_VERSION;
5762                 rc = -ENOENT;
5763         } else {
5764                 version = dt_version_get(mti->mti_env, mdt_obj2dt(obj));
5765                *(__u64 *)data->ioc_inlbuf2 = version;
5766                 rc = 0;
5767         }
5768         mdt_object_unlock_put(mti, obj, lh, 1);
5769         RETURN(rc);
5770 }
5771
5772 /* ioctls on obd dev */
5773 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
5774                          void *karg, void *uarg)
5775 {
5776         struct lu_env      env;
5777         struct obd_device *obd = exp->exp_obd;
5778         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
5779         struct dt_device  *dt = mdt->mdt_bottom;
5780         int rc;
5781
5782         ENTRY;
5783         CDEBUG(D_IOCTL, "handling ioctl cmd %#x\n", cmd);
5784         rc = lu_env_init(&env, LCT_MD_THREAD);
5785         if (rc)
5786                 RETURN(rc);
5787
5788         switch (cmd) {
5789         case OBD_IOC_SYNC:
5790                 rc = mdt_device_sync(&env, mdt);
5791                 break;
5792         case OBD_IOC_SET_READONLY:
5793                 rc = dt->dd_ops->dt_ro(&env, dt);
5794                 break;
5795         case OBD_IOC_ABORT_RECOVERY:
5796                 CERROR("%s: Aborting recovery for device\n", mdt_obd_name(mdt));
5797                 target_stop_recovery_thread(obd);
5798                 rc = 0;
5799                 break;
5800         case OBD_IOC_CHANGELOG_REG:
5801         case OBD_IOC_CHANGELOG_DEREG:
5802         case OBD_IOC_CHANGELOG_CLEAR:
5803                 rc = mdt_ioc_child(&env, mdt, cmd, len, karg);
5804                 break;
5805         case OBD_IOC_START_LFSCK: {
5806                 struct md_device *next = mdt->mdt_child;
5807                 struct obd_ioctl_data *data = karg;
5808                 struct lfsck_start_param lsp;
5809
5810                 if (unlikely(data == NULL)) {
5811                         rc = -EINVAL;
5812                         break;
5813                 }
5814
5815                 lsp.lsp_start = (struct lfsck_start *)(data->ioc_inlbuf1);
5816                 lsp.lsp_index_valid = 0;
5817                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &lsp);
5818                 break;
5819         }
5820         case OBD_IOC_STOP_LFSCK: {
5821                 struct md_device        *next = mdt->mdt_child;
5822                 struct obd_ioctl_data   *data = karg;
5823                 struct lfsck_stop        stop;
5824
5825                 stop.ls_status = LS_STOPPED;
5826                 /* Old lfsck utils may pass NULL @stop. */
5827                 if (data->ioc_inlbuf1 == NULL)
5828                         stop.ls_flags = 0;
5829                 else
5830                         stop.ls_flags =
5831                         ((struct lfsck_stop *)(data->ioc_inlbuf1))->ls_flags;
5832
5833                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &stop);
5834                 break;
5835         }
5836         case OBD_IOC_GET_OBJ_VERSION: {
5837                 struct mdt_thread_info *mti;
5838                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5839                 memset(mti, 0, sizeof *mti);
5840                 mti->mti_env = &env;
5841                 mti->mti_mdt = mdt;
5842                 mti->mti_exp = exp;
5843
5844                 rc = mdt_ioc_version_get(mti, karg);
5845                 break;
5846         }
5847         case OBD_IOC_CATLOGLIST: {
5848                 struct mdt_thread_info *mti;
5849
5850                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5851                 lu_local_obj_fid(&mti->mti_tmp_fid1, LLOG_CATALOGS_OID);
5852                 rc = llog_catalog_list(&env, mdt->mdt_bottom, 0, karg,
5853                                        &mti->mti_tmp_fid1);
5854                 break;
5855          }
5856         default:
5857                 rc = -EOPNOTSUPP;
5858                 CERROR("%s: Not supported cmd = %d, rc = %d\n",
5859                         mdt_obd_name(mdt), cmd, rc);
5860         }
5861
5862         lu_env_fini(&env);
5863         RETURN(rc);
5864 }
5865
5866 static int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
5867 {
5868         struct lu_device *ld = md2lu_dev(mdt->mdt_child);
5869         struct lfsck_start_param lsp;
5870         int rc;
5871         ENTRY;
5872
5873         lsp.lsp_start = NULL;
5874         lsp.lsp_index_valid = 0;
5875         rc = mdt->mdt_child->md_ops->mdo_iocontrol(env, mdt->mdt_child,
5876                                                    OBD_IOC_START_LFSCK,
5877                                                    0, &lsp);
5878         if (rc != 0 && rc != -EALREADY)
5879                 CWARN("%s: auto trigger paused LFSCK failed: rc = %d\n",
5880                       mdt_obd_name(mdt), rc);
5881
5882         rc = ld->ld_ops->ldo_recovery_complete(env, ld);
5883         RETURN(rc);
5884 }
5885
5886 static int mdt_obd_postrecov(struct obd_device *obd)
5887 {
5888         struct lu_env env;
5889         int rc;
5890
5891         rc = lu_env_init(&env, LCT_MD_THREAD);
5892         if (rc)
5893                 RETURN(rc);
5894         rc = mdt_postrecov(&env, mdt_dev(obd->obd_lu_dev));
5895         lu_env_fini(&env);
5896         return rc;
5897 }
5898
5899 static struct obd_ops mdt_obd_device_ops = {
5900         .o_owner          = THIS_MODULE,
5901         .o_set_info_async = mdt_obd_set_info_async,
5902         .o_connect        = mdt_obd_connect,
5903         .o_reconnect      = mdt_obd_reconnect,
5904         .o_disconnect     = mdt_obd_disconnect,
5905         .o_init_export    = mdt_init_export,
5906         .o_destroy_export = mdt_destroy_export,
5907         .o_iocontrol      = mdt_iocontrol,
5908         .o_postrecov      = mdt_obd_postrecov,
5909 };
5910
5911 static struct lu_device* mdt_device_fini(const struct lu_env *env,
5912                                          struct lu_device *d)
5913 {
5914         struct mdt_device *m = mdt_dev(d);
5915         ENTRY;
5916
5917         mdt_fini(env, m);
5918         RETURN(NULL);
5919 }
5920
5921 static struct lu_device *mdt_device_free(const struct lu_env *env,
5922                                          struct lu_device *d)
5923 {
5924         struct mdt_device *m = mdt_dev(d);
5925         ENTRY;
5926
5927         lu_device_fini(&m->mdt_lu_dev);
5928         OBD_FREE_PTR(m);
5929
5930         RETURN(NULL);
5931 }
5932
5933 static struct lu_device *mdt_device_alloc(const struct lu_env *env,
5934                                           struct lu_device_type *t,
5935                                           struct lustre_cfg *cfg)
5936 {
5937         struct lu_device  *l;
5938         struct mdt_device *m;
5939
5940         OBD_ALLOC_PTR(m);
5941         if (m != NULL) {
5942                 int rc;
5943
5944                 l = &m->mdt_lu_dev;
5945                 rc = mdt_init0(env, m, t, cfg);
5946                 if (rc != 0) {
5947                         mdt_device_free(env, l);
5948                         l = ERR_PTR(rc);
5949                         return l;
5950                 }
5951         } else
5952                 l = ERR_PTR(-ENOMEM);
5953         return l;
5954 }
5955
5956 /* context key constructor/destructor: mdt_key_init, mdt_key_fini */
5957 LU_KEY_INIT(mdt, struct mdt_thread_info);
5958
5959 static void mdt_key_fini(const struct lu_context *ctx,
5960                          struct lu_context_key *key, void* data)
5961 {
5962         struct mdt_thread_info *info = data;
5963
5964         if (info->mti_big_lmm) {
5965                 OBD_FREE_LARGE(info->mti_big_lmm, info->mti_big_lmmsize);
5966                 info->mti_big_lmm = NULL;
5967                 info->mti_big_lmmsize = 0;
5968         }
5969         OBD_FREE_PTR(info);
5970 }
5971
5972 /* context key: mdt_thread_key */
5973 LU_CONTEXT_KEY_DEFINE(mdt, LCT_MD_THREAD);
5974
5975 struct lu_ucred *mdt_ucred(const struct mdt_thread_info *info)
5976 {
5977         return lu_ucred(info->mti_env);
5978 }
5979
5980 struct lu_ucred *mdt_ucred_check(const struct mdt_thread_info *info)
5981 {
5982         return lu_ucred_check(info->mti_env);
5983 }
5984
5985 /**
5986  * Enable/disable COS (Commit On Sharing).
5987  *
5988  * Set/Clear the COS flag in mdt options.
5989  *
5990  * \param mdt mdt device
5991  * \param val 0 disables COS, other values enable COS
5992  */
5993 void mdt_enable_cos(struct mdt_device *mdt, int val)
5994 {
5995         struct lu_env env;
5996         int rc;
5997
5998         mdt->mdt_opts.mo_cos = !!val;
5999         rc = lu_env_init(&env, LCT_LOCAL);
6000         if (unlikely(rc != 0)) {
6001                 CWARN("%s: lu_env initialization failed, cannot "
6002                       "sync: rc = %d\n", mdt_obd_name(mdt), rc);
6003                 return;
6004         }
6005         mdt_device_sync(&env, mdt);
6006         lu_env_fini(&env);
6007 }
6008
6009 /**
6010  * Check COS (Commit On Sharing) status.
6011  *
6012  * Return COS flag status.
6013  *
6014  * \param mdt mdt device
6015  */
6016 int mdt_cos_is_enabled(struct mdt_device *mdt)
6017 {
6018         return mdt->mdt_opts.mo_cos != 0;
6019 }
6020
6021 static struct lu_device_type_operations mdt_device_type_ops = {
6022         .ldto_device_alloc = mdt_device_alloc,
6023         .ldto_device_free  = mdt_device_free,
6024         .ldto_device_fini  = mdt_device_fini
6025 };
6026
6027 static struct lu_device_type mdt_device_type = {
6028         .ldt_tags     = LU_DEVICE_MD,
6029         .ldt_name     = LUSTRE_MDT_NAME,
6030         .ldt_ops      = &mdt_device_type_ops,
6031         .ldt_ctx_tags = LCT_MD_THREAD
6032 };
6033
6034 static int __init mdt_mod_init(void)
6035 {
6036         int rc;
6037
6038         CLASSERT(sizeof("0x0123456789ABCDEF:0x01234567:0x01234567") ==
6039                  FID_NOBRACE_LEN + 1);
6040         CLASSERT(sizeof("[0x0123456789ABCDEF:0x01234567:0x01234567]") ==
6041                  FID_LEN + 1);
6042         rc = lu_kmem_init(mdt_caches);
6043         if (rc)
6044                 return rc;
6045
6046         rc = mds_mod_init();
6047         if (rc)
6048                 GOTO(lu_fini, rc);
6049
6050         rc = class_register_type(&mdt_obd_device_ops, NULL, true, NULL,
6051                                  LUSTRE_MDT_NAME, &mdt_device_type);
6052         if (rc)
6053                 GOTO(mds_fini, rc);
6054 lu_fini:
6055         if (rc)
6056                 lu_kmem_fini(mdt_caches);
6057 mds_fini:
6058         if (rc)
6059                 mds_mod_exit();
6060         return rc;
6061 }
6062
6063 static void __exit mdt_mod_exit(void)
6064 {
6065         class_unregister_type(LUSTRE_MDT_NAME);
6066         mds_mod_exit();
6067         lu_kmem_fini(mdt_caches);
6068 }
6069
6070 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
6071 MODULE_DESCRIPTION("Lustre Metadata Target ("LUSTRE_MDT_NAME")");
6072 MODULE_LICENSE("GPL");
6073
6074 cfs_module(mdt, LUSTRE_VERSION_STRING, mdt_mod_init, mdt_mod_exit);