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