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