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