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