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