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