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