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