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