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