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