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