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