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