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