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