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