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