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