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