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