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