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