Whamcloud - gitweb
LU-16350 osd-ldiskfs: no_llseek removed, dquot_transfer
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/osd/osd_handler.c
32  *
33  * Top-level entry points into osd module
34  *
35  * Author: Nikita Danilov <nikita@clusterfs.com>
36  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
37  */
38
39 #define DEBUG_SUBSYSTEM S_OSD
40
41 #include <linux/fs_struct.h>
42 #include <linux/module.h>
43 #include <linux/user_namespace.h>
44 #include <linux/uidgid.h>
45
46 /* prerequisite for linux/xattr.h */
47 #include <linux/types.h>
48 /* prerequisite for linux/xattr.h */
49 #include <linux/fs.h>
50 /* XATTR_{REPLACE,CREATE} */
51 #include <linux/xattr.h>
52
53 #include <ldiskfs/ldiskfs.h>
54 #include <ldiskfs/xattr.h>
55 #include <ldiskfs/ldiskfs_extents.h>
56 #undef ENTRY
57 /*
58  * struct OBD_{ALLOC,FREE}*()
59  * OBD_FAIL_CHECK
60  */
61 #include <obd_support.h>
62 /* struct ptlrpc_thread */
63 #include <lustre_net.h>
64 #include <lustre_fid.h>
65 /* process_config */
66 #include <uapi/linux/lustre/lustre_param.h>
67
68 #include "osd_internal.h"
69 #include "osd_dynlocks.h"
70
71 /* llo_* api support */
72 #include <md_object.h>
73 #include <lustre_quota.h>
74
75 #include <lustre_linkea.h>
76
77 /* encoding routines */
78 #include <lustre_crypto.h>
79
80 /* Maximum EA size is limited by LNET_MTU for remote objects */
81 #define OSD_MAX_EA_SIZE 1048364
82
83 int ldiskfs_pdo = 1;
84 module_param(ldiskfs_pdo, int, 0644);
85 MODULE_PARM_DESC(ldiskfs_pdo, "ldiskfs with parallel directory operations");
86
87 int ldiskfs_track_declares_assert;
88 module_param(ldiskfs_track_declares_assert, int, 0644);
89 MODULE_PARM_DESC(ldiskfs_track_declares_assert, "LBUG during tracking of declares");
90
91 /* Slab to allocate dynlocks */
92 struct kmem_cache *dynlock_cachep;
93
94 /* Slab to allocate osd_it_ea */
95 struct kmem_cache *osd_itea_cachep;
96
97 static struct lu_kmem_descr ldiskfs_caches[] = {
98         {
99                 .ckd_cache = &dynlock_cachep,
100                 .ckd_name  = "dynlock_cache",
101                 .ckd_size  = sizeof(struct dynlock_handle)
102         },
103         {
104                 .ckd_cache = &osd_itea_cachep,
105                 .ckd_name  = "osd_itea_cache",
106                 .ckd_size  = sizeof(struct osd_it_ea)
107         },
108         {
109                 .ckd_cache = NULL
110         }
111 };
112
113 static const char dot[] = ".";
114 static const char dotdot[] = "..";
115
116 static const struct lu_object_operations      osd_lu_obj_ops;
117 static const struct dt_object_operations      osd_obj_ops;
118 static const struct dt_object_operations      osd_obj_otable_it_ops;
119 static const struct dt_index_operations       osd_index_iam_ops;
120 static const struct dt_index_operations       osd_index_ea_ops;
121
122 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
123                           const struct lu_fid *fid);
124 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
125                                                 struct osd_device *osd);
126 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
127                          const struct lu_buf *buf, const char *name, int fl,
128                          struct thandle *handle);
129
130 int osd_trans_declare_op2rb[] = {
131         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
132         [OSD_OT_PUNCH]          = OSD_OT_MAX,
133         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
134         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
135         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
136         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
137         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
138         [OSD_OT_WRITE]          = OSD_OT_WRITE,
139         [OSD_OT_INSERT]         = OSD_OT_DELETE,
140         [OSD_OT_DELETE]         = OSD_OT_INSERT,
141         [OSD_OT_QUOTA]          = OSD_OT_MAX,
142 };
143
144 static int osd_has_index(const struct osd_object *obj)
145 {
146         return obj->oo_dt.do_index_ops != NULL;
147 }
148
149 static int osd_object_invariant(const struct lu_object *l)
150 {
151         return osd_invariant(osd_obj(l));
152 }
153
154 /*
155  * Concurrency: doesn't matter
156  */
157 static int osd_is_write_locked(const struct lu_env *env, struct osd_object *o)
158 {
159         struct osd_thread_info *oti = osd_oti_get(env);
160
161         return oti->oti_w_locks > 0 && o->oo_owner == env;
162 }
163
164 /*
165  * Concurrency: doesn't access mutable data
166  */
167 static int osd_root_get(const struct lu_env *env,
168                         struct dt_device *dev, struct lu_fid *f)
169 {
170         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
171         return 0;
172 }
173
174 /*
175  * the following set of functions are used to maintain per-thread
176  * cache of FID->ino mapping. this mechanism is needed to resolve
177  * FID to inode at dt_insert() which in turn stores ino in the
178  * directory entries to keep ldiskfs compatible with ext[34].
179  * due to locking-originated restrictions we can't lookup ino
180  * using LU cache (deadlock is possible). lookup using OI is quite
181  * expensive. so instead we maintain this cache and methods like
182  * dt_create() fill it. so in the majority of cases dt_insert() is
183  * able to find needed mapping in lockless manner.
184  */
185 static struct osd_idmap_cache *
186 osd_idc_find(const struct lu_env *env, struct osd_device *osd,
187              const struct lu_fid *fid)
188 {
189         struct osd_thread_info *oti = osd_oti_get(env);
190         struct osd_idmap_cache *idc = oti->oti_ins_cache;
191         int i;
192
193         for (i = 0; i < oti->oti_ins_cache_used; i++) {
194                 if (!lu_fid_eq(&idc[i].oic_fid, fid))
195                         continue;
196                 if (idc[i].oic_dev != osd)
197                         continue;
198
199                 return idc + i;
200         }
201
202         return NULL;
203 }
204
205 static struct osd_idmap_cache *
206 osd_idc_add(const struct lu_env *env, struct osd_device *osd,
207             const struct lu_fid *fid)
208 {
209         struct osd_thread_info *oti   = osd_oti_get(env);
210         struct osd_idmap_cache *idc;
211         int i;
212
213         if (unlikely(oti->oti_ins_cache_used >= oti->oti_ins_cache_size)) {
214                 i = oti->oti_ins_cache_size * 2;
215                 if (i == 0)
216                         i = OSD_INS_CACHE_SIZE;
217                 OBD_ALLOC_PTR_ARRAY_LARGE(idc, i);
218                 if (idc == NULL)
219                         return ERR_PTR(-ENOMEM);
220                 if (oti->oti_ins_cache != NULL) {
221                         memcpy(idc, oti->oti_ins_cache,
222                                oti->oti_ins_cache_used * sizeof(*idc));
223                         OBD_FREE_PTR_ARRAY_LARGE(oti->oti_ins_cache,
224                                            oti->oti_ins_cache_used);
225                 }
226                 oti->oti_ins_cache = idc;
227                 oti->oti_ins_cache_size = i;
228         }
229
230         idc = oti->oti_ins_cache + oti->oti_ins_cache_used++;
231         idc->oic_fid = *fid;
232         idc->oic_dev = osd;
233         idc->oic_lid.oii_ino = 0;
234         idc->oic_lid.oii_gen = 0;
235         idc->oic_remote = 0;
236
237         return idc;
238 }
239
240 /*
241  * lookup mapping for the given fid in the cache, initialize a
242  * new one if not found. the initialization checks whether the
243  * object is local or remote. for local objects, OI is used to
244  * learn ino/generation. the function is used when the caller
245  * has no information about the object, e.g. at dt_insert().
246  */
247 static struct osd_idmap_cache *
248 osd_idc_find_or_init(const struct lu_env *env, struct osd_device *osd,
249                      const struct lu_fid *fid)
250 {
251         struct osd_idmap_cache *idc;
252         int rc;
253
254         idc = osd_idc_find(env, osd, fid);
255         LASSERT(!IS_ERR(idc));
256         if (idc != NULL)
257                 return idc;
258
259         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
260                osd->od_svname, PFID(fid));
261
262         /* new mapping is needed */
263         idc = osd_idc_add(env, osd, fid);
264         if (IS_ERR(idc)) {
265                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
266                        osd->od_svname, PFID(fid), PTR_ERR(idc));
267                 return idc;
268         }
269
270         /* initialize it */
271         rc = osd_remote_fid(env, osd, fid);
272         if (unlikely(rc < 0))
273                 return ERR_PTR(rc);
274
275         if (rc == 0) {
276                 /* the object is local, lookup in OI */
277                 /* XXX: probably cheaper to lookup in LU first? */
278                 rc = osd_oi_lookup(osd_oti_get(env), osd, fid,
279                                    &idc->oic_lid, 0);
280                 if (unlikely(rc < 0)) {
281                         CERROR("can't lookup: rc = %d\n", rc);
282                         return ERR_PTR(rc);
283                 }
284         } else {
285                 /* the object is remote */
286                 idc->oic_remote = 1;
287         }
288
289         return idc;
290 }
291
292 static void osd_idc_dump_lma(const struct lu_env *env,
293                                 struct osd_device *osd,
294                                 unsigned long ino,
295                                 bool check_in_oi)
296 {
297         struct osd_thread_info *info = osd_oti_get(env);
298         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
299         const struct lu_fid *fid;
300         struct osd_inode_id lid;
301         struct inode *inode;
302         int rc;
303
304         inode = osd_ldiskfs_iget(osd_sb(osd), ino);
305         if (IS_ERR(inode)) {
306                 CERROR("%s: can't get inode %lu: rc = %d\n",
307                        osd->od_svname, ino, (int)PTR_ERR(inode));
308                 return;
309         }
310         if (is_bad_inode(inode)) {
311                 CERROR("%s: bad inode %lu\n", osd->od_svname, ino);
312                 goto put;
313         }
314         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
315         if (rc) {
316                 CERROR("%s: can't get LMA for %lu: rc = %d\n",
317                        osd->od_svname, ino, rc);
318                 goto put;
319         }
320         fid = &loa->loa_lma.lma_self_fid;
321         LCONSOLE(D_INFO, "%s: "DFID" in inode %lu/%u\n", osd->od_svname,
322                       PFID(fid), ino, (unsigned)inode->i_generation);
323         if (!check_in_oi)
324                 goto put;
325         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
326         if (rc) {
327                 CERROR("%s: can't lookup "DFID": rc = %d\n",
328                        osd->od_svname, PFID(fid), rc);
329                 goto put;
330         }
331         LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n", osd->od_svname,
332                       PFID(fid), lid.oii_ino, lid.oii_gen);
333 put:
334         iput(inode);
335 }
336
337 static void osd_idc_dump_debug(const struct lu_env *env,
338                                 struct osd_device *osd,
339                                 const struct lu_fid *fid,
340                                 unsigned long ino1,
341                                 unsigned long ino2)
342 {
343         struct osd_inode_id lid;
344
345         int rc;
346
347         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
348         if (!rc) {
349                 LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n",
350                         osd->od_svname, PFID(fid), lid.oii_ino, lid.oii_gen);
351                 osd_idc_dump_lma(env, osd, lid.oii_ino, false);
352         } else {
353                 CERROR("%s: can't lookup "DFID": rc = %d\n",
354                        osd->od_svname, PFID(fid), rc);
355         }
356         if (ino1)
357                 osd_idc_dump_lma(env, osd, ino1, true);
358         if (ino2)
359                 osd_idc_dump_lma(env, osd, ino2, true);
360 }
361
362 /*
363  * lookup mapping for given FID and fill it from the given object.
364  * the object is lolcal by definition.
365  */
366 static int osd_idc_find_and_init(const struct lu_env *env,
367                                  struct osd_device *osd,
368                                  struct osd_object *obj)
369 {
370         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
371         struct osd_idmap_cache *idc;
372
373         idc = osd_idc_find(env, osd, fid);
374         LASSERT(!IS_ERR(idc));
375         if (idc != NULL) {
376                 if (obj->oo_inode == NULL)
377                         return 0;
378                 if (idc->oic_lid.oii_ino != obj->oo_inode->i_ino) {
379                         if (idc->oic_lid.oii_ino) {
380                                 osd_idc_dump_debug(env, osd, fid,
381                                                    idc->oic_lid.oii_ino,
382                                                    obj->oo_inode->i_ino);
383                                 return -EINVAL;
384                         }
385                         idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
386                         idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
387                 }
388                 return 0;
389         }
390
391         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
392                osd->od_svname, PFID(fid));
393
394         /* new mapping is needed */
395         idc = osd_idc_add(env, osd, fid);
396         if (IS_ERR(idc)) {
397                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
398                        osd->od_svname, PFID(fid), PTR_ERR(idc));
399                 return PTR_ERR(idc);
400         }
401
402         if (obj->oo_inode != NULL) {
403                 idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
404                 idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
405         }
406         return 0;
407 }
408
409 /*
410  * OSD object methods.
411  */
412
413 /*
414  * Concurrency: no concurrent access is possible that early in object
415  * life-cycle.
416  */
417 static struct lu_object *osd_object_alloc(const struct lu_env *env,
418                                           const struct lu_object_header *hdr,
419                                           struct lu_device *d)
420 {
421         struct osd_object *mo;
422
423         OBD_ALLOC_PTR(mo);
424         if (mo != NULL) {
425                 struct lu_object *l;
426                 struct lu_object_header *h;
427                 struct osd_device *o = osd_dev(d);
428
429                 l = &mo->oo_dt.do_lu;
430                 if (unlikely(o->od_in_init)) {
431                         OBD_ALLOC_PTR(h);
432                         if (!h) {
433                                 OBD_FREE_PTR(mo);
434                                 return NULL;
435                         }
436
437                         lu_object_header_init(h);
438                         lu_object_init(l, h, d);
439                         lu_object_add_top(h, l);
440                         mo->oo_header = h;
441                 } else {
442                         dt_object_init(&mo->oo_dt, NULL, d);
443                         mo->oo_header = NULL;
444                 }
445
446                 mo->oo_dt.do_ops = &osd_obj_ops;
447                 l->lo_ops = &osd_lu_obj_ops;
448                 init_rwsem(&mo->oo_sem);
449                 init_rwsem(&mo->oo_ext_idx_sem);
450                 spin_lock_init(&mo->oo_guard);
451                 INIT_LIST_HEAD(&mo->oo_xattr_list);
452                 return l;
453         }
454         return NULL;
455 }
456
457 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
458                 struct dentry *dentry, struct lustre_ost_attrs *loa)
459 {
460         int rc;
461
462         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
463                              (void *)loa, sizeof(*loa));
464         if (rc > 0) {
465                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
466
467                 if (rc < sizeof(*lma))
468                         return -EINVAL;
469
470                 rc = 0;
471                 lustre_loa_swab(loa, true);
472                 /* Check LMA compatibility */
473                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
474                         rc = -EOPNOTSUPP;
475                         CWARN("%s: unsupported incompat LMA feature(s) %#x for fid = "DFID", ino = %lu: rc = %d\n",
476                               osd_ino2name(inode),
477                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
478                               PFID(&lma->lma_self_fid), inode->i_ino, rc);
479                 }
480         } else if (rc == 0) {
481                 rc = -ENODATA;
482         }
483
484         return rc;
485 }
486
487 /*
488  * retrieve object from backend ext fs.
489  **/
490 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
491                        struct osd_inode_id *id)
492 {
493         int rc;
494         struct inode *inode = NULL;
495
496         /*
497          * if we look for an inode withing a running
498          * transaction, then we risk to deadlock
499          * osd_dirent_check_repair() breaks this
500          */
501          /* LASSERT(current->journal_info == NULL); */
502
503         inode = osd_ldiskfs_iget(osd_sb(dev), id->oii_ino);
504         if (IS_ERR(inode)) {
505                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
506                        id->oii_ino, PTR_ERR(inode));
507         } else if (id->oii_gen != OSD_OII_NOGEN &&
508                    inode->i_generation != id->oii_gen) {
509                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
510                        "i_generation = %u\n",
511                        id->oii_ino, id->oii_gen, inode->i_generation);
512                 iput(inode);
513                 inode = ERR_PTR(-ESTALE);
514         } else if (inode->i_nlink == 0) {
515                 /*
516                  * due to parallel readdir and unlink,
517                  * we can have dead inode here.
518                  */
519                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
520                 iput(inode);
521                 inode = ERR_PTR(-ESTALE);
522         } else if (is_bad_inode(inode)) {
523                 CWARN("%s: bad inode: ino = %u: rc = %d\n",
524                       osd_dev2name(dev), id->oii_ino, -ENOENT);
525                 iput(inode);
526                 inode = ERR_PTR(-ENOENT);
527         } else  if (osd_is_ea_inode(inode)) {
528                 /*
529                  * EA inode is internal ldiskfs object, should don't visible
530                  * on osd
531                  */
532                 CDEBUG(D_INODE, "EA inode: ino = %u\n", id->oii_ino);
533                 iput(inode);
534                 inode = ERR_PTR(-ENOENT);
535         } else if ((rc = osd_attach_jinode(inode))) {
536                 iput(inode);
537                 inode = ERR_PTR(rc);
538         } else {
539                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
540                 if (id->oii_gen == OSD_OII_NOGEN)
541                         osd_id_gen(id, inode->i_ino, inode->i_generation);
542
543                 /*
544                  * Do not update file c/mtime in ldiskfs.
545                  * NB: we don't have any lock to protect this because we don't
546                  * have reference on osd_object now, but contention with
547                  * another lookup + attr_set can't happen in the tiny window
548                  * between if (...) and set S_NOCMTIME.
549                  */
550                 if (!(inode->i_flags & S_NOCMTIME))
551                         inode->i_flags |= S_NOCMTIME;
552         }
553         return inode;
554 }
555
556 int osd_ldiskfs_add_entry(struct osd_thread_info *info, struct osd_device *osd,
557                           handle_t *handle, struct dentry *child,
558                           struct inode *inode, struct htree_lock *hlock)
559 {
560         int rc, rc2;
561
562         rc = __ldiskfs_add_entry(handle, child, inode, hlock);
563         if (rc == -ENOBUFS || rc == -ENOSPC) {
564                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
565                 struct inode *parent = child->d_parent->d_inode;
566                 struct lu_fid *fid = NULL;
567                 char fidstr[FID_LEN + 1] = "unknown";
568
569                 rc2 = osd_get_lma(info, parent, child->d_parent, loa);
570                 if (!rc2) {
571                         fid = &loa->loa_lma.lma_self_fid;
572                 } else if (rc2 == -ENODATA) {
573                         if (unlikely(is_root_inode(parent))) {
574                                 fid = &info->oti_fid3;
575                                 lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
576                         } else if (!osd->od_is_ost && osd->od_index == 0) {
577                                 fid = &info->oti_fid3;
578                                 lu_igif_build(fid, parent->i_ino,
579                                               parent->i_generation);
580                         }
581                 }
582
583                 if (fid != NULL)
584                         snprintf(fidstr, sizeof(fidstr), DFID, PFID(fid));
585
586                 /* below message is checked in sanity.sh test_129 */
587                 if (rc == -ENOSPC) {
588                         CWARN("%s: directory (inode: %lu, FID: %s) has reached max size limit\n",
589                               osd_name(osd), parent->i_ino, fidstr);
590                 } else {
591                         rc = 0; /* ignore such error now */
592                         CWARN("%s: directory (inode: %lu, FID: %s) is approaching max size limit\n",
593                               osd_name(osd), parent->i_ino, fidstr);
594                 }
595
596         }
597
598         return rc;
599 }
600
601
602 struct inode *
603 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
604              struct osd_inode_id *id, struct lu_fid *fid)
605 {
606         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
607         struct inode *inode;
608         int rc;
609
610         inode = osd_iget(info, dev, id);
611         if (IS_ERR(inode))
612                 return inode;
613
614         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
615         if (!rc) {
616                 *fid = loa->loa_lma.lma_self_fid;
617         } else if (rc == -ENODATA) {
618                 if (unlikely(is_root_inode(inode)))
619                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
620                 else
621                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
622         } else {
623                 iput(inode);
624                 inode = ERR_PTR(rc);
625         }
626         return inode;
627 }
628
629 static struct inode *osd_iget_check(struct osd_thread_info *info,
630                                     struct osd_device *dev,
631                                     const struct lu_fid *fid,
632                                     struct osd_inode_id *id,
633                                     bool trusted)
634 {
635         struct inode *inode;
636         int rc = 0;
637
638         ENTRY;
639
640         /*
641          * The cached OI mapping is trustable. If we cannot locate the inode
642          * via the cached OI mapping, then return the failure to the caller
643          * directly without further OI checking.
644          */
645
646 again:
647         inode = osd_iget(info, dev, id);
648         if (IS_ERR(inode)) {
649                 rc = PTR_ERR(inode);
650                 if (!trusted && (rc == -ENOENT || rc == -ESTALE))
651                         goto check_oi;
652
653                 CDEBUG(D_INODE, "no inode for FID: "DFID", ino = %u, rc = %d\n",
654                        PFID(fid), id->oii_ino, rc);
655                 GOTO(put, rc);
656         }
657
658 check_oi:
659         if (rc != 0) {
660                 __u32 saved_ino = id->oii_ino;
661                 __u32 saved_gen = id->oii_gen;
662
663                 LASSERT(!trusted);
664                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
665
666                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
667                 /*
668                  * XXX: There are four possible cases:
669                  *      1. rc = 0.
670                  *         Backup/restore caused the OI invalid.
671                  *      2. rc = 0.
672                  *         Someone unlinked the object but NOT removed
673                  *         the OI mapping, such as mount target device
674                  *         as ldiskfs, and modify something directly.
675                  *      3. rc = -ENOENT.
676                  *         Someone just removed the object between the
677                  *         former oi_lookup and the iget. It is normal.
678                  *      4. Other failure cases.
679                  *
680                  *      Generally, when the device is mounted, it will
681                  *      auto check whether the system is restored from
682                  *      file-level backup or not. We trust such detect
683                  *      to distinguish the 1st case from the 2nd case:
684                  *      if the OI files are consistent but may contain
685                  *      stale OI mappings because of case 2, if iget()
686                  *      returns -ENOENT or -ESTALE, then it should be
687                  *      the case 2.
688                  */
689                 if (rc != 0)
690                         /*
691                          * If the OI mapping was in OI file before the
692                          * osd_iget_check(), but now, it is disappear,
693                          * then it must be removed by race. That is a
694                          * normal race case.
695                          */
696                         GOTO(put, rc);
697
698                 /*
699                  * It is the OI scrub updated the OI mapping by race.
700                  * The new OI mapping must be valid.
701                  */
702                 if (saved_ino != id->oii_ino ||
703                     (saved_gen != id->oii_gen && saved_gen != OSD_OII_NOGEN)) {
704                         if (!IS_ERR(inode))
705                                 iput(inode);
706
707                         trusted = true;
708                         goto again;
709                 }
710
711                 if (IS_ERR(inode)) {
712                         if (dev->od_scrub.os_scrub.os_file.sf_flags &
713                             SF_INCONSISTENT)
714                                 /*
715                                  * It still can be the case 2, but we cannot
716                                  * distinguish it from the case 1. So return
717                                  * -EREMCHG to block current operation until
718                                  *  OI scrub rebuilt the OI mappings.
719                                  */
720                                 rc = -EREMCHG;
721                         else
722                                 rc = -ENOENT;
723
724                         GOTO(put, rc);
725                 }
726
727                 if (inode->i_generation == id->oii_gen)
728                         rc = -ENOENT;
729                 else
730                         rc = -EREMCHG;
731         }
732
733         GOTO(put, rc);
734
735 put:
736         if (rc != 0) {
737                 if (!IS_ERR(inode))
738                         iput(inode);
739
740                 inode = ERR_PTR(rc);
741         }
742
743         return inode;
744 }
745
746 /**
747  * \retval +v: new filter_fid does not contain self-fid
748  * \retval 0:  filter_fid_18_23, contains self-fid
749  * \retval -v: other failure cases
750  */
751 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
752                  struct dentry *dentry, struct lu_fid *fid)
753 {
754         struct filter_fid *ff = &info->oti_ff;
755         struct ost_id *ostid = &info->oti_ostid;
756         int rc;
757
758         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
759         if (rc == sizeof(struct filter_fid_18_23)) {
760                 struct filter_fid_18_23 *ff_old = (void *)ff;
761
762                 ostid_set_seq(ostid, le64_to_cpu(ff_old->ff_seq));
763                 rc = ostid_set_id(ostid, le64_to_cpu(ff_old->ff_objid));
764                 /*
765                  * XXX: use 0 as the index for compatibility, the caller will
766                  * handle index related issues when necessary.
767                  */
768                 if (!rc)
769                         ostid_to_fid(fid, ostid, 0);
770         } else if (rc >= (int)sizeof(struct filter_fid_24_29)) {
771                 rc = 1;
772         } else if (rc >= 0) {
773                 rc = -EINVAL;
774         }
775
776         return rc;
777 }
778
779 static int osd_lma_self_repair(struct osd_thread_info *info,
780                                struct osd_device *osd, struct inode *inode,
781                                const struct lu_fid *fid, __u32 compat)
782 {
783         handle_t *jh;
784         int rc;
785
786         LASSERT(current->journal_info == NULL);
787
788         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
789                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
790         if (IS_ERR(jh)) {
791                 rc = PTR_ERR(jh);
792                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
793                       osd_name(osd), rc);
794                 return rc;
795         }
796
797         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
798         if (rc != 0)
799                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
800                       osd_name(osd), rc);
801         ldiskfs_journal_stop(jh);
802         return rc;
803 }
804
805 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
806 {
807         struct osd_thread_info *info = osd_oti_get(env);
808         struct osd_device *osd = osd_obj2dev(obj);
809         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
810         struct lustre_mdt_attrs *lma = &loa->loa_lma;
811         struct inode *inode = obj->oo_inode;
812         struct dentry *dentry = &info->oti_obj_dentry;
813         struct lu_fid *fid = NULL;
814         const struct lu_fid *rfid = lu_object_fid(&obj->oo_dt.do_lu);
815         int rc;
816
817         ENTRY;
818
819         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
820                              (void *)loa, sizeof(*loa));
821         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
822                 fid = &lma->lma_self_fid;
823                 rc = osd_get_idif(info, inode, dentry, fid);
824                 if (rc > 0 || (rc == -ENODATA && osd->od_index_in_idif)) {
825                         /*
826                          * For the given OST-object, if it has neither LMA nor
827                          * FID in XATTR_NAME_FID, then the given FID (which is
828                          * contained in the @obj, from client RPC for locating
829                          * the OST-object) is trusted. We use it to generate
830                          * the LMA.
831                          */
832                         osd_lma_self_repair(info, osd, inode, rfid,
833                                             LMAC_FID_ON_OST);
834                         RETURN(0);
835                 }
836         }
837
838         if (rc < 0)
839                 RETURN(rc);
840
841         if (rc > 0) {
842                 rc = 0;
843                 lustre_lma_swab(lma);
844                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
845                              (CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT) &&
846                               S_ISREG(inode->i_mode)))) {
847                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
848                               "fid = "DFID", ino = %lu\n", osd_name(osd),
849                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
850                               PFID(rfid), inode->i_ino);
851                         rc = -EOPNOTSUPP;
852                 } else {
853                         fid = &lma->lma_self_fid;
854                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
855                             osd->od_is_ost)
856                                 obj->oo_pfid_in_lma = 1;
857                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
858                             !osd->od_is_ost)
859                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
860                 }
861         }
862
863         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
864                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
865                         struct ost_id   *oi   = &info->oti_ostid;
866                         struct lu_fid   *fid1 = &info->oti_fid3;
867                         __u32            idx  = fid_idif_ost_idx(rfid);
868
869                         /*
870                          * For old IDIF, the OST index is not part of the IDIF,
871                          * Means that different OSTs may have the same IDIFs.
872                          * Under such case, we need to make some compatible
873                          * check to make sure to trigger OI scrub properly.
874                          */
875                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
876                                 /* Given @rfid is new, LMA is old. */
877                                 fid_to_ostid(fid, oi);
878                                 ostid_to_fid(fid1, oi, idx);
879                                 if (lu_fid_eq(fid1, rfid)) {
880                                         if (osd->od_index_in_idif)
881                                                 osd_lma_self_repair(info, osd,
882                                                         inode, rfid,
883                                                         LMAC_FID_ON_OST);
884                                         RETURN(0);
885                                 }
886                         }
887                 }
888
889                 rc = -EREMCHG;
890         }
891
892         RETURN(rc);
893 }
894
895 struct osd_check_lmv_buf {
896         /* please keep it as first member */
897         struct dir_context ctx;
898         struct osd_thread_info *oclb_info;
899         struct osd_device *oclb_dev;
900         int oclb_items;
901         bool oclb_found;
902 };
903
904 /**
905  * It is called internally by ->iterate*() to filter out the
906  * local slave object's FID of the striped directory.
907  *
908  * \retval      1 found the local slave's FID
909  * \retval      0 continue to check next item
910  * \retval      -ve for failure
911  */
912 #ifdef HAVE_FILLDIR_USE_CTX
913 static int osd_stripe_dir_filldir(struct dir_context *buf,
914 #else
915 static int osd_stripe_dir_filldir(void *buf,
916 #endif
917                                   const char *name, int namelen,
918                                   loff_t offset, __u64 ino, unsigned int d_type)
919 {
920         struct osd_check_lmv_buf *oclb = (struct osd_check_lmv_buf *)buf;
921         struct osd_thread_info *oti = oclb->oclb_info;
922         struct lu_fid *fid = &oti->oti_fid3;
923         struct osd_inode_id *id = &oti->oti_id3;
924         struct osd_device *dev = oclb->oclb_dev;
925         struct inode *inode;
926
927         oclb->oclb_items++;
928
929         if (name[0] == '.')
930                 return 0;
931
932         fid_zero(fid);
933         sscanf(name + 1, SFID, RFID(fid));
934         if (!fid_is_sane(fid))
935                 return 0;
936
937         if (osd_remote_fid(oti->oti_env, dev, fid))
938                 return 0;
939
940         osd_id_gen(id, ino, OSD_OII_NOGEN);
941         inode = osd_iget(oti, dev, id);
942         if (IS_ERR(inode))
943                 return PTR_ERR(inode);
944
945         iput(inode);
946         osd_add_oi_cache(oti, dev, id, fid);
947         osd_scrub_oi_insert(dev, fid, id, true);
948         oclb->oclb_found = true;
949
950         return 1;
951 }
952
953 /*
954  * When lookup item under striped directory, we need to locate the master
955  * MDT-object of the striped directory firstly, then the client will send
956  * lookup (getattr_by_name) RPC to the MDT with some slave MDT-object's FID
957  * and the item's name. If the system is restored from MDT file level backup,
958  * then before the OI scrub completely built the OI files, the OI mappings of
959  * the master MDT-object and slave MDT-object may be invalid. Usually, it is
960  * not a problem for the master MDT-object. Because when locate the master
961  * MDT-object, we will do name based lookup (for the striped directory itself)
962  * firstly, during such process we can setup the correct OI mapping for the
963  * master MDT-object. But it will be trouble for the slave MDT-object. Because
964  * the client will not trigger name based lookup on the MDT to locate the slave
965  * MDT-object before locating item under the striped directory, then when
966  * osd_fid_lookup(), it will find that the OI mapping for the slave MDT-object
967  * is invalid and does not know what the right OI mapping is, then the MDT has
968  * to return -EINPROGRESS to the client to notify that the OI scrub is rebuiding
969  * the OI file, related OI mapping is unknown yet, please try again later. And
970  * then client will re-try the RPC again and again until related OI mapping has
971  * been updated. That is quite inefficient.
972  *
973  * To resolve above trouble, we will handle it as the following two cases:
974  *
975  * 1) The slave MDT-object and the master MDT-object are on different MDTs.
976  *    It is relative easy. Be as one of remote MDT-objects, the slave MDT-object
977  *    is linked under /REMOTE_PARENT_DIR with the name of its FID string.
978  *    We can locate the slave MDT-object via lookup the /REMOTE_PARENT_DIR
979  *    directly. Please check osd_fid_lookup().
980  *
981  * 2) The slave MDT-object and the master MDT-object reside on the same MDT.
982  *    Under such case, during lookup the master MDT-object, we will lookup the
983  *    slave MDT-object via readdir against the master MDT-object, because the
984  *    slave MDT-objects information are stored as sub-directories with the name
985  *    "${FID}:${index}". Then when find the local slave MDT-object, its OI
986  *    mapping will be recorded. Then subsequent osd_fid_lookup() will know
987  *    the correct OI mapping for the slave MDT-object.
988  */
989 static int osd_check_lmv(struct osd_thread_info *oti, struct osd_device *dev,
990                          struct inode *inode)
991 {
992         struct lu_buf *buf = &oti->oti_big_buf;
993         struct file *filp;
994         struct lmv_mds_md_v1 *lmv1;
995         struct osd_check_lmv_buf oclb = {
996                 .ctx.actor = osd_stripe_dir_filldir,
997                 .oclb_info = oti,
998                 .oclb_dev = dev,
999                 .oclb_found = false,
1000         };
1001         int rc = 0;
1002
1003         ENTRY;
1004         /* We should use the VFS layer to create a real dentry. */
1005         oti->oti_obj_dentry.d_inode = inode;
1006         oti->oti_obj_dentry.d_sb = inode->i_sb;
1007
1008         filp = alloc_file_pseudo(inode, dev->od_mnt, "/", O_NOATIME,
1009                                  inode->i_fop);
1010         if (IS_ERR(filp))
1011                 RETURN(-ENOMEM);
1012
1013         filp->f_mode |= FMODE_64BITHASH;
1014         filp->f_pos = 0;
1015         ihold(inode);
1016 again:
1017         rc = __osd_xattr_get(inode, filp->f_path.dentry, XATTR_NAME_LMV,
1018                              buf->lb_buf, buf->lb_len);
1019         if (rc == -ERANGE) {
1020                 rc = __osd_xattr_get(inode, filp->f_path.dentry,
1021                                      XATTR_NAME_LMV, NULL, 0);
1022                 if (rc > 0) {
1023                         lu_buf_realloc(buf, rc);
1024                         if (buf->lb_buf == NULL)
1025                                 GOTO(out, rc = -ENOMEM);
1026
1027                         goto again;
1028                 }
1029         }
1030
1031         if (unlikely(rc == 0 || rc == -ENODATA))
1032                 GOTO(out, rc = 0);
1033
1034         if (rc < 0)
1035                 GOTO(out, rc);
1036
1037         if (unlikely(buf->lb_buf == NULL)) {
1038                 lu_buf_realloc(buf, rc);
1039                 if (buf->lb_buf == NULL)
1040                         GOTO(out, rc = -ENOMEM);
1041
1042                 goto again;
1043         }
1044
1045         lmv1 = buf->lb_buf;
1046         if (le32_to_cpu(lmv1->lmv_magic) != LMV_MAGIC_V1)
1047                 GOTO(out, rc = 0);
1048
1049         do {
1050                 oclb.oclb_items = 0;
1051                 rc = iterate_dir(filp, &oclb.ctx);
1052         } while (rc >= 0 && oclb.oclb_items > 0 && !oclb.oclb_found &&
1053                  filp->f_pos != LDISKFS_HTREE_EOF_64BIT);
1054 out:
1055         fput(filp);
1056         if (rc < 0)
1057                 CDEBUG(D_LFSCK,
1058                        "%s: cannot check LMV, ino = %lu/%u: rc = %d\n",
1059                        osd_ino2name(inode), inode->i_ino, inode->i_generation,
1060                        rc);
1061         else
1062                 rc = 0;
1063
1064         RETURN(rc);
1065 }
1066
1067 /**
1068  * Is object in scrub inconsistent/stale list.
1069  *
1070  * \a scrub has two lists, os_inconsistent_items contains mappings to fix, while
1071  * os_stale_items contains mappings failed to fix.
1072  */
1073 static bool fid_in_scrub_list(struct lustre_scrub *scrub,
1074                               const struct list_head *list,
1075                               const struct lu_fid *fid)
1076 {
1077         struct osd_inconsistent_item *oii;
1078
1079         if (list_empty(list))
1080                 return false;
1081
1082         spin_lock(&scrub->os_lock);
1083         list_for_each_entry(oii, list, oii_list) {
1084                 if (lu_fid_eq(fid, &oii->oii_cache.oic_fid)) {
1085                         spin_unlock(&scrub->os_lock);
1086                         return true;
1087                 }
1088         }
1089         spin_unlock(&scrub->os_lock);
1090
1091         return false;
1092 }
1093
1094 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
1095                           const struct lu_fid *fid,
1096                           const struct lu_object_conf *conf)
1097 {
1098         struct osd_thread_info *info;
1099         struct lu_device *ldev = obj->oo_dt.do_lu.lo_dev;
1100         struct osd_device *dev;
1101         struct osd_idmap_cache *oic;
1102         struct osd_inode_id *id;
1103         struct inode *inode = NULL;
1104         struct lustre_scrub *scrub;
1105         struct scrub_file *sf;
1106         __u32 flags = SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT | SS_AUTO_FULL;
1107         __u32 saved_ino;
1108         __u32 saved_gen;
1109         int result = 0;
1110         int rc1 = 0;
1111         bool remote = false;
1112         bool trusted = true;
1113         bool updated = false;
1114         bool checked = false;
1115         bool stale = false;
1116
1117         ENTRY;
1118
1119         LINVRNT(osd_invariant(obj));
1120         LASSERT(obj->oo_inode == NULL);
1121
1122         if (fid_is_sane(fid) == 0) {
1123                 CERROR("%s: invalid FID "DFID"\n", ldev->ld_obd->obd_name,
1124                        PFID(fid));
1125                 dump_stack();
1126                 RETURN(-EINVAL);
1127         }
1128
1129         dev = osd_dev(ldev);
1130         scrub = &dev->od_scrub.os_scrub;
1131         sf = &scrub->os_file;
1132         info = osd_oti_get(env);
1133         LASSERT(info);
1134         oic = &info->oti_cache;
1135
1136         if (OBD_FAIL_CHECK(OBD_FAIL_SRV_ENOENT))
1137                 RETURN(-ENOENT);
1138
1139         /*
1140          * For the object is created as locking anchor, or for the object to
1141          * be created on disk. No need to osd_oi_lookup() at here because FID
1142          * shouldn't never be re-used, if it's really a duplicate FID from
1143          * unexpected reason, we should be able to detect it later by calling
1144          * do_create->osd_oi_insert().
1145          */
1146         if (conf && conf->loc_flags & LOC_F_NEW)
1147                 RETURN(0);
1148
1149         /* Search order: 1. per-thread cache. */
1150         if (lu_fid_eq(fid, &oic->oic_fid) && likely(oic->oic_dev == dev)) {
1151                 id = &oic->oic_lid;
1152                 goto iget;
1153         }
1154
1155         /* Search order: 2. OI scrub pending list. */
1156         id = &info->oti_id;
1157         memset(id, 0, sizeof(struct osd_inode_id));
1158         if (fid_in_scrub_list(scrub, &scrub->os_inconsistent_items, fid) &&
1159             scrub->os_running)
1160                 RETURN(-EINPROGRESS);
1161
1162         stale = fid_in_scrub_list(scrub, &scrub->os_stale_items, fid);
1163         if (stale && OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_STALE))
1164                 RETURN(-ESTALE);
1165
1166         /*
1167          * The OI mapping in the OI file can be updated by the OI scrub
1168          * when we locate the inode via FID. So it may be not trustable.
1169          */
1170         trusted = false;
1171
1172         /* Search order: 3. OI files. */
1173         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1174         if (result == -ENOENT) {
1175                 if (!fid_is_norm(fid) ||
1176                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
1177                     !ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
1178                                       sf->sf_oi_bitmap))
1179                         GOTO(out, result = 0);
1180
1181                 goto trigger;
1182         }
1183
1184         /* -ESTALE is returned if inode of OST object doesn't exist */
1185         if (result == -ESTALE &&
1186             fid_is_on_ost(info, dev, fid, OI_CHECK_FLD)) {
1187                 GOTO(out, result = 0);
1188         }
1189
1190         if (result)
1191                 GOTO(out, result);
1192
1193 iget:
1194         obj->oo_inode = NULL;
1195         /* for later passes through checks, not true on first pass */
1196         if (!IS_ERR_OR_NULL(inode))
1197                 iput(inode);
1198
1199         inode = osd_iget_check(info, dev, fid, id, trusted);
1200         if (!IS_ERR(inode)) {
1201                 obj->oo_inode = inode;
1202                 result = 0;
1203                 if (remote)
1204                         goto trigger;
1205
1206                 goto check_lma;
1207         }
1208
1209         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_STALE))
1210                 goto trigger;
1211
1212         result = PTR_ERR(inode);
1213         if (result == -ENOENT || result == -ESTALE)
1214                 GOTO(out, result = 0);
1215
1216         if (result != -EREMCHG)
1217                 GOTO(out, result);
1218
1219 trigger:
1220         /* don't trigger repeatedly for stale mapping */
1221         if (stale)
1222                 GOTO(out, result = -ESTALE);
1223
1224         /*
1225          * We still have chance to get the valid inode: for the
1226          * object which is referenced by remote name entry, the
1227          * object on the local MDT will be linked under the dir
1228          * of "/REMOTE_PARENT_DIR" with its FID string as name.
1229          *
1230          * We do not know whether the object for the given FID
1231          * is referenced by some remote name entry or not, and
1232          * especially for DNE II, a multiple-linked object may
1233          * have many name entries reside on many MDTs.
1234          *
1235          * To simplify the operation, OSD will not distinguish
1236          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
1237          * only happened for the RPC from other MDT during the
1238          * OI scrub, or for the client side RPC with FID only,
1239          * such as FID to path, or from old connected client.
1240          */
1241         if (!remote) {
1242                 rc1 = osd_lookup_in_remote_parent(info, dev, fid, id);
1243                 if (!rc1) {
1244                         remote = true;
1245                         trusted = true;
1246                         flags |= SS_AUTO_PARTIAL;
1247                         flags &= ~SS_AUTO_FULL;
1248                         goto iget;
1249                 }
1250         }
1251
1252         if (scrub->os_running) {
1253                 if (scrub->os_partial_scan && !scrub->os_in_join)
1254                         goto join;
1255
1256                 if (IS_ERR_OR_NULL(inode) || result) {
1257                         osd_scrub_oi_insert(dev, fid, id, result == -ENOENT);
1258                         GOTO(out, result = -EINPROGRESS);
1259                 }
1260
1261                 LASSERT(remote);
1262                 LASSERT(obj->oo_inode == inode);
1263
1264                 osd_scrub_oi_insert(dev, fid, id, true);
1265                 goto found;
1266         }
1267
1268         if (dev->od_scrub.os_scrub.os_auto_scrub_interval == AS_NEVER) {
1269                 if (!remote)
1270                         GOTO(out, result = -EREMCHG);
1271
1272                 LASSERT(!result);
1273                 LASSERT(obj->oo_inode == inode);
1274
1275                 osd_add_oi_cache(info, dev, id, fid);
1276                 goto found;
1277         }
1278
1279 join:
1280         if (IS_ERR_OR_NULL(inode) || result)
1281                 osd_scrub_oi_insert(dev, fid, id, result == -ENOENT);
1282
1283         rc1 = osd_scrub_start(env, dev, flags);
1284         CDEBUG_LIMIT(D_LFSCK | D_CONSOLE | D_WARNING,
1285                      "%s: trigger OI scrub by RPC for "DFID"/%u with flags %#x: rc = %d\n",
1286                      osd_name(dev), PFID(fid), id->oii_ino, flags, rc1);
1287         if (rc1 && rc1 != -EALREADY)
1288                 GOTO(out, result = -EREMCHG);
1289
1290         if (IS_ERR_OR_NULL(inode) || result)
1291                 GOTO(out, result = -EINPROGRESS);
1292
1293         LASSERT(remote);
1294         LASSERT(obj->oo_inode == inode);
1295         goto found;
1296
1297 check_lma:
1298         checked = true;
1299         if (unlikely(obj->oo_header))
1300                 goto found;
1301
1302         result = osd_check_lma(env, obj);
1303         if (!result)
1304                 goto found;
1305
1306         LASSERTF(id->oii_ino == inode->i_ino &&
1307                  id->oii_gen == inode->i_generation,
1308                  "locate wrong inode for FID: "DFID", %u/%u => %ld/%u\n",
1309                  PFID(fid), id->oii_ino, id->oii_gen,
1310                  inode->i_ino, inode->i_generation);
1311
1312         saved_ino = inode->i_ino;
1313         saved_gen = inode->i_generation;
1314
1315         if (unlikely(result == -ENODATA)) {
1316                 /*
1317                  * If the OI scrub updated the OI mapping by race, it
1318                  * must be valid. Trust the inode that has no LMA EA.
1319                  */
1320                 if (updated)
1321                         goto found;
1322
1323                 result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1324                 if (!result) {
1325                         /*
1326                          * The OI mapping is still there, the inode is still
1327                          * valid. It is just becaues the inode has no LMA EA.
1328                          */
1329                         if (saved_ino == id->oii_ino &&
1330                             saved_gen == id->oii_gen)
1331                                 goto found;
1332
1333                         /*
1334                          * It is the OI scrub updated the OI mapping by race.
1335                          * The new OI mapping must be valid.
1336                          */
1337                         trusted = true;
1338                         updated = true;
1339                         goto iget;
1340                 }
1341
1342                 /*
1343                  * "result == -ENOENT" means that the OI mappinghas been
1344                  * removed by race, so the inode belongs to other object.
1345                  *
1346                  * Others error can be returned  directly.
1347                  */
1348                 if (result == -ENOENT) {
1349                         LASSERT(trusted);
1350
1351                         obj->oo_inode = NULL;
1352                         result = 0;
1353                 }
1354         }
1355
1356         if (result != -EREMCHG)
1357                 GOTO(out, result);
1358
1359         LASSERT(!updated);
1360
1361         /*
1362          * if two OST objects map to the same inode, and inode mode is
1363          * (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666), which means it's
1364          * reserved by precreate, and not written yet, in this case, don't
1365          * set inode for the object whose FID mismatch, so that it can create
1366          * inode and not block precreate.
1367          */
1368         if (fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) &&
1369             inode->i_mode == (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666)) {
1370                 obj->oo_inode = NULL;
1371                 GOTO(out, result = 0);
1372         }
1373
1374         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1375         /*
1376          * "result == -ENOENT" means the cached OI mapping has been removed
1377          * from the OI file by race, above inode belongs to other object.
1378          */
1379         if (result == -ENOENT) {
1380                 LASSERT(trusted);
1381
1382                 obj->oo_inode = NULL;
1383                 GOTO(out, result = 0);
1384         }
1385
1386         if (result)
1387                 GOTO(out, result);
1388
1389         if (saved_ino == id->oii_ino && saved_gen == id->oii_gen) {
1390                 result = -EREMCHG;
1391                 osd_scrub_refresh_mapping(info, dev, fid, id, DTO_INDEX_DELETE,
1392                                           true, 0, NULL);
1393                 goto trigger;
1394         }
1395
1396         /*
1397          * It is the OI scrub updated the OI mapping by race.
1398          * The new OI mapping must be valid.
1399          */
1400         trusted = true;
1401         updated = true;
1402         goto iget;
1403
1404 found:
1405         if (!checked) {
1406                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
1407                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
1408
1409                 result = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
1410                 if (!result) {
1411                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
1412                             dev->od_is_ost)
1413                                 obj->oo_pfid_in_lma = 1;
1414                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
1415                             !dev->od_is_ost)
1416                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
1417                 } else if (result != -ENODATA) {
1418                         GOTO(out, result);
1419                 }
1420         }
1421
1422         obj->oo_compat_dot_created = 1;
1423         obj->oo_compat_dotdot_created = 1;
1424
1425         if (S_ISDIR(inode->i_mode) &&
1426             (flags & SS_AUTO_PARTIAL || sf->sf_status == SS_SCANNING))
1427                 osd_check_lmv(info, dev, inode);
1428
1429         result = osd_attach_jinode(inode);
1430         if (result)
1431                 GOTO(out, result);
1432
1433         if (!ldiskfs_pdo)
1434                 GOTO(out, result = 0);
1435
1436         LASSERT(!obj->oo_hl_head);
1437         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1438
1439         GOTO(out, result = (!obj->oo_hl_head ? -ENOMEM : 0));
1440
1441 out:
1442         if (!result && stale)
1443                 osd_scrub_oi_resurrect(scrub, fid);
1444
1445         if (result || !obj->oo_inode) {
1446                 if (!IS_ERR_OR_NULL(inode))
1447                         iput(inode);
1448
1449                 obj->oo_inode = NULL;
1450                 if (trusted)
1451                         fid_zero(&oic->oic_fid);
1452         }
1453
1454         LINVRNT(osd_invariant(obj));
1455         return result;
1456 }
1457
1458 /*
1459  * Concurrency: shouldn't matter.
1460  */
1461 static void osd_object_init0(struct osd_object *obj)
1462 {
1463         LASSERT(obj->oo_inode != NULL);
1464         obj->oo_dt.do_body_ops = &osd_body_ops;
1465         obj->oo_dt.do_lu.lo_header->loh_attr |=
1466                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
1467 }
1468
1469 /*
1470  * Concurrency: no concurrent access is possible that early in object
1471  * life-cycle.
1472  */
1473 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
1474                            const struct lu_object_conf *conf)
1475 {
1476         struct osd_object *obj = osd_obj(l);
1477         int result;
1478
1479         LINVRNT(osd_invariant(obj));
1480
1481         if (OBD_FAIL_PRECHECK(OBD_FAIL_MDS_LLOG_UMOUNT_RACE) &&
1482             cfs_fail_val == 2) {
1483                 struct osd_thread_info *info = osd_oti_get(env);
1484                 struct osd_idmap_cache *oic = &info->oti_cache;
1485                 /* invalidate thread cache */
1486                 memset(&oic->oic_fid, 0, sizeof(oic->oic_fid));
1487         }
1488         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
1489                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
1490                 l->lo_header->loh_attr |= LOHA_EXISTS;
1491                 return 0;
1492         }
1493
1494         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
1495         obj->oo_dt.do_body_ops = &osd_body_ops_new;
1496         if (result == 0 && obj->oo_inode != NULL) {
1497                 struct osd_thread_info *oti = osd_oti_get(env);
1498                 struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
1499
1500                 osd_object_init0(obj);
1501                 if (unlikely(obj->oo_header))
1502                         return 0;
1503
1504                 result = osd_get_lma(oti, obj->oo_inode,
1505                                      &oti->oti_obj_dentry, loa);
1506                 if (!result) {
1507                         /*
1508                          * Convert LMAI flags to lustre LMA flags
1509                          * and cache it to oo_lma_flags
1510                          */
1511                         obj->oo_lma_flags =
1512                                 lma_to_lustre_flags(loa->loa_lma.lma_incompat);
1513                 } else if (result == -ENODATA) {
1514                         result = 0;
1515                 }
1516         }
1517         obj->oo_dirent_count = LU_DIRENT_COUNT_UNSET;
1518
1519         LINVRNT(osd_invariant(obj));
1520         return result;
1521 }
1522
1523 /*
1524  * The first part of oxe_buf is xattr name, and is '\0' terminated.
1525  * The left part is for value, binary mode.
1526  */
1527 struct osd_xattr_entry {
1528         struct list_head        oxe_list;
1529         size_t                  oxe_len;
1530         size_t                  oxe_namelen;
1531         bool                    oxe_exist;
1532         struct rcu_head         oxe_rcu;
1533         char                    oxe_buf[0];
1534 };
1535
1536 static int osd_oxc_get(struct osd_object *obj, const char *name,
1537                        struct lu_buf *buf)
1538 {
1539         struct osd_xattr_entry *tmp;
1540         struct osd_xattr_entry *oxe = NULL;
1541         size_t namelen = strlen(name);
1542         int rc;
1543
1544         rcu_read_lock();
1545         list_for_each_entry_rcu(tmp, &obj->oo_xattr_list, oxe_list) {
1546                 if (namelen == tmp->oxe_namelen &&
1547                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1548                         oxe = tmp;
1549                         break;
1550                 }
1551         }
1552
1553         if (oxe == NULL)
1554                 GOTO(out, rc = -ENOENT);
1555
1556         if (!oxe->oxe_exist)
1557                 GOTO(out, rc = -ENODATA);
1558
1559         /* vallen */
1560         rc = oxe->oxe_len - sizeof(*oxe) - oxe->oxe_namelen - 1;
1561         LASSERT(rc > 0);
1562
1563         if (buf->lb_buf == NULL)
1564                 GOTO(out, rc);
1565
1566         if (buf->lb_len < rc)
1567                 GOTO(out, rc = -ERANGE);
1568
1569         memcpy(buf->lb_buf, &oxe->oxe_buf[namelen + 1], rc);
1570 out:
1571         rcu_read_unlock();
1572
1573         return rc;
1574 }
1575
1576 static void osd_oxc_free(struct rcu_head *head)
1577 {
1578         struct osd_xattr_entry *oxe;
1579
1580         oxe = container_of(head, struct osd_xattr_entry, oxe_rcu);
1581         OBD_FREE(oxe, oxe->oxe_len);
1582 }
1583
1584 static void osd_oxc_add(struct osd_object *obj, const char *name,
1585                         const char *buf, int buflen)
1586 {
1587         struct osd_xattr_entry *oxe;
1588         struct osd_xattr_entry *old = NULL;
1589         struct osd_xattr_entry *tmp;
1590         size_t namelen = strlen(name);
1591         size_t len = sizeof(*oxe) + namelen + 1 + buflen;
1592
1593         OBD_ALLOC(oxe, len);
1594         if (oxe == NULL)
1595                 return;
1596
1597         INIT_LIST_HEAD(&oxe->oxe_list);
1598         oxe->oxe_len = len;
1599         oxe->oxe_namelen = namelen;
1600         memcpy(oxe->oxe_buf, name, namelen);
1601         if (buflen > 0) {
1602                 LASSERT(buf != NULL);
1603                 memcpy(oxe->oxe_buf + namelen + 1, buf, buflen);
1604                 oxe->oxe_exist = true;
1605         } else {
1606                 oxe->oxe_exist = false;
1607         }
1608
1609         /* this should be rarely called, just remove old and add new */
1610         spin_lock(&obj->oo_guard);
1611         list_for_each_entry(tmp, &obj->oo_xattr_list, oxe_list) {
1612                 if (namelen == tmp->oxe_namelen &&
1613                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1614                         old = tmp;
1615                         break;
1616                 }
1617         }
1618         if (old != NULL) {
1619                 list_replace_rcu(&old->oxe_list, &oxe->oxe_list);
1620                 call_rcu(&old->oxe_rcu, osd_oxc_free);
1621         } else {
1622                 list_add_tail_rcu(&oxe->oxe_list, &obj->oo_xattr_list);
1623         }
1624         spin_unlock(&obj->oo_guard);
1625 }
1626
1627 static void osd_oxc_del(struct osd_object *obj, const char *name)
1628 {
1629         struct osd_xattr_entry *oxe;
1630         size_t namelen = strlen(name);
1631
1632         spin_lock(&obj->oo_guard);
1633         list_for_each_entry(oxe, &obj->oo_xattr_list, oxe_list) {
1634                 if (namelen == oxe->oxe_namelen &&
1635                     strncmp(name, oxe->oxe_buf, namelen) == 0) {
1636                         list_del_rcu(&oxe->oxe_list);
1637                         call_rcu(&oxe->oxe_rcu, osd_oxc_free);
1638                         break;
1639                 }
1640         }
1641         spin_unlock(&obj->oo_guard);
1642 }
1643
1644 static void osd_oxc_fini(struct osd_object *obj)
1645 {
1646         struct osd_xattr_entry *oxe, *next;
1647
1648         list_for_each_entry_safe(oxe, next, &obj->oo_xattr_list, oxe_list) {
1649                 list_del(&oxe->oxe_list);
1650                 OBD_FREE(oxe, oxe->oxe_len);
1651         }
1652 }
1653
1654 /*
1655  * Concurrency: no concurrent access is possible that late in object
1656  * life-cycle.
1657  */
1658 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
1659 {
1660         struct osd_object *obj = osd_obj(l);
1661         struct lu_object_header *h = obj->oo_header;
1662
1663         LINVRNT(osd_invariant(obj));
1664
1665         osd_oxc_fini(obj);
1666         dt_object_fini(&obj->oo_dt);
1667         if (obj->oo_hl_head != NULL)
1668                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1669         /* obj doesn't contain an lu_object_header, so we don't need call_rcu */
1670         OBD_FREE_PTR(obj);
1671         if (unlikely(h))
1672                 lu_object_header_free(h);
1673 }
1674
1675 /*
1676  * Concurrency: no concurrent access is possible that late in object
1677  * life-cycle.
1678  */
1679 static void osd_index_fini(struct osd_object *o)
1680 {
1681         struct iam_container *bag;
1682
1683         if (o->oo_dir != NULL) {
1684                 bag = &o->oo_dir->od_container;
1685                 if (o->oo_inode != NULL) {
1686                         if (bag->ic_object == o->oo_inode)
1687                                 iam_container_fini(bag);
1688                 }
1689                 OBD_FREE_PTR(o->oo_dir);
1690                 o->oo_dir = NULL;
1691         }
1692 }
1693
1694 enum {
1695         OSD_TXN_OI_DELETE_CREDITS    = 20,
1696         OSD_TXN_INODE_DELETE_CREDITS = 20
1697 };
1698
1699 /*
1700  * Journal
1701  */
1702
1703 #if OSD_THANDLE_STATS
1704 /**
1705  * Set time when the handle is allocated
1706  */
1707 static void osd_th_alloced(struct osd_thandle *oth)
1708 {
1709         oth->oth_alloced = ktime_get();
1710 }
1711
1712 /**
1713  * Set time when the handle started
1714  */
1715 static void osd_th_started(struct osd_thandle *oth)
1716 {
1717         oth->oth_started = ktime_get();
1718 }
1719
1720 /**
1721  * Check whether the we deal with this handle for too long.
1722  */
1723 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
1724                                 ktime_t alloced, ktime_t started,
1725                                 ktime_t closed)
1726 {
1727         ktime_t now = ktime_get();
1728
1729         LASSERT(dev != NULL);
1730
1731         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
1732                             ktime_us_delta(started, alloced));
1733         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
1734                             ktime_us_delta(closed, started));
1735         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
1736                             ktime_us_delta(now, closed));
1737
1738         if (ktime_before(ktime_add_ns(alloced, 30 * NSEC_PER_SEC), now)) {
1739                 CWARN("transaction handle %p was open for too long: now %lld, alloced %lld, started %lld, closed %lld\n",
1740                                 oth, now, alloced, started, closed);
1741                 libcfs_debug_dumpstack(NULL);
1742         }
1743 }
1744
1745 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
1746 {                                                                       \
1747         ktime_t __closed = ktime_get();                                 \
1748         ktime_t __alloced = oth->oth_alloced;                           \
1749         ktime_t __started = oth->oth_started;                           \
1750                                                                         \
1751         expr;                                                           \
1752         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
1753 }
1754
1755 #else /* OSD_THANDLE_STATS */
1756
1757 #define osd_th_alloced(h)                  do {} while(0)
1758 #define osd_th_started(h)                  do {} while(0)
1759 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
1760
1761 #endif /* OSD_THANDLE_STATS */
1762
1763 /*
1764  * in some cases (like overstriped files) the same operations on the same
1765  * objects are declared many times and this may lead to huge number of
1766  * credits which can be a problem and/or cause performance degradation.
1767  * this function is to remember what declarations have been made within
1768  * a given thandle and then skip duplications.
1769  * limit it's scope so that regular small transactions don't need all
1770  * this overhead with allocations, lists.
1771  * also, limit scope to the specific objects like llogs, etc.
1772  */
1773 static inline bool osd_check_special_fid(const struct lu_fid *f)
1774 {
1775         if (fid_seq_is_llog(f->f_seq))
1776                 return true;
1777         if (f->f_seq == FID_SEQ_LOCAL_FILE &&
1778             f->f_oid == MDD_LOV_OBJ_OID)
1779                 return true;
1780         return false;
1781 }
1782
1783 bool osd_tx_was_declared(const struct lu_env *env, struct osd_thandle *oth,
1784                          struct dt_object *dt, enum dt_txn_op op, loff_t pos)
1785 {
1786         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
1787         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
1788         struct osd_thread_info *oti = osd_oti_get(env);
1789         struct osd_obj_declare *old;
1790
1791         if (osd->od_is_ost)
1792                 return false;
1793
1794         /* small transactions don't need this overhead */
1795         if (oti->oti_declare_ops[DTO_OBJECT_CREATE] < 10 &&
1796             oti->oti_declare_ops[DTO_WRITE_BASE] < 10)
1797                 return false;
1798
1799         if (osd_check_special_fid(fid) == 0)
1800                 return false;
1801
1802         list_for_each_entry(old, &oth->ot_declare_list, old_list) {
1803                 if (old->old_op == op && old->old_pos == pos &&
1804                     lu_fid_eq(&old->old_fid, fid))
1805                         return true;
1806         }
1807         OBD_ALLOC_PTR(old);
1808         if (unlikely(old == NULL))
1809                 return false;
1810         old->old_fid = *lu_object_fid(&dt->do_lu);
1811         old->old_op = op;
1812         old->old_pos = pos;
1813         list_add(&old->old_list, &oth->ot_declare_list);
1814         return false;
1815 }
1816
1817 void osd_tx_declaration_free(struct osd_thandle *oth)
1818 {
1819         struct osd_obj_declare *old, *tmp;
1820
1821         list_for_each_entry_safe(old, tmp, &oth->ot_declare_list, old_list) {
1822                 list_del_init(&old->old_list);
1823                 OBD_FREE_PTR(old);
1824         }
1825 }
1826
1827 /*
1828  * Concurrency: doesn't access mutable data.
1829  */
1830 static int osd_param_is_not_sane(const struct osd_device *dev,
1831                                  const struct thandle *th)
1832 {
1833         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
1834
1835         return oh->ot_credits > osd_transaction_size(dev);
1836 }
1837
1838 /*
1839  * Concurrency: shouldn't matter.
1840  */
1841 static void osd_trans_commit_cb(struct super_block *sb,
1842                                 struct ldiskfs_journal_cb_entry *jcb, int error)
1843 {
1844         struct osd_thandle *oh = container_of(jcb, struct osd_thandle, ot_jcb);
1845         struct thandle *th = &oh->ot_super;
1846         struct lu_device *lud = &th->th_dev->dd_lu_dev;
1847         struct osd_device *osd = osd_dev(lud);
1848         struct dt_txn_commit_cb *dcb, *tmp;
1849
1850         LASSERT(oh->ot_handle == NULL);
1851
1852         if (error)
1853                 CERROR("transaction @0x%p commit error: %d\n", th, error);
1854
1855         /* call per-transaction callbacks if any */
1856         list_for_each_entry_safe(dcb, tmp, &oh->ot_commit_dcb_list,
1857                                  dcb_linkage) {
1858                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1859                          "commit callback entry: magic=%x name='%s'\n",
1860                          dcb->dcb_magic, dcb->dcb_name);
1861                 list_del_init(&dcb->dcb_linkage);
1862                 dcb->dcb_func(NULL, th, dcb, error);
1863         }
1864
1865         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
1866         if (atomic_dec_and_test(&osd->od_commit_cb_in_flight))
1867                 wake_up(&osd->od_commit_cb_done);
1868         th->th_dev = NULL;
1869
1870         OBD_FREE_PTR(oh);
1871 }
1872
1873 static struct thandle *osd_trans_create(const struct lu_env *env,
1874                                         struct dt_device *d)
1875 {
1876         struct osd_thread_info *oti = osd_oti_get(env);
1877         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1878         struct osd_thandle *oh;
1879         struct thandle *th;
1880
1881         ENTRY;
1882
1883         if (d->dd_rdonly) {
1884                 CERROR("%s: someone try to start transaction under "
1885                        "readonly mode, should be disabled.\n",
1886                        osd_name(osd_dt_dev(d)));
1887                 dump_stack();
1888                 RETURN(ERR_PTR(-EROFS));
1889         }
1890
1891         /* on pending IO in this thread should left from prev. request */
1892         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
1893
1894         sb_start_write(osd_sb(osd_dt_dev(d)));
1895
1896         OBD_ALLOC_GFP(oh, sizeof(*oh), GFP_NOFS);
1897         if (!oh) {
1898                 sb_end_write(osd_sb(osd_dt_dev(d)));
1899                 RETURN(ERR_PTR(-ENOMEM));
1900         }
1901
1902         oh->ot_quota_trans = &oti->oti_quota_trans;
1903         memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
1904         th = &oh->ot_super;
1905         th->th_dev = d;
1906         th->th_result = 0;
1907         oh->ot_credits = 0;
1908         oh->oh_declared_ext = 0;
1909         INIT_LIST_HEAD(&oh->ot_commit_dcb_list);
1910         INIT_LIST_HEAD(&oh->ot_stop_dcb_list);
1911         INIT_LIST_HEAD(&oh->ot_trunc_locks);
1912         INIT_LIST_HEAD(&oh->ot_declare_list);
1913         osd_th_alloced(oh);
1914
1915         memset(oti->oti_declare_ops, 0,
1916                sizeof(oti->oti_declare_ops));
1917         memset(oti->oti_declare_ops_cred, 0,
1918                sizeof(oti->oti_declare_ops_cred));
1919         memset(oti->oti_declare_ops_used, 0,
1920                sizeof(oti->oti_declare_ops_used));
1921
1922         oti->oti_ins_cache_depth++;
1923
1924         RETURN(th);
1925 }
1926
1927 void osd_trans_dump_creds(const struct lu_env *env, struct thandle *th)
1928 {
1929         struct osd_thread_info *oti = osd_oti_get(env);
1930         struct osd_thandle *oh;
1931
1932         oh = container_of(th, struct osd_thandle, ot_super);
1933         LASSERT(oh != NULL);
1934
1935         CWARN("  create: %u/%u/%u, destroy: %u/%u/%u\n",
1936               oti->oti_declare_ops[OSD_OT_CREATE],
1937               oti->oti_declare_ops_cred[OSD_OT_CREATE],
1938               oti->oti_declare_ops_used[OSD_OT_CREATE],
1939               oti->oti_declare_ops[OSD_OT_DESTROY],
1940               oti->oti_declare_ops_cred[OSD_OT_DESTROY],
1941               oti->oti_declare_ops_used[OSD_OT_DESTROY]);
1942         CWARN("  attr_set: %u/%u/%u, xattr_set: %u/%u/%u\n",
1943               oti->oti_declare_ops[OSD_OT_ATTR_SET],
1944               oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1945               oti->oti_declare_ops_used[OSD_OT_ATTR_SET],
1946               oti->oti_declare_ops[OSD_OT_XATTR_SET],
1947               oti->oti_declare_ops_cred[OSD_OT_XATTR_SET],
1948               oti->oti_declare_ops_used[OSD_OT_XATTR_SET]);
1949         CWARN("  write: %u/%u/%u, punch: %u/%u/%u, quota %u/%u/%u\n",
1950               oti->oti_declare_ops[OSD_OT_WRITE],
1951               oti->oti_declare_ops_cred[OSD_OT_WRITE],
1952               oti->oti_declare_ops_used[OSD_OT_WRITE],
1953               oti->oti_declare_ops[OSD_OT_PUNCH],
1954               oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1955               oti->oti_declare_ops_used[OSD_OT_PUNCH],
1956               oti->oti_declare_ops[OSD_OT_QUOTA],
1957               oti->oti_declare_ops_cred[OSD_OT_QUOTA],
1958               oti->oti_declare_ops_used[OSD_OT_QUOTA]);
1959         CWARN("  insert: %u/%u/%u, delete: %u/%u/%u\n",
1960               oti->oti_declare_ops[OSD_OT_INSERT],
1961               oti->oti_declare_ops_cred[OSD_OT_INSERT],
1962               oti->oti_declare_ops_used[OSD_OT_INSERT],
1963               oti->oti_declare_ops[OSD_OT_DELETE],
1964               oti->oti_declare_ops_cred[OSD_OT_DELETE],
1965               oti->oti_declare_ops_used[OSD_OT_DELETE]);
1966         CWARN("  ref_add: %u/%u/%u, ref_del: %u/%u/%u\n",
1967               oti->oti_declare_ops[OSD_OT_REF_ADD],
1968               oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1969               oti->oti_declare_ops_used[OSD_OT_REF_ADD],
1970               oti->oti_declare_ops[OSD_OT_REF_DEL],
1971               oti->oti_declare_ops_cred[OSD_OT_REF_DEL],
1972               oti->oti_declare_ops_used[OSD_OT_REF_DEL]);
1973 }
1974
1975 /*
1976  * Concurrency: shouldn't matter.
1977  */
1978 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
1979                            struct thandle *th)
1980 {
1981         struct osd_thread_info *oti = osd_oti_get(env);
1982         struct osd_device *dev = osd_dt_dev(d);
1983         handle_t *jh;
1984         struct osd_thandle *oh;
1985         int rc;
1986
1987         ENTRY;
1988
1989         LASSERT(current->journal_info == NULL);
1990
1991         oh = container_of(th, struct osd_thandle, ot_super);
1992         LASSERT(oh != NULL);
1993         LASSERT(oh->ot_handle == NULL);
1994         if (unlikely(ldiskfs_track_declares_assert != 0)) {
1995                 LASSERT(oti->oti_r_locks == 0);
1996                 LASSERT(oti->oti_w_locks == 0);
1997         }
1998
1999         rc = dt_txn_hook_start(env, d, th);
2000         if (rc != 0)
2001                 GOTO(out, rc);
2002
2003         if (unlikely(osd_param_is_not_sane(dev, th))) {
2004                 static unsigned long last_printed;
2005                 static int last_credits;
2006
2007                 lprocfs_counter_add(dev->od_stats,
2008                                     LPROC_OSD_TOO_MANY_CREDITS, 1);
2009
2010                 /*
2011                  * don't make noise on a tiny testing systems
2012                  * actual credits misuse will be caught anyway
2013                  */
2014                 if (last_credits != oh->ot_credits &&
2015                     time_after(jiffies, last_printed +
2016                                cfs_time_seconds(60)) &&
2017                     osd_transaction_size(dev) > 512) {
2018                         CWARN("%s: credits %u > trans_max %u\n", osd_name(dev),
2019                               oh->ot_credits, osd_transaction_size(dev));
2020                         osd_trans_dump_creds(env, th);
2021                         libcfs_debug_dumpstack(NULL);
2022                         last_credits = oh->ot_credits;
2023                         last_printed = jiffies;
2024                 }
2025                 /*
2026                  * XXX Limit the credits to 'max_transaction_buffers', and
2027                  *     let the underlying filesystem to catch the error if
2028                  *     we really need so many credits.
2029                  *
2030                  *     This should be removed when we can calculate the
2031                  *     credits precisely.
2032                  */
2033                 oh->ot_credits = osd_transaction_size(dev);
2034         } else if (ldiskfs_track_declares_assert != 0) {
2035                 /*
2036                  * reserve few credits to prevent an assertion in JBD
2037                  * our debugging mechanism will be able to detected
2038                  * overuse. this can help to debug single-update
2039                  * transactions
2040                  */
2041                 oh->ot_credits += 10;
2042                 if (unlikely(osd_param_is_not_sane(dev, th)))
2043                         oh->ot_credits = osd_transaction_size(dev);
2044         }
2045
2046         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_TXN_START))
2047                 GOTO(out, rc = -EIO);
2048
2049          /*
2050           * we ignore quota checks for system-owned files, but still
2051           * need to count blocks for uid/gid/projid
2052           */
2053         osd_trans_declare_op(env, oh, OSD_OT_QUOTA, 3);
2054
2055         /*
2056          * XXX temporary stuff. Some abstraction layer should
2057          * be used.
2058          */
2059         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
2060         osd_th_started(oh);
2061         if (!IS_ERR(jh)) {
2062                 oh->ot_handle = jh;
2063                 LASSERT(oti->oti_txns == 0);
2064
2065                 atomic_inc(&dev->od_commit_cb_in_flight);
2066                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
2067                               "osd-tx", th);
2068                 oti->oti_txns++;
2069                 rc = 0;
2070         } else {
2071                 rc = PTR_ERR(jh);
2072         }
2073 out:
2074         RETURN(rc);
2075 }
2076
2077 static int osd_seq_exists(const struct lu_env *env,
2078                           struct osd_device *osd, u64 seq)
2079 {
2080         struct lu_seq_range *range = &osd_oti_get(env)->oti_seq_range;
2081         struct seq_server_site *ss = osd_seq_site(osd);
2082         int rc;
2083
2084         ENTRY;
2085
2086         LASSERT(ss != NULL);
2087         LASSERT(ss->ss_server_fld != NULL);
2088
2089         rc = osd_fld_lookup(env, osd, seq, range);
2090         if (rc != 0) {
2091                 if (rc != -ENOENT)
2092                         CERROR("%s: can't lookup FLD sequence %#llx: rc = %d\n",
2093                                osd_name(osd), seq, rc);
2094                 RETURN(0);
2095         }
2096
2097         RETURN(ss->ss_node_id == range->lsr_index);
2098 }
2099
2100 static void osd_trans_stop_cb(struct osd_thandle *oth, int result)
2101 {
2102         struct dt_txn_commit_cb *dcb;
2103         struct dt_txn_commit_cb *tmp;
2104
2105         /* call per-transaction stop callbacks if any */
2106         list_for_each_entry_safe(dcb, tmp, &oth->ot_stop_dcb_list,
2107                                  dcb_linkage) {
2108                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
2109                          "commit callback entry: magic=%x name='%s'\n",
2110                          dcb->dcb_magic, dcb->dcb_name);
2111                 list_del_init(&dcb->dcb_linkage);
2112                 dcb->dcb_func(NULL, &oth->ot_super, dcb, result);
2113         }
2114 }
2115
2116 /*
2117  * Concurrency: shouldn't matter.
2118  */
2119 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
2120                           struct thandle *th)
2121 {
2122         struct osd_thread_info *oti = osd_oti_get(env);
2123         struct osd_thandle *oh;
2124         struct osd_iobuf *iobuf = &oti->oti_iobuf;
2125         struct osd_device *osd = osd_dt_dev(th->th_dev);
2126         struct qsd_instance *qsd = osd_def_qsd(osd);
2127         struct lquota_trans *qtrans;
2128         LIST_HEAD(truncates);
2129         int rc = 0, remove_agents = 0;
2130
2131         ENTRY;
2132
2133         oh = container_of(th, struct osd_thandle, ot_super);
2134
2135         remove_agents = oh->ot_remove_agents;
2136
2137         qtrans = oh->ot_quota_trans;
2138         oh->ot_quota_trans = NULL;
2139
2140         osd_tx_declaration_free(oh);
2141
2142         /* move locks to local list, stop tx, execute truncates */
2143         list_splice(&oh->ot_trunc_locks, &truncates);
2144
2145         if (oh->ot_handle != NULL) {
2146                 int rc2;
2147
2148                 handle_t *hdl = oh->ot_handle;
2149
2150                 /*
2151                  * add commit callback
2152                  * notice we don't do this in osd_trans_start()
2153                  * as underlying transaction can change during truncate
2154                  */
2155                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
2156                                              &oh->ot_jcb);
2157
2158                 LASSERT(oti->oti_txns == 1);
2159                 oti->oti_txns--;
2160
2161                 rc = dt_txn_hook_stop(env, th);
2162                 if (rc != 0)
2163                         CERROR("%s: failed in transaction hook: rc = %d\n",
2164                                osd_name(osd), rc);
2165
2166                 osd_trans_stop_cb(oh, rc);
2167                 /* hook functions might modify th_sync */
2168                 hdl->h_sync = th->th_sync;
2169
2170                 oh->ot_handle = NULL;
2171                 OSD_CHECK_SLOW_TH(oh, osd, rc2 = ldiskfs_journal_stop(hdl));
2172                 if (rc2 != 0)
2173                         CERROR("%s: failed to stop transaction: rc = %d\n",
2174                                osd_name(osd), rc2);
2175                 if (!rc)
2176                         rc = rc2;
2177
2178                 /* We preserve the origin behavior of ignoring any
2179                  * failures with the underlying punch / truncate
2180                  * operation. We do record for debugging if an error
2181                  * does occur in the lctl dk logs.
2182                  */
2183                 rc2 = osd_process_truncates(env, &truncates);
2184                 if (rc2 != 0)
2185                         CERROR("%s: failed truncate process: rc = %d\n",
2186                                osd_name(osd), rc2);
2187         } else {
2188                 osd_trans_stop_cb(oh, th->th_result);
2189                 OBD_FREE_PTR(oh);
2190         }
2191
2192         osd_trunc_unlock_all(env, &truncates);
2193
2194         /* inform the quota slave device that the transaction is stopping */
2195         qsd_op_end(env, qsd, qtrans);
2196
2197         /*
2198          * as we want IO to journal and data IO be concurrent, we don't block
2199          * awaiting data IO completion in osd_do_bio(), instead we wait here
2200          * once transaction is submitted to the journal. all reqular requests
2201          * don't do direct IO (except read/write), thus this wait_event becomes
2202          * no-op for them.
2203          *
2204          * IMPORTANT: we have to wait till any IO submited by the thread is
2205          * completed otherwise iobuf may be corrupted by different request
2206          */
2207         wait_event(iobuf->dr_wait,
2208                        atomic_read(&iobuf->dr_numreqs) == 0);
2209         osd_fini_iobuf(osd, iobuf);
2210         if (!rc)
2211                 rc = iobuf->dr_error;
2212
2213         if (unlikely(remove_agents != 0))
2214                 osd_process_scheduled_agent_removals(env, osd);
2215
2216         LASSERT(oti->oti_ins_cache_depth > 0);
2217         oti->oti_ins_cache_depth--;
2218         /* reset OI cache for safety */
2219         if (oti->oti_ins_cache_depth == 0)
2220                 oti->oti_ins_cache_used = 0;
2221
2222         sb_end_write(osd_sb(osd));
2223
2224         RETURN(rc);
2225 }
2226
2227 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
2228 {
2229         struct osd_thandle *oh = container_of(th, struct osd_thandle,
2230                                               ot_super);
2231
2232         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
2233         LASSERT(&dcb->dcb_func != NULL);
2234         if (dcb->dcb_flags & DCB_TRANS_STOP)
2235                 list_add(&dcb->dcb_linkage, &oh->ot_stop_dcb_list);
2236         else
2237                 list_add(&dcb->dcb_linkage, &oh->ot_commit_dcb_list);
2238
2239         return 0;
2240 }
2241
2242 /*
2243  * Called just before object is freed. Releases all resources except for
2244  * object itself (that is released by osd_object_free()).
2245  *
2246  * Concurrency: no concurrent access is possible that late in object
2247  * life-cycle.
2248  */
2249 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
2250 {
2251         struct osd_object *obj = osd_obj(l);
2252         struct qsd_instance *qsd = osd_def_qsd(osd_obj2dev(obj));
2253         struct inode *inode = obj->oo_inode;
2254         __u64 projid;
2255         qid_t uid;
2256         qid_t gid;
2257
2258         LINVRNT(osd_invariant(obj));
2259
2260         /*
2261          * If object is unlinked remove fid->ino mapping from object index.
2262          */
2263
2264         osd_index_fini(obj);
2265
2266         if (!inode)
2267                 return;
2268
2269         if (osd_has_index(obj) &&  obj->oo_dt.do_index_ops == &osd_index_iam_ops)
2270                 ldiskfs_set_inode_flag(inode, LDISKFS_INODE_JOURNAL_DATA);
2271
2272         uid = i_uid_read(inode);
2273         gid = i_gid_read(inode);
2274         projid = i_projid_read(inode);
2275
2276         obj->oo_inode = NULL;
2277         iput(inode);
2278
2279         /* do not rebalance quota if the caller needs to release memory
2280          * otherwise qsd_refresh_usage() may went into a new ldiskfs
2281          * transaction and risk to deadlock - LU-12178 */
2282         if (current->flags & (PF_MEMALLOC | PF_KSWAPD))
2283                 return;
2284
2285         if (!obj->oo_header && qsd) {
2286                 struct osd_thread_info *info = osd_oti_get(env);
2287                 struct lquota_id_info *qi = &info->oti_qi;
2288
2289                 /* Release granted quota to master if necessary */
2290                 qi->lqi_id.qid_uid = uid;
2291                 qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
2292
2293                 qi->lqi_id.qid_uid = gid;
2294                 qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
2295
2296                 qi->lqi_id.qid_uid = projid;
2297                 qsd_op_adjust(env, qsd, &qi->lqi_id, PRJQUOTA);
2298         }
2299 }
2300
2301 /*
2302  * Concurrency: ->loo_object_release() is called under site spin-lock.
2303  */
2304 static void osd_object_release(const struct lu_env *env,
2305                                struct lu_object *l)
2306 {
2307         struct osd_object *o = osd_obj(l);
2308
2309         /*
2310          * nobody should be releasing a non-destroyed object with nlink=0
2311          * the API allows this, but ldiskfs doesn't like and then report
2312          * this inode as deleted
2313          */
2314         LASSERT(!(o->oo_destroyed == 0 && o->oo_inode &&
2315                   o->oo_inode->i_nlink == 0));
2316 }
2317
2318 /*
2319  * Concurrency: shouldn't matter.
2320  */
2321 static int osd_object_print(const struct lu_env *env, void *cookie,
2322                             lu_printer_t p, const struct lu_object *l)
2323 {
2324         struct osd_object *o = osd_obj(l);
2325         struct iam_descr *d;
2326
2327         if (o->oo_dir != NULL)
2328                 d = o->oo_dir->od_container.ic_descr;
2329         else
2330                 d = NULL;
2331         return (*p)(env, cookie,
2332                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
2333                     o, o->oo_inode,
2334                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
2335                     o->oo_inode ? o->oo_inode->i_generation : 0,
2336                     d ? d->id_ops->id_name : "plain");
2337 }
2338
2339 /*
2340  * Concurrency: shouldn't matter.
2341  */
2342 int osd_statfs(const struct lu_env *env, struct dt_device *d,
2343                 struct obd_statfs *sfs, struct obd_statfs_info *info)
2344 {
2345         struct osd_device *osd = osd_dt_dev(d);
2346         struct super_block *sb = osd_sb(osd);
2347         struct kstatfs *ksfs;
2348         __u64 reserved;
2349         int result = 0;
2350
2351         if (unlikely(osd->od_mnt == NULL))
2352                 return -EINPROGRESS;
2353
2354         /* osd_lproc.c call this without env, allocate ksfs for that case */
2355         if (unlikely(env == NULL)) {
2356                 OBD_ALLOC_PTR(ksfs);
2357                 if (ksfs == NULL)
2358                         return -ENOMEM;
2359         } else {
2360                 ksfs = &osd_oti_get(env)->oti_ksfs;
2361         }
2362
2363         result = sb->s_op->statfs(sb->s_root, ksfs);
2364         if (result)
2365                 goto out;
2366
2367         statfs_pack(sfs, ksfs);
2368         if (unlikely(sb->s_flags & SB_RDONLY))
2369                 sfs->os_state |= OS_STATFS_READONLY;
2370
2371         sfs->os_state |= osd->od_nonrotational ? OS_STATFS_NONROT : 0;
2372
2373         if (ldiskfs_has_feature_extents(sb))
2374                 sfs->os_maxbytes = sb->s_maxbytes;
2375         else
2376                 sfs->os_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2377
2378         /*
2379          * Reserve some space so to avoid fragmenting the filesystem too much.
2380          * Fragmentation not only impacts performance, but can also increase
2381          * metadata overhead significantly, causing grant calculation to be
2382          * wrong.
2383          *
2384          * Reserve 0.78% of total space, at least 8MB for small filesystems.
2385          */
2386         BUILD_BUG_ON(OSD_STATFS_RESERVED <= LDISKFS_MAX_BLOCK_SIZE);
2387         reserved = OSD_STATFS_RESERVED >> sb->s_blocksize_bits;
2388         if (likely(sfs->os_blocks >= reserved << OSD_STATFS_RESERVED_SHIFT))
2389                 reserved = sfs->os_blocks >> OSD_STATFS_RESERVED_SHIFT;
2390
2391         sfs->os_blocks -= reserved;
2392         sfs->os_bfree  -= min(reserved, sfs->os_bfree);
2393         sfs->os_bavail -= min(reserved, sfs->os_bavail);
2394
2395 out:
2396         if (unlikely(env == NULL))
2397                 OBD_FREE_PTR(ksfs);
2398         return result;
2399 }
2400
2401 /**
2402  * Estimate space needed for file creations. We assume the largest filename
2403  * which is 2^64 - 1, hence a filename of 20 chars.
2404  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
2405  */
2406 #ifdef __LDISKFS_DIR_REC_LEN
2407 # define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
2408 #elif defined  LDISKFS_DIR_REC_LEN_WITH_DIR
2409 # define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20, NULL)
2410 #else
2411 # define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
2412 #endif
2413
2414 /*
2415  * Concurrency: doesn't access mutable data.
2416  */
2417 static void osd_conf_get(const struct lu_env *env,
2418                          const struct dt_device *dev,
2419                          struct dt_device_param *param)
2420 {
2421         struct osd_device *d = osd_dt_dev(dev);
2422         struct super_block *sb = osd_sb(d);
2423         struct blk_integrity *bi = bdev_get_integrity(sb->s_bdev);
2424         const char *name;
2425         int ea_overhead;
2426
2427         /*
2428          * XXX should be taken from not-yet-existing fs abstraction layer.
2429          */
2430         param->ddp_max_name_len = LDISKFS_NAME_LEN;
2431         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
2432         param->ddp_symlink_max  = sb->s_blocksize;
2433         param->ddp_mount_type   = LDD_MT_LDISKFS;
2434         if (ldiskfs_has_feature_extents(sb))
2435                 param->ddp_maxbytes = sb->s_maxbytes;
2436         else
2437                 param->ddp_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2438         /*
2439          * inode are statically allocated, so per-inode space consumption
2440          * is the space consumed by the directory entry
2441          */
2442         param->ddp_inodespace     = PER_OBJ_USAGE;
2443         /*
2444          * EXT_INIT_MAX_LEN is the theoretical maximum extent size (32k blocks
2445          * is 128MB) which is unlikely to be hit in real life. Report a smaller
2446          * maximum length to not under-count the actual number of extents
2447          * needed for writing a file if there are sub-optimal block allocations.
2448          */
2449         param->ddp_max_extent_blks = EXT_INIT_MAX_LEN >> 1;
2450         /* worst-case extent insertion metadata overhead */
2451         param->ddp_extent_tax = 6 * LDISKFS_BLOCK_SIZE(sb);
2452         param->ddp_mntopts = 0;
2453         if (test_opt(sb, XATTR_USER))
2454                 param->ddp_mntopts |= MNTOPT_USERXATTR;
2455         if (test_opt(sb, POSIX_ACL))
2456                 param->ddp_mntopts |= MNTOPT_ACL;
2457
2458         /*
2459          * LOD might calculate the max stripe count based on max_ea_size,
2460          * so we need take account in the overhead as well,
2461          * xattr_header + magic + xattr_entry_head
2462          */
2463         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
2464                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
2465
2466 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
2467         if (ldiskfs_has_feature_ea_inode(sb))
2468                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
2469                                                                 ea_overhead;
2470         else
2471 #endif
2472                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
2473
2474         if (param->ddp_max_ea_size > OBD_MAX_EA_SIZE)
2475                 param->ddp_max_ea_size = OBD_MAX_EA_SIZE;
2476
2477         /*
2478          * Preferred RPC size for efficient disk IO.  4MB shows good
2479          * all-around performance for ldiskfs, but use bigalloc chunk size
2480          * by default if larger.
2481          */
2482 #if defined(LDISKFS_CLUSTER_SIZE)
2483         if (LDISKFS_CLUSTER_SIZE(sb) > DT_DEF_BRW_SIZE)
2484                 param->ddp_brw_size = LDISKFS_CLUSTER_SIZE(sb);
2485         else
2486 #endif
2487                 param->ddp_brw_size = DT_DEF_BRW_SIZE;
2488
2489         param->ddp_t10_cksum_type = 0;
2490         if (bi) {
2491                 unsigned short interval = blk_integrity_interval(bi);
2492                 name = blk_integrity_name(bi);
2493                 /*
2494                  * Expected values:
2495                  * T10-DIF-TYPE1-CRC
2496                  * T10-DIF-TYPE2-CRC
2497                  * T10-DIF-TYPE3-CRC
2498                  * T10-DIF-TYPE1-IP
2499                  * T10-DIF-TYPE2-IP
2500                  * T10-DIF-TYPE3-IP
2501                  */
2502                 if (strncmp(name, "T10-DIF-TYPE",
2503                             sizeof("T10-DIF-TYPE") - 1) == 0) {
2504                         /* also skip "1/2/3-" at end */
2505                         const int type_off = sizeof("T10-DIF-TYPE.");
2506                         char type_number = name[type_off - 2];
2507
2508                         if (interval != 512 && interval != 4096) {
2509                                 CERROR("%s: unsupported T10PI sector size %u\n",
2510                                        d->od_svname, interval);
2511                                 goto out;
2512                         }
2513                         switch (type_number) {
2514                         case '1':
2515                                 d->od_t10_type = OSD_T10_TYPE1;
2516                                 break;
2517                         case '2':
2518                                 d->od_t10_type = OSD_T10_TYPE2;
2519                                 break;
2520                         case '3':
2521                                 d->od_t10_type = OSD_T10_TYPE3;
2522                                 break;
2523                         default:
2524                                 CERROR("%s: unsupported T10PI type %s\n",
2525                                        d->od_svname, name);
2526                                 goto out;
2527                         }
2528                         if (strcmp(name + type_off, "CRC") == 0) {
2529                                 d->od_t10_type |= OSD_T10_TYPE_CRC;
2530                                 param->ddp_t10_cksum_type = interval == 512 ?
2531                                         OBD_CKSUM_T10CRC512 :
2532                                         OBD_CKSUM_T10CRC4K;
2533                         } else if (strcmp(name + type_off, "IP") == 0) {
2534                                 d->od_t10_type |= OSD_T10_TYPE_IP;
2535                                 param->ddp_t10_cksum_type = interval == 512 ?
2536                                         OBD_CKSUM_T10IP512 :
2537                                         OBD_CKSUM_T10IP4K;
2538                         } else {
2539                                 CERROR("%s: unsupported checksum type of T10PI type '%s'\n",
2540                                        d->od_svname, name);
2541                                 d->od_t10_type = 0;
2542                         }
2543
2544                 } else {
2545                         CERROR("%s: unsupported T10PI type '%s'\n",
2546                                d->od_svname, name);
2547                 }
2548         }
2549
2550 out:
2551         param->ddp_has_lseek_data_hole = true;
2552 }
2553
2554 static struct super_block *osd_mnt_sb_get(const struct dt_device *d)
2555 {
2556         return osd_sb(osd_dt_dev(d));
2557 }
2558
2559 /*
2560  * Concurrency: shouldn't matter.
2561  */
2562 static int osd_sync(const struct lu_env *env, struct dt_device *d)
2563 {
2564         int rc;
2565         struct super_block *s = osd_sb(osd_dt_dev(d));
2566         ENTRY;
2567
2568         down_read(&s->s_umount);
2569         rc = s->s_op->sync_fs(s, 1);
2570         up_read(&s->s_umount);
2571
2572         CDEBUG(D_CACHE, "%s: synced OSD: rc = %d\n", osd_dt_dev(d)->od_svname,
2573                rc);
2574
2575         return rc;
2576 }
2577
2578 /**
2579  * Start commit for OSD device.
2580  *
2581  * An implementation of dt_commit_async method for OSD device.
2582  * Asychronously starts underlayng fs sync and thereby a transaction
2583  * commit.
2584  *
2585  * \param env environment
2586  * \param d dt device
2587  *
2588  * \see dt_device_operations
2589  */
2590 static int osd_commit_async(const struct lu_env *env,
2591                             struct dt_device *d)
2592 {
2593         struct super_block *s = osd_sb(osd_dt_dev(d));
2594         int rc;
2595
2596         ENTRY;
2597
2598         CDEBUG(D_HA, "%s: async commit OSD\n", osd_dt_dev(d)->od_svname);
2599         down_read(&s->s_umount);
2600         rc = s->s_op->sync_fs(s, 0);
2601         up_read(&s->s_umount);
2602
2603         RETURN(rc);
2604 }
2605
2606 /*
2607  * Concurrency: shouldn't matter.
2608  */
2609 static int osd_ro(const struct lu_env *env, struct dt_device *d)
2610 {
2611         struct super_block *sb = osd_sb(osd_dt_dev(d));
2612         struct block_device *dev = sb->s_bdev;
2613         int rc = -EOPNOTSUPP;
2614
2615         ENTRY;
2616
2617         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
2618                osd_dt_dev(d)->od_svname, (long)dev, rc);
2619
2620         RETURN(rc);
2621 }
2622
2623 /**
2624  * Note: we do not count into QUOTA here.
2625  * If we mount with --data_journal we may need more.
2626  */
2627 const int osd_dto_credits_noquota[DTO_NR] = {
2628         /**
2629          * Insert.
2630          * INDEX_EXTRA_TRANS_BLOCKS(8) +
2631          * SINGLEDATA_TRANS_BLOCKS(8)
2632          * XXX Note: maybe iam need more, since iam have more level than
2633          *           EXT3 htree.
2634          */
2635         [DTO_INDEX_INSERT]  = 16,
2636         /**
2637          * Delete
2638          * just modify a single entry, probably merge few within a block
2639          */
2640         [DTO_INDEX_DELETE]  = 1,
2641         /**
2642          * Used for OI scrub
2643          */
2644         [DTO_INDEX_UPDATE]  = 16,
2645         /**
2646          * 4(inode, inode bits, groups, GDT)
2647          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
2648          */
2649         [DTO_OBJECT_CREATE] = 4,
2650         /**
2651          * 4(inode, inode bits, groups, GDT)
2652          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
2653          */
2654         [DTO_OBJECT_DELETE] = 4,
2655         /**
2656          * Attr set credits (inode)
2657          */
2658         [DTO_ATTR_SET_BASE] = 1,
2659         /**
2660          * Xattr set. The same as xattr of EXT3.
2661          * DATA_TRANS_BLOCKS(14)
2662          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
2663          * are also counted in. Do not know why?
2664          */
2665         [DTO_XATTR_SET]     = 14,
2666         /**
2667          * credits for inode change during write.
2668          */
2669         [DTO_WRITE_BASE]    = 3,
2670         /**
2671          * credits for single block write.
2672          */
2673         [DTO_WRITE_BLOCK]   = 14,
2674         /**
2675          * Attr set credits for chown.
2676          * This is extra credits for setattr, and it is null without quota
2677          */
2678         [DTO_ATTR_SET_CHOWN] = 0
2679 };
2680
2681 /* reserve or free quota for some operation */
2682 static int osd_reserve_or_free_quota(const struct lu_env *env,
2683                                      struct dt_device *dev,
2684                                      struct lquota_id_info *qi)
2685 {
2686         struct osd_device       *osd = osd_dt_dev(dev);
2687         struct qsd_instance     *qsd = NULL;
2688         int rc;
2689
2690         ENTRY;
2691
2692         if (qi->lqi_is_blk)
2693                 qsd = osd->od_quota_slave_dt;
2694         else
2695                 qsd = osd->od_quota_slave_md;
2696
2697         rc = qsd_reserve_or_free_quota(env, qsd, qi);
2698         RETURN(rc);
2699 }
2700
2701 static const struct dt_device_operations osd_dt_ops = {
2702         .dt_root_get              = osd_root_get,
2703         .dt_statfs                = osd_statfs,
2704         .dt_trans_create          = osd_trans_create,
2705         .dt_trans_start           = osd_trans_start,
2706         .dt_trans_stop            = osd_trans_stop,
2707         .dt_trans_cb_add          = osd_trans_cb_add,
2708         .dt_conf_get              = osd_conf_get,
2709         .dt_mnt_sb_get            = osd_mnt_sb_get,
2710         .dt_sync                  = osd_sync,
2711         .dt_ro                    = osd_ro,
2712         .dt_commit_async          = osd_commit_async,
2713         .dt_reserve_or_free_quota = osd_reserve_or_free_quota,
2714 };
2715
2716 static void osd_read_lock(const struct lu_env *env, struct dt_object *dt,
2717                           unsigned int role)
2718 {
2719         struct osd_object *obj = osd_dt_obj(dt);
2720         struct osd_thread_info *oti = osd_oti_get(env);
2721
2722         LINVRNT(osd_invariant(obj));
2723
2724         LASSERT(obj->oo_owner != env);
2725         down_read_nested(&obj->oo_sem, role);
2726
2727         LASSERT(obj->oo_owner == NULL);
2728         oti->oti_r_locks++;
2729 }
2730
2731 static void osd_write_lock(const struct lu_env *env, struct dt_object *dt,
2732                            unsigned int role)
2733 {
2734         struct osd_object *obj = osd_dt_obj(dt);
2735         struct osd_thread_info *oti = osd_oti_get(env);
2736
2737         LINVRNT(osd_invariant(obj));
2738
2739         LASSERT(obj->oo_owner != env);
2740         down_write_nested(&obj->oo_sem, role);
2741
2742         LASSERT(obj->oo_owner == NULL);
2743         obj->oo_owner = env;
2744         oti->oti_w_locks++;
2745 }
2746
2747 static void osd_read_unlock(const struct lu_env *env, struct dt_object *dt)
2748 {
2749         struct osd_object *obj = osd_dt_obj(dt);
2750         struct osd_thread_info *oti = osd_oti_get(env);
2751
2752         LINVRNT(osd_invariant(obj));
2753
2754         LASSERT(oti->oti_r_locks > 0);
2755         oti->oti_r_locks--;
2756         up_read(&obj->oo_sem);
2757 }
2758
2759 static void osd_write_unlock(const struct lu_env *env, struct dt_object *dt)
2760 {
2761         struct osd_object *obj = osd_dt_obj(dt);
2762         struct osd_thread_info *oti = osd_oti_get(env);
2763
2764         LINVRNT(osd_invariant(obj));
2765
2766         LASSERT(obj->oo_owner == env);
2767         LASSERT(oti->oti_w_locks > 0);
2768         oti->oti_w_locks--;
2769         obj->oo_owner = NULL;
2770         up_write(&obj->oo_sem);
2771 }
2772
2773 static int osd_write_locked(const struct lu_env *env, struct dt_object *dt)
2774 {
2775         struct osd_object *obj = osd_dt_obj(dt);
2776
2777         LINVRNT(osd_invariant(obj));
2778
2779         return obj->oo_owner == env;
2780 }
2781
2782 static void osd_inode_getattr(const struct lu_env *env,
2783                               struct inode *inode, struct lu_attr *attr)
2784 {
2785         attr->la_valid  |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
2786                            LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
2787                            LA_PROJID | LA_FLAGS | LA_NLINK | LA_RDEV |
2788                            LA_BLKSIZE | LA_TYPE | LA_BTIME;
2789
2790         attr->la_atime = inode->i_atime.tv_sec;
2791         attr->la_mtime = inode->i_mtime.tv_sec;
2792         attr->la_ctime = inode->i_ctime.tv_sec;
2793         attr->la_btime = LDISKFS_I(inode)->i_crtime.tv_sec;
2794         attr->la_mode    = inode->i_mode;
2795         attr->la_size    = i_size_read(inode);
2796         attr->la_blocks  = inode->i_blocks;
2797         attr->la_uid     = i_uid_read(inode);
2798         attr->la_gid     = i_gid_read(inode);
2799         attr->la_projid  = i_projid_read(inode);
2800         attr->la_flags   = ll_inode_to_ext_flags(inode->i_flags);
2801         attr->la_nlink   = inode->i_nlink;
2802         attr->la_rdev    = inode->i_rdev;
2803         attr->la_blksize = 1 << inode->i_blkbits;
2804         attr->la_blkbits = inode->i_blkbits;
2805         /*
2806          * Ext4 did not transfer inherit flags from raw inode
2807          * to inode flags, and ext4 internally test raw inode
2808          * @i_flags directly. Instead of patching ext4, we do it here.
2809          */
2810         if (LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL)
2811                 attr->la_flags |= LUSTRE_PROJINHERIT_FL;
2812 }
2813
2814 static int osd_dirent_count(const struct lu_env *env, struct dt_object *dt,
2815                             u64 *count)
2816 {
2817         struct osd_object *obj = osd_dt_obj(dt);
2818         const struct dt_it_ops *iops;
2819         struct dt_it *it;
2820         int rc;
2821
2822         ENTRY;
2823
2824         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
2825         LASSERT(fid_is_namespace_visible(lu_object_fid(&obj->oo_dt.do_lu)));
2826
2827         if (obj->oo_dirent_count != LU_DIRENT_COUNT_UNSET) {
2828                 *count = obj->oo_dirent_count;
2829                 RETURN(0);
2830         }
2831
2832         /* directory not initialized yet */
2833         if (!dt->do_index_ops) {
2834                 *count = 0;
2835                 RETURN(0);
2836         }
2837
2838         iops = &dt->do_index_ops->dio_it;
2839         it = iops->init(env, dt, LUDA_64BITHASH);
2840         if (IS_ERR(it))
2841                 RETURN(PTR_ERR(it));
2842
2843         rc = iops->load(env, it, 0);
2844         if (rc < 0) {
2845                 if (rc == -ENODATA) {
2846                         rc = 0;
2847                         *count = 0;
2848                 }
2849                 GOTO(out, rc);
2850         }
2851         if (rc > 0)
2852                 rc = iops->next(env, it);
2853
2854         for (*count = 0; rc == 0 || rc == -ESTALE; rc = iops->next(env, it)) {
2855                 if (rc == -ESTALE)
2856                         continue;
2857
2858                 if (iops->key_size(env, it) == 0)
2859                         continue;
2860
2861                 (*count)++;
2862         }
2863         if (rc == 1) {
2864                 obj->oo_dirent_count = *count;
2865                 rc = 0;
2866         }
2867 out:
2868         iops->put(env, it);
2869         iops->fini(env, it);
2870
2871         RETURN(rc);
2872 }
2873
2874 static int osd_attr_get(const struct lu_env *env, struct dt_object *dt,
2875                         struct lu_attr *attr)
2876 {
2877         struct osd_object *obj = osd_dt_obj(dt);
2878         int rc = 0;
2879
2880         if (unlikely(!dt_object_exists(dt)))
2881                 return -ENOENT;
2882         if (unlikely(obj->oo_destroyed))
2883                 return -ENOENT;
2884
2885         LASSERT(!dt_object_remote(dt));
2886         LINVRNT(osd_invariant(obj));
2887
2888         spin_lock(&obj->oo_guard);
2889         osd_inode_getattr(env, obj->oo_inode, attr);
2890         if (obj->oo_lma_flags & LUSTRE_ORPHAN_FL) {
2891                 attr->la_valid |= LA_FLAGS;
2892                 attr->la_flags |= LUSTRE_ORPHAN_FL;
2893         }
2894         if (obj->oo_lma_flags & LUSTRE_ENCRYPT_FL) {
2895                 attr->la_valid |= LA_FLAGS;
2896                 attr->la_flags |= LUSTRE_ENCRYPT_FL;
2897         }
2898         spin_unlock(&obj->oo_guard);
2899
2900         if (S_ISDIR(obj->oo_inode->i_mode) &&
2901             fid_is_namespace_visible(lu_object_fid(&dt->do_lu)))
2902                 rc = osd_dirent_count(env, dt, &attr->la_dirent_count);
2903
2904         return rc;
2905 }
2906
2907 static int osd_declare_attr_qid(const struct lu_env *env,
2908                                 struct osd_object *obj,
2909                                 struct osd_thandle *oh, long long bspace,
2910                                 qid_t old_id, qid_t new_id, bool enforce,
2911                                 unsigned int type)
2912 {
2913         int rc;
2914         struct osd_thread_info *info = osd_oti_get(env);
2915         struct lquota_id_info  *qi = &info->oti_qi;
2916
2917         qi->lqi_type = type;
2918         /* inode accounting */
2919         qi->lqi_is_blk = false;
2920
2921         /* one more inode for the new id ... */
2922         qi->lqi_id.qid_uid = new_id;
2923         qi->lqi_space      = 1;
2924         /* Reserve credits for the new id */
2925         rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
2926         if (rc == -EDQUOT || rc == -EINPROGRESS)
2927                 rc = 0;
2928         if (rc)
2929                 RETURN(rc);
2930
2931         /* and one less inode for the current id */
2932         qi->lqi_id.qid_uid = old_id;
2933         qi->lqi_space = -1;
2934         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2935         if (rc == -EDQUOT || rc == -EINPROGRESS)
2936                 rc = 0;
2937         if (rc)
2938                 RETURN(rc);
2939
2940         /* block accounting */
2941         qi->lqi_is_blk = true;
2942
2943         /* more blocks for the new id ... */
2944         qi->lqi_id.qid_uid = new_id;
2945         qi->lqi_space      = bspace;
2946         /*
2947          * Credits for the new uid has been reserved, re-use "obj"
2948          * to save credit reservation.
2949          */
2950         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2951         if (rc == -EDQUOT || rc == -EINPROGRESS)
2952                 rc = 0;
2953         if (rc)
2954                 RETURN(rc);
2955
2956         /* and finally less blocks for the current uid */
2957         qi->lqi_id.qid_uid = old_id;
2958         qi->lqi_space      = -bspace;
2959         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2960         if (rc == -EDQUOT || rc == -EINPROGRESS)
2961                 rc = 0;
2962
2963         RETURN(rc);
2964 }
2965
2966 static int osd_declare_attr_set(const struct lu_env *env,
2967                                 struct dt_object *dt,
2968                                 const struct lu_attr *attr,
2969                                 struct thandle *handle)
2970 {
2971         struct osd_thandle *oh;
2972         struct osd_object *obj;
2973         qid_t uid;
2974         qid_t gid;
2975         long long bspace;
2976         int rc = 0;
2977         bool enforce;
2978
2979         ENTRY;
2980
2981         LASSERT(dt != NULL);
2982         LASSERT(handle != NULL);
2983
2984         obj = osd_dt_obj(dt);
2985         LASSERT(osd_invariant(obj));
2986
2987         oh = container_of(handle, struct osd_thandle, ot_super);
2988         LASSERT(oh->ot_handle == NULL);
2989
2990         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
2991                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2992
2993         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2994                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2995
2996         if (attr == NULL || obj->oo_inode == NULL)
2997                 RETURN(rc);
2998
2999         bspace   = obj->oo_inode->i_blocks << 9;
3000         bspace   = toqb(bspace);
3001
3002         /*
3003          * Changing ownership is always preformed by super user, it should not
3004          * fail with EDQUOT unless required explicitly.
3005          *
3006          * We still need to call the osd_declare_qid() to calculate the journal
3007          * credits for updating quota accounting files and to trigger quota
3008          * space adjustment once the operation is completed.
3009          */
3010         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
3011                 /* USERQUOTA */
3012                 uid = i_uid_read(obj->oo_inode);
3013                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
3014                 rc = osd_declare_attr_qid(env, obj, oh, bspace, uid,
3015                                           attr->la_uid, enforce, USRQUOTA);
3016                 if (rc)
3017                         RETURN(rc);
3018
3019                 gid = i_gid_read(obj->oo_inode);
3020                 CDEBUG(D_QUOTA, "declare uid %d -> %d gid %d -> %d\n", uid,
3021                        attr->la_uid, gid, attr->la_gid);
3022                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
3023                 rc = osd_declare_attr_qid(env, obj, oh, bspace, gid,
3024                                           attr->la_gid, enforce, GRPQUOTA);
3025                 if (rc)
3026                         RETURN(rc);
3027
3028         }
3029 #ifdef HAVE_PROJECT_QUOTA
3030         if (attr->la_valid & LA_PROJID) {
3031                 __u32 projid = i_projid_read(obj->oo_inode);
3032
3033                 enforce = (attr->la_valid & LA_PROJID) &&
3034                                         (attr->la_projid != projid);
3035                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
3036                                           (qid_t)projid, (qid_t)attr->la_projid,
3037                                           enforce, PRJQUOTA);
3038                 if (rc)
3039                         RETURN(rc);
3040         }
3041 #endif
3042         /* punch must be aware we are dealing with an encrypted file */
3043         if (attr->la_valid & LA_FLAGS && attr->la_flags & LUSTRE_ENCRYPT_FL)
3044                 obj->oo_lma_flags |= LUSTRE_ENCRYPT_FL;
3045
3046         RETURN(rc);
3047 }
3048
3049 static int osd_inode_setattr(const struct lu_env *env,
3050                              struct inode *inode, const struct lu_attr *attr)
3051 {
3052         __u64 bits = attr->la_valid;
3053
3054         /* Only allow set size for regular file */
3055         if (!S_ISREG(inode->i_mode))
3056                 bits &= ~(LA_SIZE | LA_BLOCKS);
3057
3058         if (bits == 0)
3059                 return 0;
3060
3061         if (bits & LA_ATIME)
3062                 inode->i_atime = osd_inode_time(inode, attr->la_atime);
3063         if (bits & LA_CTIME)
3064                 inode->i_ctime = osd_inode_time(inode, attr->la_ctime);
3065         if (bits & LA_MTIME)
3066                 inode->i_mtime = osd_inode_time(inode, attr->la_mtime);
3067         if (bits & LA_SIZE) {
3068                 spin_lock(&inode->i_lock);
3069                 LDISKFS_I(inode)->i_disksize = attr->la_size;
3070                 i_size_write(inode, attr->la_size);
3071                 spin_unlock(&inode->i_lock);
3072         }
3073
3074         /*
3075          * OSD should not change "i_blocks" which is used by quota.
3076          * "i_blocks" should be changed by ldiskfs only.
3077          */
3078         if (bits & LA_MODE)
3079                 inode->i_mode = (inode->i_mode & S_IFMT) |
3080                                 (attr->la_mode & ~S_IFMT);
3081         if (bits & LA_UID)
3082                 i_uid_write(inode, attr->la_uid);
3083         if (bits & LA_GID)
3084                 i_gid_write(inode, attr->la_gid);
3085         if (bits & LA_PROJID)
3086                 i_projid_write(inode, attr->la_projid);
3087         if (bits & LA_NLINK)
3088                 set_nlink(inode, attr->la_nlink);
3089         if (bits & LA_RDEV)
3090                 inode->i_rdev = attr->la_rdev;
3091
3092         if (bits & LA_FLAGS) {
3093                 /* always keep S_NOCMTIME */
3094                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
3095                                  S_NOCMTIME;
3096 #if defined(S_ENCRYPTED)
3097                 /* Always remove S_ENCRYPTED, because ldiskfs must not be
3098                  * aware of encryption status. It is just stored into LMA
3099                  * so that it can be forwared to client side.
3100                  */
3101                 inode->i_flags &= ~S_ENCRYPTED;
3102 #endif
3103                 /*
3104                  * Ext4 did not transfer inherit flags from
3105                  * @inode->i_flags to raw inode i_flags when writing
3106                  * flags, we do it explictly here.
3107                  */
3108                 if (attr->la_flags & LUSTRE_PROJINHERIT_FL)
3109                         LDISKFS_I(inode)->i_flags |= LUSTRE_PROJINHERIT_FL;
3110                 else
3111                         LDISKFS_I(inode)->i_flags &= ~LUSTRE_PROJINHERIT_FL;
3112         }
3113         return 0;
3114 }
3115
3116 #ifdef HAVE_PROJECT_QUOTA
3117 static int osd_transfer_project(struct inode *inode, __u32 projid,
3118                                 struct thandle *handle)
3119 {
3120         struct super_block *sb = inode->i_sb;
3121         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
3122         int err;
3123         kprojid_t kprojid;
3124         struct ldiskfs_iloc iloc;
3125         struct ldiskfs_inode *raw_inode;
3126         struct dquot *transfer_to[LDISKFS_MAXQUOTAS] = { };
3127
3128         if (!ldiskfs_has_feature_project(sb)) {
3129                 LASSERT(__kprojid_val(LDISKFS_I(inode)->i_projid)
3130                         == LDISKFS_DEF_PROJID);
3131                 if (projid != LDISKFS_DEF_PROJID)
3132                         return -EOPNOTSUPP;
3133                 else
3134                         return 0;
3135         }
3136
3137         if (LDISKFS_INODE_SIZE(sb) <= LDISKFS_GOOD_OLD_INODE_SIZE)
3138                 return -EOPNOTSUPP;
3139
3140         kprojid = make_kprojid(&init_user_ns, (projid_t)projid);
3141         if (projid_eq(kprojid, LDISKFS_I(inode)->i_projid))
3142                 return 0;
3143
3144         err = ldiskfs_get_inode_loc(inode, &iloc);
3145         if (err)
3146                 return err;
3147
3148         raw_inode = ldiskfs_raw_inode(&iloc);
3149         if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3150                 struct osd_thandle *oh = container_of(handle,
3151                                                       struct osd_thandle,
3152                                                       ot_super);
3153                 /**
3154                  * try to expand inode size automatically.
3155                  */
3156                 ldiskfs_mark_inode_dirty(oh->ot_handle, inode);
3157                 if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3158                         err = -EOVERFLOW;
3159                         brelse(iloc.bh);
3160                         return err;
3161                 }
3162         }
3163         brelse(iloc.bh);
3164
3165         dquot_initialize(inode);
3166         transfer_to[PRJQUOTA] = dqget(sb, make_kqid_projid(kprojid));
3167         if (transfer_to[PRJQUOTA]) {
3168                 lock_dquot_transfer(inode);
3169                 err = __dquot_transfer(inode, transfer_to);
3170                 unlock_dquot_transfer(inode);
3171                 dqput(transfer_to[PRJQUOTA]);
3172                 if (err)
3173                         return err;
3174         }
3175
3176         return err;
3177 }
3178 #endif
3179
3180 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr,
3181                               struct thandle *handle)
3182 {
3183         int rc;
3184
3185         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
3186             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
3187                 struct iattr iattr;
3188
3189                 CDEBUG(D_QUOTA,
3190                        "executing dquot_transfer inode %ld uid %d -> %d gid %d -> %d\n",
3191                        inode->i_ino, i_uid_read(inode), attr->la_uid,
3192                        i_gid_read(inode), attr->la_gid);
3193
3194                 dquot_initialize(inode);
3195                 iattr.ia_valid = 0;
3196                 if (attr->la_valid & LA_UID)
3197                         iattr.ia_valid |= ATTR_UID;
3198                 if (attr->la_valid & LA_GID)
3199                         iattr.ia_valid |= ATTR_GID;
3200                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3201                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3202
3203                 lock_dquot_transfer(inode);
3204                 rc = osd_dquot_transfer(&init_user_ns, inode, &iattr);
3205                 unlock_dquot_transfer(inode);
3206                 if (rc) {
3207                         CERROR("%s: quota transfer failed. Is quota enforcement enabled on the ldiskfs filesystem? rc = %d\n",
3208                                osd_ino2name(inode), rc);
3209                         return rc;
3210                 }
3211         }
3212
3213         /* Handle project id transfer here properly */
3214         if (attr->la_valid & LA_PROJID &&
3215             attr->la_projid != i_projid_read(inode)) {
3216                 if (!projid_valid(make_kprojid(&init_user_ns, attr->la_projid)))
3217                         return -EINVAL;
3218 #ifdef HAVE_PROJECT_QUOTA
3219                 rc = osd_transfer_project(inode, attr->la_projid, handle);
3220 #else
3221                 rc = -ENOTSUPP;
3222 #endif
3223                 if (rc) {
3224                         CERROR("%s: quota transfer failed. Is project enforcement enabled on the ldiskfs filesystem? rc = %d\n",
3225                                osd_ino2name(inode), rc);
3226                         return rc;
3227                 }
3228         }
3229         return 0;
3230 }
3231
3232 static int osd_attr_set(const struct lu_env *env,
3233                         struct dt_object *dt,
3234                         const struct lu_attr *attr,
3235                         struct thandle *handle)
3236 {
3237         struct osd_thread_info *info = osd_oti_get(env);
3238         struct osd_object *obj = osd_dt_obj(dt);
3239         struct osd_device *osd = osd_obj2dev(obj);
3240         struct inode *inode;
3241         int rc;
3242
3243         if (!dt_object_exists(dt))
3244                 return -ENOENT;
3245
3246         LASSERT(handle != NULL);
3247         LASSERT(!dt_object_remote(dt));
3248         LASSERT(osd_invariant(obj));
3249
3250         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
3251
3252         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING) &&
3253             !osd_obj2dev(obj)->od_is_ost) {
3254                 struct osd_thread_info *oti = osd_oti_get(env);
3255                 const struct lu_fid *fid0 = lu_object_fid(&dt->do_lu);
3256                 struct lu_fid *fid1 = &oti->oti_fid;
3257                 struct osd_inode_id *id = &oti->oti_id;
3258                 struct iam_path_descr *ipd;
3259                 struct iam_container *bag;
3260                 struct osd_thandle *oh;
3261                 int rc;
3262
3263                 fid_cpu_to_be(fid1, fid0);
3264                 memset(id, 1, sizeof(*id));
3265                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
3266                                   fid0)->oi_dir.od_container;
3267                 ipd = osd_idx_ipd_get(env, bag);
3268                 if (unlikely(ipd == NULL))
3269                         RETURN(-ENOMEM);
3270
3271                 oh = container_of(handle, struct osd_thandle, ot_super);
3272                 rc = iam_update(oh->ot_handle, bag,
3273                                 (const struct iam_key *)fid1,
3274                                 (const struct iam_rec *)id, ipd);
3275                 osd_ipd_put(env, bag, ipd);
3276                 return(rc > 0 ? 0 : rc);
3277         }
3278
3279         inode = obj->oo_inode;
3280
3281         rc = osd_quota_transfer(inode, attr, handle);
3282         if (rc)
3283                 return rc;
3284
3285         spin_lock(&obj->oo_guard);
3286         rc = osd_inode_setattr(env, inode, attr);
3287         spin_unlock(&obj->oo_guard);
3288         if (rc != 0)
3289                 GOTO(out, rc);
3290
3291         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3292
3293         osd_trans_exec_check(env, handle, OSD_OT_ATTR_SET);
3294
3295         if (!(attr->la_valid & LA_FLAGS))
3296                 GOTO(out, rc);
3297
3298         /* If setting LUSTRE_ENCRYPT_FL on an OST object, also set a dummy
3299          * enc ctx xattr, with 2 benefits:
3300          * - setting the LL_XATTR_NAME_ENCRYPTION_CONTEXT xattr internally sets
3301          *   the LDISKFS_ENCRYPT_FL flag on the on-disk inode;
3302          * - it makes e2fsprogs happy to see an enc ctx for an inode that has
3303          *   the LDISKFS_ENCRYPT_FL flag
3304          * We do not need the actual encryption context on OST objects, it is
3305          * only stored on MDT inodes, at file creation time.
3306          */
3307         if (!(LDISKFS_I(obj->oo_inode)->i_flags & LDISKFS_ENCRYPT_FL) &&
3308             attr->la_flags & LUSTRE_ENCRYPT_FL && osd->od_is_ost &&
3309             !OBD_FAIL_CHECK(OBD_FAIL_LFSCK_NO_ENCFLAG)) {
3310                 struct lu_buf buf;
3311
3312                 /* use a dummy enc ctx, fine with e2fsprogs */
3313                 buf.lb_buf = "\xFF";
3314                 buf.lb_len = 1;
3315                 rc = osd_xattr_set(env, dt, &buf,
3316                                    LL_XATTR_NAME_ENCRYPTION_CONTEXT,
3317                                    0, handle);
3318                 if (rc)
3319                         CWARN("%s: set "DFID" enc ctx failed: rc = %d\n",
3320                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
3321                               rc);
3322         }
3323
3324         /* Let's check if there are extra flags need to be set into LMA */
3325         if (attr->la_flags & LUSTRE_LMA_FL_MASKS) {
3326                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
3327
3328                 LASSERT(!obj->oo_pfid_in_lma);
3329
3330                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
3331                                  &info->oti_ost_attrs);
3332                 if (rc)
3333                         GOTO(out, rc);
3334
3335                 if ((lma->lma_incompat & lustre_to_lma_flags(attr->la_flags)) ==
3336                     lustre_to_lma_flags(attr->la_flags))
3337                         /* if lma incompat already has the flags,
3338                          * save a useless call to xattr_set
3339                          */
3340                         GOTO(out, rc = 0);
3341
3342                 lma->lma_incompat |=
3343                         lustre_to_lma_flags(attr->la_flags);
3344                 lustre_lma_swab(lma);
3345
3346                 osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3347
3348                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA,
3349                                      lma, sizeof(*lma), XATTR_REPLACE);
3350                 if (rc != 0)
3351                         CWARN("%s: set "DFID" lma flags %u failed: rc = %d\n",
3352                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
3353                               lma->lma_incompat, rc);
3354                 else
3355                         obj->oo_lma_flags =
3356                                 attr->la_flags & LUSTRE_LMA_FL_MASKS;
3357                 osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
3358         }
3359
3360 out:
3361         return rc;
3362 }
3363
3364 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
3365                                            struct osd_object *obj,
3366                                            const char *name, const int namelen)
3367 {
3368         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
3369 }
3370
3371 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
3372                       umode_t mode, struct dt_allocation_hint *hint,
3373                       struct thandle *th, struct lu_attr *attr)
3374 {
3375         int result;
3376         struct osd_device *osd = osd_obj2dev(obj);
3377         struct osd_thandle *oth;
3378         struct dt_object *parent = NULL;
3379         struct inode *inode;
3380         struct iattr iattr = {
3381                 .ia_valid = ATTR_UID | ATTR_GID |
3382                             ATTR_CTIME | ATTR_MTIME | ATTR_ATIME,
3383                 .ia_ctime.tv_sec = attr->la_ctime,
3384                 .ia_mtime.tv_sec = attr->la_mtime,
3385                 .ia_atime.tv_sec = attr->la_atime,
3386                 .ia_uid = GLOBAL_ROOT_UID,
3387                 .ia_gid = GLOBAL_ROOT_GID,
3388         };
3389         const struct osd_timespec omit = { .tv_nsec = UTIME_OMIT };
3390
3391         if (attr->la_valid & LA_UID)
3392                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3393         if (attr->la_valid & LA_GID)
3394                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3395
3396         LINVRNT(osd_invariant(obj));
3397         LASSERT(obj->oo_inode == NULL);
3398         LASSERT(obj->oo_hl_head == NULL);
3399
3400         if (S_ISDIR(mode) && ldiskfs_pdo) {
3401                 obj->oo_hl_head =
3402                         ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
3403                 if (obj->oo_hl_head == NULL)
3404                         return -ENOMEM;
3405         }
3406
3407         oth = container_of(th, struct osd_thandle, ot_super);
3408         LASSERT(oth->ot_handle->h_transaction != NULL);
3409
3410         if (hint != NULL && hint->dah_parent != NULL &&
3411             !dt_object_remote(hint->dah_parent))
3412                 parent = hint->dah_parent;
3413
3414         /* if a time component is not valid set it to UTIME_OMIT */
3415         if (!(attr->la_valid & LA_CTIME))
3416                 iattr.ia_ctime = omit;
3417         if (!(attr->la_valid & LA_MTIME))
3418                 iattr.ia_mtime = omit;
3419         if (!(attr->la_valid & LA_ATIME))
3420                 iattr.ia_atime = omit;
3421
3422         inode = ldiskfs_create_inode(oth->ot_handle,
3423                                      parent ? osd_dt_obj(parent)->oo_inode :
3424                                               osd_sb(osd)->s_root->d_inode,
3425                                      mode, &iattr);
3426         if (!IS_ERR(inode)) {
3427                 /* Do not update file c/mtime in ldiskfs. */
3428                 inode->i_flags |= S_NOCMTIME;
3429
3430                 /*
3431                  * For new created object, it must be consistent,
3432                  * and it is unnecessary to scrub against it.
3433                  */
3434                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
3435
3436                 obj->oo_inode = inode;
3437                 result = 0;
3438         } else {
3439                 if (obj->oo_hl_head != NULL) {
3440                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
3441                         obj->oo_hl_head = NULL;
3442                 }
3443                 result = PTR_ERR(inode);
3444         }
3445         LINVRNT(osd_invariant(obj));
3446         return result;
3447 }
3448
3449 enum {
3450         OSD_NAME_LEN = 255
3451 };
3452
3453 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
3454                      struct lu_attr *attr,
3455                      struct dt_allocation_hint *hint,
3456                      struct dt_object_format *dof,
3457                      struct thandle *th)
3458 {
3459         int result;
3460         struct osd_thandle *oth;
3461         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX | S_ISGID));
3462
3463         LASSERT(S_ISDIR(attr->la_mode));
3464
3465         oth = container_of(th, struct osd_thandle, ot_super);
3466         LASSERT(oth->ot_handle->h_transaction != NULL);
3467         if (fid_is_namespace_visible(lu_object_fid(&obj->oo_dt.do_lu)))
3468                 obj->oo_dirent_count = 0;
3469         result = osd_mkfile(info, obj, mode, hint, th, attr);
3470
3471         return result;
3472 }
3473
3474 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
3475                         struct lu_attr *attr,
3476                         struct dt_allocation_hint *hint,
3477                         struct dt_object_format *dof,
3478                         struct thandle *th)
3479 {
3480         int result;
3481         struct osd_thandle *oth;
3482         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
3483
3484         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
3485
3486         LASSERT(S_ISREG(attr->la_mode));
3487
3488         oth = container_of(th, struct osd_thandle, ot_super);
3489         LASSERT(oth->ot_handle->h_transaction != NULL);
3490
3491         result = osd_mkfile(info, obj, mode, hint, th, attr);
3492         if (result == 0) {
3493                 LASSERT(obj->oo_inode != NULL);
3494                 if (feat->dif_flags & DT_IND_VARKEY)
3495                         result = iam_lvar_create(obj->oo_inode,
3496                                                  feat->dif_keysize_max,
3497                                                  feat->dif_ptrsize,
3498                                                  feat->dif_recsize_max,
3499                                                  oth->ot_handle);
3500                 else
3501                         result = iam_lfix_create(obj->oo_inode,
3502                                                  feat->dif_keysize_max,
3503                                                  feat->dif_ptrsize,
3504                                                  feat->dif_recsize_max,
3505                                                  oth->ot_handle);
3506         }
3507         return result;
3508 }
3509
3510 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
3511                      struct lu_attr *attr,
3512                      struct dt_allocation_hint *hint,
3513                      struct dt_object_format *dof,
3514                      struct thandle *th)
3515 {
3516         LASSERT(S_ISREG(attr->la_mode));
3517         return osd_mkfile(info, obj, (attr->la_mode &
3518                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3519                           attr);
3520 }
3521
3522 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
3523                      struct lu_attr *attr,
3524                      struct dt_allocation_hint *hint,
3525                      struct dt_object_format *dof,
3526                      struct thandle *th)
3527 {
3528         LASSERT(S_ISLNK(attr->la_mode));
3529         return osd_mkfile(info, obj, (attr->la_mode &
3530                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3531                           attr);
3532 }
3533
3534 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
3535                      struct lu_attr *attr,
3536                      struct dt_allocation_hint *hint,
3537                      struct dt_object_format *dof,
3538                      struct thandle *th)
3539 {
3540         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
3541         int result;
3542
3543         LINVRNT(osd_invariant(obj));
3544         LASSERT(obj->oo_inode == NULL);
3545         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
3546                 S_ISFIFO(mode) || S_ISSOCK(mode));
3547
3548         result = osd_mkfile(info, obj, mode, hint, th, attr);
3549         if (result == 0) {
3550                 LASSERT(obj->oo_inode != NULL);
3551                 /*
3552                  * This inode should be marked dirty for i_rdev.  Currently
3553                  * that is done in the osd_attr_init().
3554                  */
3555                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
3556                                    attr->la_rdev);
3557         }
3558         LINVRNT(osd_invariant(obj));
3559         return result;
3560 }
3561
3562 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
3563                               struct lu_attr *,
3564                               struct dt_allocation_hint *hint,
3565                               struct dt_object_format *dof,
3566                               struct thandle *);
3567
3568 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
3569 {
3570         osd_obj_type_f result;
3571
3572         switch (type) {
3573         case DFT_DIR:
3574                 result = osd_mkdir;
3575                 break;
3576         case DFT_REGULAR:
3577                 result = osd_mkreg;
3578                 break;
3579         case DFT_SYM:
3580                 result = osd_mksym;
3581                 break;
3582         case DFT_NODE:
3583                 result = osd_mknod;
3584                 break;
3585         case DFT_INDEX:
3586                 result = osd_mk_index;
3587                 break;
3588
3589         default:
3590                 LBUG();
3591                 break;
3592         }
3593         return result;
3594 }
3595
3596 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
3597                         struct dt_object *parent, struct dt_object *child,
3598                         umode_t child_mode)
3599 {
3600         LASSERT(ah);
3601
3602         ah->dah_parent = parent;
3603
3604         if (parent != NULL && !dt_object_remote(parent)) {
3605                 /* will help to find FID->ino at dt_insert("..") */
3606                 struct osd_object *pobj = osd_dt_obj(parent);
3607
3608                 osd_idc_find_and_init(env, osd_obj2dev(pobj), pobj);
3609         }
3610 }
3611
3612 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
3613                           struct lu_attr *attr, struct dt_object_format *dof,
3614                           struct thandle *handle)
3615 {
3616         struct inode *inode = obj->oo_inode;
3617         __u64 valid = attr->la_valid;
3618         int result;
3619
3620         attr->la_valid &= ~(LA_TYPE | LA_MODE);
3621
3622         if (dof->dof_type != DFT_NODE)
3623                 attr->la_valid &= ~LA_RDEV;
3624         if ((valid & LA_ATIME) && (attr->la_atime == inode->i_atime.tv_sec))
3625                 attr->la_valid &= ~LA_ATIME;
3626         if ((valid & LA_CTIME) && (attr->la_ctime == inode->i_ctime.tv_sec))
3627                 attr->la_valid &= ~LA_CTIME;
3628         if ((valid & LA_MTIME) && (attr->la_mtime == inode->i_mtime.tv_sec))
3629                 attr->la_valid &= ~LA_MTIME;
3630
3631         result = osd_quota_transfer(inode, attr, handle);
3632         if (result)
3633                 return;
3634
3635         if (attr->la_valid != 0) {
3636                 result = osd_inode_setattr(info->oti_env, inode, attr);
3637                 /*
3638                  * The osd_inode_setattr() should always succeed here.  The
3639                  * only error that could be returned is EDQUOT when we are
3640                  * trying to change the UID or GID of the inode. However, this
3641                  * should not happen since quota enforcement is no longer
3642                  * enabled on ldiskfs (lquota takes care of it).
3643                  */
3644                 LASSERTF(result == 0, "%d\n", result);
3645                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3646         }
3647
3648         attr->la_valid = valid;
3649 }
3650
3651 /**
3652  * Helper function for osd_create()
3653  *
3654  * \retval 0, on success
3655  */
3656 static int __osd_create(struct osd_thread_info *info, struct osd_object *obj,
3657                         struct lu_attr *attr, struct dt_allocation_hint *hint,
3658                         struct dt_object_format *dof, struct thandle *th)
3659 {
3660         int result;
3661         __u32 umask;
3662
3663         osd_trans_exec_op(info->oti_env, th, OSD_OT_CREATE);
3664
3665         /* we drop umask so that permissions we pass are not affected */
3666         umask = current->fs->umask;
3667         current->fs->umask = 0;
3668
3669         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
3670                                                   th);
3671         if (likely(obj->oo_inode != NULL)) {
3672                 LASSERT(obj->oo_inode->i_state & I_NEW);
3673
3674                 /*
3675                  * Unlock the inode before attr initialization to avoid
3676                  * unnecessary dqget operations. LU-6378
3677                  */
3678                 unlock_new_inode(obj->oo_inode);
3679         }
3680
3681         if (likely(result == 0)) {
3682                 osd_attr_init(info, obj, attr, dof, th);
3683                 osd_object_init0(obj);
3684         }
3685
3686         /* restore previous umask value */
3687         current->fs->umask = umask;
3688
3689         osd_trans_exec_check(info->oti_env, th, OSD_OT_CREATE);
3690
3691         return result;
3692 }
3693
3694 /**
3695  * Helper function for osd_create()
3696  *
3697  * \retval 0, on success
3698  */
3699 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
3700                            const struct lu_fid *fid, struct thandle *th)
3701 {
3702         struct osd_thread_info *info = osd_oti_get(env);
3703         struct osd_inode_id    *id   = &info->oti_id;
3704         struct osd_device      *osd  = osd_obj2dev(obj);
3705         struct osd_thandle     *oh;
3706         int rc;
3707
3708         LASSERT(obj->oo_inode != NULL);
3709
3710         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_OI_ENOSPC))
3711                 return -ENOSPC;
3712
3713         oh = container_of(th, struct osd_thandle, ot_super);
3714         LASSERT(oh->ot_handle);
3715         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3716
3717         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
3718         rc = osd_oi_insert(info, osd, fid, id, oh->ot_handle,
3719                            OI_CHECK_FLD, NULL);
3720         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP) && osd->od_is_ost) {
3721                 struct lu_fid next_fid = *fid;
3722
3723                 /* insert next object in advance, and map to the same inode */
3724                 next_fid.f_oid++;
3725                 if (next_fid.f_oid != 0) {
3726                         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3727                         osd_oi_insert(info, osd, &next_fid, id, oh->ot_handle,
3728                                       OI_CHECK_FLD, NULL);
3729                         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3730                 }
3731         }
3732
3733         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3734
3735         return rc;
3736 }
3737
3738 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
3739                    u64 seq, struct lu_seq_range *range)
3740 {
3741         struct seq_server_site *ss = osd_seq_site(osd);
3742
3743         if (fid_seq_is_idif(seq)) {
3744                 fld_range_set_ost(range);
3745                 range->lsr_index = idif_ost_idx(seq);
3746                 return 0;
3747         }
3748
3749         if (!fid_seq_in_fldb(seq)) {
3750                 fld_range_set_mdt(range);
3751                 if (ss != NULL)
3752                         /*
3753                          * FIXME: If ss is NULL, it suppose not get lsr_index
3754                          * at all
3755                          */
3756                         range->lsr_index = ss->ss_node_id;
3757                 return 0;
3758         }
3759
3760         LASSERT(ss != NULL);
3761         fld_range_set_any(range);
3762         /* OSD will only do local fld lookup */
3763         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
3764 }
3765
3766 static int osd_declare_create(const struct lu_env *env, struct dt_object *dt,
3767                               struct lu_attr *attr,
3768                               struct dt_allocation_hint *hint,
3769                               struct dt_object_format *dof,
3770                               struct thandle *handle)
3771 {
3772         struct osd_thandle *oh;
3773         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3774         int credits;
3775         int rc;
3776
3777         ENTRY;
3778
3779         LASSERT(handle != NULL);
3780
3781         oh = container_of(handle, struct osd_thandle, ot_super);
3782         LASSERT(oh->ot_handle == NULL);
3783
3784         if (osd_tx_was_declared(env, oh, dt, DTO_OBJECT_CREATE, 0))
3785                 RETURN(0);
3786
3787         /*
3788          * EA object consumes more credits than regular object: osd_mk_index
3789          * vs. osd_mkreg: osd_mk_index will create 2 blocks for root_node and
3790          * leaf_node, could involves the block, block bitmap, groups, GDT
3791          * change for each block, so add 4 * 2 credits in that case.
3792          *
3793          * The default ACL initialization may consume an additional 16 blocks
3794          */
3795         credits = osd_dto_credits_noquota[DTO_OBJECT_CREATE] +
3796                   ((dof->dof_type == DFT_INDEX) ? 4 * 2 : 0);
3797
3798         /**
3799          * While ldiskfs_new_inode() calls ldiskfs_init_acl() we have to add
3800          * credits for possible default ACL creation in new inode
3801          */
3802         if (hint && hint->dah_acl_len)
3803                 credits += osd_calc_bkmap_credits(sb, NULL, 0, -1,
3804                                 (hint->dah_acl_len + sb->s_blocksize - 1) >>
3805                                 sb->s_blocksize_bits);
3806
3807         osd_trans_declare_op(env, oh, OSD_OT_CREATE, credits);
3808
3809         /*
3810          * Reuse idle OI block may cause additional one OI block
3811          * to be changed.
3812          */
3813         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3814                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3815         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP))
3816                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3817                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3818
3819         /* will help to find FID->ino mapping at dt_insert() */
3820         rc = osd_idc_find_and_init(env, osd_obj2dev(osd_dt_obj(dt)),
3821                                    osd_dt_obj(dt));
3822         if (rc != 0)
3823                 RETURN(rc);
3824
3825         if (!attr)
3826                 RETURN(0);
3827
3828         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid,
3829                                    attr->la_projid, 1, oh, osd_dt_obj(dt),
3830                                    NULL, OSD_QID_INODE);
3831         if (rc != 0)
3832                 RETURN(rc);
3833
3834         RETURN(rc);
3835 }
3836
3837 /**
3838  * Called to destroy on-disk representation of the object
3839  *
3840  * Concurrency: must be locked
3841  */
3842 static int osd_declare_destroy(const struct lu_env *env, struct dt_object *dt,
3843                                struct thandle *th)
3844 {
3845         struct osd_object *obj = osd_dt_obj(dt);
3846         struct inode *inode = obj->oo_inode;
3847         struct osd_thandle *oh;
3848         int rc;
3849
3850         ENTRY;
3851
3852         if (inode == NULL)
3853                 RETURN(-ENOENT);
3854
3855         oh = container_of(th, struct osd_thandle, ot_super);
3856         LASSERT(oh->ot_handle == NULL);
3857
3858         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
3859                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
3860
3861         /* For removing agent entry */
3862         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu))
3863                 oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
3864
3865         /*
3866          * Recycle idle OI leaf may cause additional three OI blocks
3867          * to be changed.
3868          */
3869         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3870                 osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3871                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
3872         /* one less inode */
3873         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3874                                    i_projid_read(inode), -1, oh, obj, NULL,
3875                                    OSD_QID_INODE);
3876         if (rc)
3877                 RETURN(rc);
3878         /* data to be truncated */
3879         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3880                                    i_projid_read(inode), 0, oh, obj, NULL,
3881                                    OSD_QID_BLK);
3882         if (rc)
3883                 RETURN(rc);
3884
3885         /*
3886          * will help to find FID->ino when this object is being
3887          * added to PENDING
3888          */
3889         rc = osd_idc_find_and_init(env, osd_obj2dev(obj), obj);
3890
3891         RETURN(rc);
3892 }
3893
3894 static int osd_destroy(const struct lu_env *env, struct dt_object *dt,
3895                        struct thandle *th)
3896 {
3897         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3898         struct osd_object *obj = osd_dt_obj(dt);
3899         struct inode *inode = obj->oo_inode;
3900         struct osd_device *osd = osd_obj2dev(obj);
3901         struct osd_thandle *oh;
3902         int result;
3903
3904         ENTRY;
3905
3906         oh = container_of(th, struct osd_thandle, ot_super);
3907         LASSERT(oh->ot_handle);
3908         LASSERT(inode);
3909         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
3910
3911         if (unlikely(fid_is_acct(fid)))
3912                 RETURN(-EPERM);
3913
3914         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu)) {
3915                 result = osd_delete_from_remote_parent(env, osd, obj, oh, true);
3916                 if (result != 0)
3917                         CERROR("%s: remove agent entry "DFID": rc = %d\n",
3918                                osd_name(osd), PFID(fid), result);
3919         }
3920
3921         if (S_ISDIR(inode->i_mode)) {
3922                 if (inode->i_nlink > 2)
3923                         CERROR("%s: directory "DFID" ino %lu link count is %u at unlink. run e2fsck to repair\n",
3924                                osd_name(osd), PFID(fid), inode->i_ino,
3925                                inode->i_nlink);
3926
3927                 spin_lock(&obj->oo_guard);
3928                 clear_nlink(inode);
3929                 spin_unlock(&obj->oo_guard);
3930                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3931         }
3932
3933         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
3934
3935         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
3936
3937         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3938                 result = osd_oi_delete(osd_oti_get(env), osd, fid,
3939                                        oh->ot_handle, OI_CHECK_FLD);
3940
3941         osd_trans_exec_check(env, th, OSD_OT_DESTROY);
3942         /* XXX: add to ext3 orphan list */
3943         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
3944
3945         /* not needed in the cache anymore */
3946         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
3947         obj->oo_destroyed = 1;
3948
3949         RETURN(0);
3950 }
3951
3952 /**
3953  * Put the fid into lustre_mdt_attrs, and then place the structure
3954  * inode's ea. This fid should not be altered during the life time
3955  * of the inode.
3956  *
3957  * \retval +ve, on success
3958  * \retval -ve, on error
3959  *
3960  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
3961  */
3962 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
3963                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
3964 {
3965         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
3966         struct lustre_mdt_attrs *lma = &loa->loa_lma;
3967         int rc;
3968
3969         ENTRY;
3970
3971         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
3972                 RETURN(0);
3973
3974         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_OST_EA_FID_SET))
3975                 rc = -ENOMEM;
3976
3977         lustre_loa_init(loa, fid, compat, incompat);
3978         lustre_loa_swab(loa, false);
3979
3980         /*
3981          * For the OST device with 256 bytes inode size by default,
3982          * the PFID EA will be stored together with LMA EA to avoid
3983          * performance trouble. Otherwise the PFID EA can be stored
3984          * independently. LU-8998
3985          */
3986         if ((compat & LMAC_FID_ON_OST) &&
3987             LDISKFS_INODE_SIZE(inode->i_sb) <= 256)
3988                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3989                                      sizeof(*loa), XATTR_CREATE);
3990         else
3991                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3992                                      sizeof(*lma), XATTR_CREATE);
3993         /*
3994          * LMA may already exist, but we need to check that all the
3995          * desired compat/incompat flags have been added.
3996          */
3997         if (unlikely(rc == -EEXIST)) {
3998                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
3999                                      XATTR_NAME_LMA, (void *)loa, sizeof(*loa));
4000                 if (rc < 0)
4001                         RETURN(rc);
4002
4003                 if (rc < sizeof(*lma))
4004                         RETURN(-EINVAL);
4005
4006                 lustre_loa_swab(loa, true);
4007                 if (lu_fid_eq(fid, &lma->lma_self_fid) &&
4008                     ((compat == 0 && incompat == 0) ||
4009                      (!(~lma->lma_compat & compat) &&
4010                       !(~lma->lma_incompat & incompat))))
4011                         RETURN(0);
4012
4013                 lma->lma_self_fid = *fid;
4014                 lma->lma_compat |= compat;
4015                 lma->lma_incompat |= incompat;
4016                 if (rc == sizeof(*lma)) {
4017                         lustre_lma_swab(lma);
4018                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4019                                              sizeof(*lma), XATTR_REPLACE);
4020                 } else {
4021                         lustre_loa_swab(loa, false);
4022                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
4023                                              sizeof(*loa), XATTR_REPLACE);
4024                 }
4025         }
4026
4027         RETURN(rc);
4028 }
4029
4030 /**
4031  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
4032  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
4033  * To have compatilibility with 1.8 ldiskfs driver we need to have
4034  * magic number at start of fid data.
4035  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
4036  * its inmemory API.
4037  */
4038 static void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
4039                                          const struct lu_fid *fid)
4040 {
4041         if (!fid_is_namespace_visible(fid) ||
4042             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
4043                 param->edp_magic = 0;
4044                 return;
4045         }
4046
4047         param->edp_magic = LDISKFS_LUFID_MAGIC;
4048         param->edp_len =  sizeof(struct lu_fid) + 1;
4049         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
4050 }
4051
4052 /**
4053  * Try to read the fid from inode ea into dt_rec.
4054  *
4055  * \param fid object fid.
4056  *
4057  * \retval 0 on success
4058  */
4059 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
4060                           __u32 ino, struct lu_fid *fid,
4061                           struct osd_inode_id *id)
4062 {
4063         struct osd_thread_info *info  = osd_oti_get(env);
4064         struct inode *inode;
4065
4066         ENTRY;
4067
4068         osd_id_gen(id, ino, OSD_OII_NOGEN);
4069         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
4070         if (IS_ERR(inode))
4071                 RETURN(PTR_ERR(inode));
4072
4073         iput(inode);
4074         RETURN(0);
4075 }
4076
4077 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
4078                                         struct inode *dir,
4079                                         struct inode *parent_dir,
4080                                         const struct lu_fid *dot_fid,
4081                                         const struct lu_fid *dot_dot_fid,
4082                                         struct osd_thandle *oth)
4083 {
4084         struct ldiskfs_dentry_param *dot_ldp;
4085         struct ldiskfs_dentry_param *dot_dot_ldp;
4086         __u32 saved_nlink = dir->i_nlink;
4087         int rc;
4088
4089         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_DOTDOT_ENOSPC))
4090                 return -ENOSPC;
4091
4092         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
4093         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
4094
4095         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
4096         dot_ldp->edp_magic = 0;
4097
4098         rc = ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
4099                                     dir, dot_ldp, dot_dot_ldp);
4100         /*
4101          * The ldiskfs_add_dot_dotdot() may dir->i_nlink as 2, then
4102          * the subseqent ref_add() will increase the dir->i_nlink
4103          * as 3. That is incorrect for new created directory.
4104          *
4105          * It looks like hack, because we want to make the OSD API
4106          * to be order-independent for new created directory object
4107          * between dt_insert(..) and ref_add() operations.
4108          *
4109          * Here, we only restore the in-RAM dir-inode's nlink attr,
4110          * becuase if the nlink attr is not 2, then there will be
4111          * ref_add() called following the dt_insert(..), such call
4112          * will make both the in-RAM and on-disk dir-inode's nlink
4113          * attr to be set as 2. LU-7447
4114          */
4115         set_nlink(dir, saved_nlink);
4116         return rc;
4117 }
4118
4119 /**
4120  * Create an local agent inode for remote entry
4121  */
4122 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
4123                                                   struct osd_device *osd,
4124                                                   struct osd_object *pobj,
4125                                                   const struct lu_fid *fid,
4126                                                   __u32 type,
4127                                                   struct thandle *th)
4128 {
4129         struct osd_thread_info *info = osd_oti_get(env);
4130         struct inode *local;
4131         struct osd_thandle *oh;
4132         struct iattr iattr = {
4133                 .ia_valid = ATTR_UID | ATTR_GID |
4134                             ATTR_CTIME | ATTR_MTIME | ATTR_ATIME,
4135                 .ia_ctime.tv_nsec = UTIME_OMIT,
4136                 .ia_mtime.tv_nsec = UTIME_OMIT,
4137                 .ia_atime.tv_nsec = UTIME_OMIT,
4138                 .ia_uid = GLOBAL_ROOT_UID,
4139                 .ia_gid = GLOBAL_ROOT_GID,
4140         };
4141         int rc;
4142
4143         ENTRY;
4144
4145         LASSERT(th);
4146         oh = container_of(th, struct osd_thandle, ot_super);
4147         LASSERT(oh->ot_handle->h_transaction != NULL);
4148
4149         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode,
4150                                      type, &iattr);
4151         if (IS_ERR(local)) {
4152                 CERROR("%s: create local error %d\n", osd_name(osd),
4153                        (int)PTR_ERR(local));
4154                 RETURN(local);
4155         }
4156
4157         /*
4158          * restore i_gid in case S_ISGID is set, we will inherit S_ISGID and set
4159          * correct gid on remote file, not agent here
4160          */
4161         local->i_gid = current_fsgid();
4162         ldiskfs_set_inode_state(local, LDISKFS_STATE_LUSTRE_NOSCRUB);
4163
4164         /* e2fsck doesn't like empty symlinks.  Store remote FID as symlink.
4165          * That gives e2fsck something to look at and be happy, and allows
4166          * debugging if we need to determine where this symlink came from.
4167          */
4168         if (S_ISLNK(type)) {
4169                 BUILD_BUG_ON(LDISKFS_N_BLOCKS * 4 < FID_LEN + 1);
4170                 ldiskfs_clear_inode_flag(local, LDISKFS_INODE_EXTENTS);
4171                 rc = scnprintf((char *)LDISKFS_I(local)->i_data,
4172                                LDISKFS_N_BLOCKS * 4, DFID, PFID(fid));
4173
4174                 i_size_write(local, rc);
4175                 LDISKFS_I(local)->i_disksize = rc;
4176         }
4177         unlock_new_inode(local);
4178
4179         /* Agent inode should not have project ID */
4180 #ifdef  HAVE_PROJECT_QUOTA
4181         if (LDISKFS_I(pobj->oo_inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
4182             i_projid_read(pobj->oo_inode) != 0) {
4183                 rc = osd_transfer_project(local, 0, th);
4184                 if (rc) {
4185                         CERROR("%s: quota transfer failed:. Is project quota enforcement enabled on the ldiskfs filesystem? rc = %d\n",
4186                                osd_ino2name(local), rc);
4187                         RETURN(ERR_PTR(rc));
4188                 }
4189         }
4190 #endif
4191         /* Set special LMA flag for local agent inode */
4192         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
4193         if (rc != 0) {
4194                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
4195                        osd_name(osd), PFID(fid), rc);
4196                 RETURN(ERR_PTR(rc));
4197         }
4198
4199         if (!S_ISDIR(type))
4200                 RETURN(local);
4201
4202         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode, fid,
4203                                          lu_object_fid(&pobj->oo_dt.do_lu),
4204                                          oh);
4205         if (rc != 0) {
4206                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
4207                         osd_name(osd), PFID(fid), rc);
4208                 RETURN(ERR_PTR(rc));
4209         }
4210
4211         RETURN(local);
4212 }
4213
4214 /**
4215  * when direntry is deleted, we have to take care of possible agent inode
4216  * referenced by that. unfortunately we can't do this at that point:
4217  * iget() within a running transaction leads to deadlock and we better do
4218  * not call that every delete declaration to save performance. so we put
4219  * a potention agent inode on a list and process that once the transaction
4220  * is over. Notice it's not any worse in terms of real orphans as regular
4221  * object destroy doesn't put inodes on the on-disk orphan list. this should
4222  * be addressed separately
4223  */
4224 static int osd_schedule_agent_inode_removal(const struct lu_env *env,
4225                                             struct osd_thandle *oh,
4226                                             __u32 ino)
4227 {
4228         struct osd_device *osd = osd_dt_dev(oh->ot_super.th_dev);
4229         struct osd_obj_orphan *oor;
4230
4231         OBD_ALLOC_PTR(oor);
4232         if (oor == NULL)
4233                 return -ENOMEM;
4234
4235         oor->oor_ino = ino;
4236         oor->oor_env = (struct lu_env *)env;
4237         spin_lock(&osd->od_osfs_lock);
4238         list_add(&oor->oor_list, &osd->od_orphan_list);
4239         spin_unlock(&osd->od_osfs_lock);
4240
4241         oh->ot_remove_agents = 1;
4242
4243         return 0;
4244
4245 }
4246
4247 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
4248                                                 struct osd_device *osd)
4249 {
4250         struct osd_thread_info *info = osd_oti_get(env);
4251         struct osd_obj_orphan *oor, *tmp;
4252         struct osd_inode_id id;
4253         LIST_HEAD(list);
4254         struct inode *inode;
4255         struct lu_fid fid;
4256         handle_t *jh;
4257         __u32 ino;
4258
4259         spin_lock(&osd->od_osfs_lock);
4260         list_for_each_entry_safe(oor, tmp, &osd->od_orphan_list, oor_list) {
4261                 if (oor->oor_env == env)
4262                         list_move(&oor->oor_list, &list);
4263         }
4264         spin_unlock(&osd->od_osfs_lock);
4265
4266         list_for_each_entry_safe(oor, tmp, &list, oor_list) {
4267
4268                 ino = oor->oor_ino;
4269
4270                 list_del(&oor->oor_list);
4271                 OBD_FREE_PTR(oor);
4272
4273                 osd_id_gen(&id, ino, OSD_OII_NOGEN);
4274                 inode = osd_iget_fid(info, osd, &id, &fid);
4275                 if (IS_ERR(inode))
4276                         continue;
4277
4278                 if (!osd_remote_fid(env, osd, &fid)) {
4279                         iput(inode);
4280                         continue;
4281                 }
4282
4283                 jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC, 1);
4284                 clear_nlink(inode);
4285                 mark_inode_dirty(inode);
4286                 ldiskfs_journal_stop(jh);
4287                 iput(inode);
4288         }
4289
4290         return 0;
4291 }
4292
4293 /**
4294  * OSD layer object create function for OST objects (b=11826).
4295  *
4296  * The FID is inserted into inode xattr here.
4297  *
4298  * \retval   0, on success
4299  * \retval -ve, on error
4300  */
4301 static int osd_create(const struct lu_env *env, struct dt_object *dt,
4302                       struct lu_attr *attr, struct dt_allocation_hint *hint,
4303                       struct dt_object_format *dof, struct thandle *th)
4304 {
4305         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4306         struct osd_object *obj = osd_dt_obj(dt);
4307         struct osd_thread_info *info = osd_oti_get(env);
4308         int result, on_ost = 0;
4309
4310         ENTRY;
4311
4312         if (dt_object_exists(dt))
4313                 RETURN(-EEXIST);
4314
4315         LINVRNT(osd_invariant(obj));
4316         LASSERT(!dt_object_remote(dt));
4317         LASSERT(osd_is_write_locked(env, obj));
4318         LASSERT(th != NULL);
4319
4320         if (unlikely(fid_is_acct(fid)))
4321                 /*
4322                  * Quota files can't be created from the kernel any more,
4323                  * 'tune2fs -O quota' will take care of creating them
4324                  */
4325                 RETURN(-EPERM);
4326
4327         result = __osd_create(info, obj, attr, hint, dof, th);
4328         if (result == 0) {
4329                 if (fid_is_idif(fid) &&
4330                     !osd_dev(dt->do_lu.lo_dev)->od_index_in_idif) {
4331                         struct lu_fid *tfid = &info->oti_fid;
4332                         struct ost_id *oi   = &info->oti_ostid;
4333
4334                         fid_to_ostid(fid, oi);
4335                         ostid_to_fid(tfid, oi, 0);
4336                         on_ost = 1;
4337                         result = osd_ea_fid_set(info, obj->oo_inode, tfid,
4338                                                 LMAC_FID_ON_OST, 0);
4339                 } else {
4340                         on_ost = fid_is_on_ost(info, osd_obj2dev(obj),
4341                                                fid, OI_CHECK_FLD);
4342                         result = osd_ea_fid_set(info, obj->oo_inode, fid,
4343                                                 on_ost ? LMAC_FID_ON_OST : 0,
4344                                                 0);
4345                 }
4346                 if (obj->oo_dt.do_body_ops == &osd_body_ops_new)
4347                         obj->oo_dt.do_body_ops = &osd_body_ops;
4348         }
4349
4350         if (!result && !CFS_FAIL_CHECK(OBD_FAIL_OSD_NO_OI_ENTRY)) {
4351                 struct inode *inode = obj->oo_inode;
4352
4353                 result = __osd_oi_insert(env, obj, fid, th);
4354                 if (result && inode) {
4355                         spin_lock(&obj->oo_guard);
4356                         clear_nlink(inode);
4357                         spin_unlock(&obj->oo_guard);
4358                         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4359                         ldiskfs_set_inode_state(inode,
4360                                                 LDISKFS_STATE_LUSTRE_DESTROY);
4361                         iput(inode);
4362                         obj->oo_inode = NULL;
4363                 }
4364         }
4365
4366         /*
4367          * a small optimization - dt_insert() isn't usually applied
4368          * to OST objects, so we don't need to cache OI mapping for
4369          * OST objects
4370          */
4371         if (result == 0 && on_ost == 0) {
4372                 struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4373
4374                 result = osd_idc_find_and_init(env, osd, obj);
4375                 LASSERT(result == 0);
4376         }
4377
4378         LASSERT(ergo(result == 0,
4379                      dt_object_exists(dt) && !dt_object_remote(dt)));
4380         LINVRNT(osd_invariant(obj));
4381         RETURN(result);
4382 }
4383
4384 static int osd_declare_ref_add(const struct lu_env *env, struct dt_object *dt,
4385                                struct thandle *handle)
4386 {
4387         struct osd_thandle *oh;
4388         int rc;
4389
4390         /* it's possible that object doesn't exist yet */
4391         LASSERT(handle != NULL);
4392
4393         oh = container_of(handle, struct osd_thandle, ot_super);
4394         LASSERT(oh->ot_handle == NULL);
4395
4396         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
4397                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4398
4399         rc = osd_idc_find_and_init(env, osd_dev(dt->do_lu.lo_dev),
4400                                    osd_dt_obj(dt));
4401
4402         return rc;
4403 }
4404
4405 /*
4406  * Concurrency: @dt is write locked.
4407  */
4408 static int osd_ref_add(const struct lu_env *env, struct dt_object *dt,
4409                        struct thandle *th)
4410 {
4411         struct osd_object *obj = osd_dt_obj(dt);
4412         struct inode *inode = obj->oo_inode;
4413         struct osd_thandle *oh;
4414         int rc = 0;
4415
4416         if (!dt_object_exists(dt) || obj->oo_destroyed)
4417                 return -ENOENT;
4418
4419         LINVRNT(osd_invariant(obj));
4420         LASSERT(!dt_object_remote(dt));
4421         LASSERT(osd_is_write_locked(env, obj));
4422         LASSERT(th != NULL);
4423
4424         oh = container_of(th, struct osd_thandle, ot_super);
4425         LASSERT(oh->ot_handle != NULL);
4426
4427         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
4428
4429         CDEBUG(D_INODE, DFID" increase nlink %d\n",
4430                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4431         /*
4432          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
4433          * (65000) subdirectories by storing "1" in i_nlink if the link count
4434          * would otherwise overflow. Directory tranversal tools understand
4435          * that (st_nlink == 1) indicates that the filesystem dose not track
4436          * hard links count on the directory, and will not abort subdirectory
4437          * scanning early once (st_nlink - 2) subdirs have been found.
4438          *
4439          * This also has to properly handle the case of inodes with nlink == 0
4440          * in case they are being linked into the PENDING directory
4441          */
4442         spin_lock(&obj->oo_guard);
4443         if (unlikely(inode->i_nlink == 0))
4444                 /* inc_nlink from 0 may cause WARN_ON */
4445                 set_nlink(inode, 1);
4446         else {
4447                 osd_ldiskfs_inc_count(oh->ot_handle, inode);
4448                 if (!S_ISDIR(inode->i_mode))
4449                         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
4450         }
4451         spin_unlock(&obj->oo_guard);
4452
4453         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4454         LINVRNT(osd_invariant(obj));
4455
4456         osd_trans_exec_check(env, th, OSD_OT_REF_ADD);
4457
4458         return rc;
4459 }
4460
4461 static int osd_declare_ref_del(const struct lu_env *env, struct dt_object *dt,
4462                                struct thandle *handle)
4463 {
4464         struct osd_thandle *oh;
4465
4466         if (!dt_object_exists(dt))
4467                 return -ENOENT;
4468
4469         LASSERT(!dt_object_remote(dt));
4470         LASSERT(handle != NULL);
4471
4472         oh = container_of(handle, struct osd_thandle, ot_super);
4473         LASSERT(oh->ot_handle == NULL);
4474
4475         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
4476                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4477
4478         return 0;
4479 }
4480
4481 /*
4482  * Concurrency: @dt is write locked.
4483  */
4484 static int osd_ref_del(const struct lu_env *env, struct dt_object *dt,
4485                        struct thandle *th)
4486 {
4487         struct osd_object *obj = osd_dt_obj(dt);
4488         struct inode *inode = obj->oo_inode;
4489         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4490         struct osd_thandle *oh;
4491
4492         if (!dt_object_exists(dt))
4493                 return -ENOENT;
4494
4495         LINVRNT(osd_invariant(obj));
4496         LASSERT(!dt_object_remote(dt));
4497         LASSERT(osd_is_write_locked(env, obj));
4498         LASSERT(th != NULL);
4499
4500         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_REF_DEL))
4501                 return -EIO;
4502
4503         oh = container_of(th, struct osd_thandle, ot_super);
4504         LASSERT(oh->ot_handle != NULL);
4505
4506         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
4507
4508         spin_lock(&obj->oo_guard);
4509         /*
4510          * That can be result of upgrade from old Lustre version and
4511          * applied only to local files.  Just skip this ref_del call.
4512          * ext4_unlink() only treats this as a warning, don't LASSERT here.
4513          */
4514         if (inode->i_nlink == 0) {
4515                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
4516                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
4517                              ", maybe an upgraded file? (LU-3915)\n",
4518                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
4519                 spin_unlock(&obj->oo_guard);
4520                 return 0;
4521         }
4522
4523         CDEBUG(D_INODE, DFID" decrease nlink %d\n",
4524                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4525
4526         osd_ldiskfs_dec_count(oh->ot_handle, inode);
4527         spin_unlock(&obj->oo_guard);
4528
4529         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4530         LINVRNT(osd_invariant(obj));
4531
4532         osd_trans_exec_check(env, th, OSD_OT_REF_DEL);
4533
4534         return 0;
4535 }
4536
4537 /*
4538  * Concurrency: @dt is read locked.
4539  */
4540 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
4541                          struct lu_buf *buf, const char *name)
4542 {
4543         struct osd_object      *obj    = osd_dt_obj(dt);
4544         struct inode           *inode  = obj->oo_inode;
4545         struct osd_thread_info *info   = osd_oti_get(env);
4546         struct dentry          *dentry = &info->oti_obj_dentry;
4547         bool cache_xattr = false;
4548         int rc;
4549
4550         LASSERT(buf);
4551
4552         /* version get is not real XATTR but uses xattr API */
4553         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4554                 dt_obj_version_t *ver = buf->lb_buf;
4555
4556                 /*
4557                  * for version we are just using xattr API but change inode
4558                  * field instead
4559                  */
4560                 if (buf->lb_len == 0)
4561                         return sizeof(dt_obj_version_t);
4562
4563                 if (buf->lb_len < sizeof(dt_obj_version_t))
4564                         return -ERANGE;
4565
4566                 CDEBUG(D_INODE, "Get version %#llx for inode %lu\n",
4567                        LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4568
4569                 *ver = LDISKFS_I(inode)->i_fs_version;
4570
4571                 return sizeof(dt_obj_version_t);
4572         }
4573
4574         if (!dt_object_exists(dt))
4575                 return -ENOENT;
4576
4577         LASSERT(!dt_object_remote(dt));
4578         LASSERT(inode->i_op != NULL);
4579 #ifdef HAVE_IOP_XATTR
4580         LASSERT(inode->i_op->getxattr != NULL);
4581 #endif
4582
4583         if (strcmp(name, XATTR_NAME_LOV) == 0 ||
4584             strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
4585                 cache_xattr = true;
4586
4587         if (cache_xattr) {
4588                 rc = osd_oxc_get(obj, name, buf);
4589                 if (rc != -ENOENT)
4590                         return rc;
4591         }
4592
4593         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4594                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4595                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4596                 struct filter_fid *ff;
4597                 struct ost_layout *ol;
4598
4599                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4600                 if (rc)
4601                         return rc;
4602
4603                 LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4604
4605                 rc = sizeof(*ff);
4606                 if (buf->lb_len == 0 || !buf->lb_buf)
4607                         return rc;
4608
4609                 if (buf->lb_len < rc)
4610                         return -ERANGE;
4611
4612                 ff = buf->lb_buf;
4613                 ol = &ff->ff_layout;
4614                 ol->ol_stripe_count = cpu_to_le32(loa->loa_parent_fid.f_ver >>
4615                                                   PFID_STRIPE_IDX_BITS);
4616                 ol->ol_stripe_size = cpu_to_le32(loa->loa_stripe_size);
4617                 loa->loa_parent_fid.f_ver &= PFID_STRIPE_COUNT_MASK;
4618                 fid_cpu_to_le(&ff->ff_parent, &loa->loa_parent_fid);
4619                 if (lma->lma_compat & LMAC_COMP_INFO) {
4620                         ol->ol_comp_start = cpu_to_le64(loa->loa_comp_start);
4621                         ol->ol_comp_end = cpu_to_le64(loa->loa_comp_end);
4622                         ol->ol_comp_id = cpu_to_le32(loa->loa_comp_id);
4623                 } else {
4624                         ol->ol_comp_start = 0;
4625                         ol->ol_comp_end = 0;
4626                         ol->ol_comp_id = 0;
4627                 }
4628         } else {
4629                 /* Get enc context xattr directly from ldiskfs instead of going
4630                  * through the VFS, as there is no xattr handler for
4631                  * "encryption.".
4632                  */
4633                 if (strcmp(name, LL_XATTR_NAME_ENCRYPTION_CONTEXT) == 0)
4634                         rc = ldiskfs_xattr_get(inode,
4635                                           LDISKFS_XATTR_INDEX_ENCRYPTION,
4636                                           LDISKFS_XATTR_NAME_ENCRYPTION_CONTEXT,
4637                                           buf->lb_buf, buf->lb_len);
4638                 else
4639                         rc = __osd_xattr_get(inode, dentry, name,
4640                                              buf->lb_buf, buf->lb_len);
4641         }
4642
4643         if (cache_xattr) {
4644                 if (rc == -ENOENT || rc == -ENODATA)
4645                         osd_oxc_add(obj, name, NULL, 0);
4646                 else if (rc > 0 && buf->lb_buf != NULL)
4647                         osd_oxc_add(obj, name, buf->lb_buf, rc);
4648         }
4649
4650         return rc;
4651 }
4652
4653 static int osd_declare_xattr_set(const struct lu_env *env,
4654                                  struct dt_object *dt,
4655                                  const struct lu_buf *buf, const char *name,
4656                                  int fl, struct thandle *handle)
4657 {
4658         struct osd_thandle *oh;
4659         int credits = 0;
4660         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4661
4662         LASSERT(handle != NULL);
4663
4664         oh = container_of(handle, struct osd_thandle, ot_super);
4665         LASSERT(oh->ot_handle == NULL);
4666
4667         if (strcmp(name, XATTR_NAME_LMA) == 0) {
4668                 /*
4669                  * For non-upgrading case, the LMA is set first and
4670                  * usually fit inode. But for upgrade case, the LMA
4671                  * may be in another separated EA block.
4672                  */
4673                 if (dt_object_exists(dt)) {
4674                         if (fl == LU_XATTR_REPLACE)
4675                                 credits = 1;
4676                         else
4677                                 goto upgrade;
4678                 }
4679         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4680                 credits = 1;
4681         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
4682                 /* We may need to delete the old PFID EA. */
4683                 credits = LDISKFS_MAXQUOTAS_DEL_BLOCKS(sb);
4684                 if (fl == LU_XATTR_REPLACE)
4685                         credits += 1;
4686                 else
4687                         goto upgrade;
4688         } else {
4689                 /*
4690                  * If some name entry resides on remote MDT, then will create
4691                  * agent entry under remote parent. On the other hand, if the
4692                  * remote entry will be removed, then related agent entry may
4693                  * need to be removed from the remote parent. So there may be
4694                  * kinds of cases, let's declare enough credits. The credits
4695                  * for create agent entry is enough for remove case.
4696                  */
4697                 if (strcmp(name, XATTR_NAME_LINK) == 0) {
4698                         credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
4699                         if (dt_object_exists(dt))
4700                                 credits += 1; /* For updating LMA */
4701                 }
4702
4703 upgrade:
4704                 credits += osd_dto_credits_noquota[DTO_XATTR_SET];
4705
4706                 if (buf != NULL) {
4707                         ssize_t buflen;
4708
4709                         if (buf->lb_buf == NULL && dt_object_exists(dt)) {
4710                                 /*
4711                                  * learn xattr size from osd_xattr_get if
4712                                  * attribute has not been read yet
4713                                  */
4714                                 buflen = __osd_xattr_get(
4715                                     osd_dt_obj(dt)->oo_inode,
4716                                     &osd_oti_get(env)->oti_obj_dentry,
4717                                     name, NULL, 0);
4718                                 if (buflen < 0)
4719                                         buflen = 0;
4720                         } else {
4721                                 buflen = buf->lb_len;
4722                         }
4723
4724                         if (buflen > sb->s_blocksize) {
4725                                 credits += osd_calc_bkmap_credits(
4726                                     sb, NULL, 0, -1,
4727                                     (buflen + sb->s_blocksize - 1) >>
4728                                     sb->s_blocksize_bits);
4729                         }
4730                 }
4731                 /*
4732                  * xattr set may involve inode quota change, reserve credits for
4733                  * dquot_initialize()
4734                  */
4735                 credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4736         }
4737
4738         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
4739
4740         return 0;
4741 }
4742
4743 static int osd_xattr_set_pfid(const struct lu_env *env, struct osd_object *obj,
4744                               const struct lu_buf *buf, int fl,
4745                               struct thandle *handle)
4746 {
4747         struct osd_thread_info *info = osd_oti_get(env);
4748         struct dentry *dentry = &info->oti_obj_dentry;
4749         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4750         struct lustre_mdt_attrs *lma = &loa->loa_lma;
4751         struct inode *inode = obj->oo_inode;
4752         struct filter_fid *ff = buf->lb_buf;
4753         struct ost_layout *ol = &ff->ff_layout;
4754         int flags = XATTR_REPLACE;
4755         int rc;
4756
4757         ENTRY;
4758
4759         if (buf->lb_len != sizeof(*ff) && buf->lb_len != sizeof(struct lu_fid))
4760                 RETURN(-EINVAL);
4761
4762         rc = osd_get_lma(info, inode, dentry, loa);
4763         if (rc == -ENODATA) {
4764                 /* Usually for upgarding from old device */
4765                 lustre_loa_init(loa, lu_object_fid(&obj->oo_dt.do_lu),
4766                                 LMAC_FID_ON_OST, 0);
4767                 flags = XATTR_CREATE;
4768         } else if (rc) {
4769                 RETURN(rc);
4770         }
4771
4772         if (!rc && lma->lma_compat & LMAC_STRIPE_INFO) {
4773                 if ((fl & LU_XATTR_CREATE) && !(fl & LU_XATTR_REPLACE))
4774                         RETURN(-EEXIST);
4775
4776                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256) {
4777                         /* Separate PFID EA from LMA */
4778                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4779                         lustre_lma_swab(lma);
4780                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4781                                              sizeof(*lma), XATTR_REPLACE);
4782                         if (!rc) {
4783                                 obj->oo_pfid_in_lma = 0;
4784                                 rc = LU_XATTR_CREATE;
4785                         }
4786
4787                         RETURN(rc);
4788                 }
4789         } else {
4790                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256)
4791                         RETURN(fl);
4792
4793                 /*
4794                  * Old client does not send stripe information,
4795                  * then store the PFID EA on disk separatedly.
4796                  */
4797                 if (unlikely(buf->lb_len == sizeof(struct lu_fid) ||
4798                              ol->ol_stripe_size == 0))
4799                         RETURN(fl);
4800
4801                 /* Remove old PFID EA entry firstly. */
4802                 dquot_initialize(inode);
4803                 rc = ll_vfs_removexattr(dentry, inode, XATTR_NAME_FID);
4804                 if (rc == -ENODATA) {
4805                         /* XATTR_NAME_FID is already absent */
4806                         rc = 0;
4807                 } else if (rc) {
4808                         RETURN(rc);
4809                 }
4810         }
4811
4812         fid_le_to_cpu(&loa->loa_parent_fid, &ff->ff_parent);
4813         if (likely(ol->ol_stripe_size != 0)) {
4814                 loa->loa_parent_fid.f_ver |= le32_to_cpu(ol->ol_stripe_count) <<
4815                                              PFID_STRIPE_IDX_BITS;
4816                 loa->loa_stripe_size = le32_to_cpu(ol->ol_stripe_size);
4817                 lma->lma_compat |= LMAC_STRIPE_INFO;
4818                 if (ol->ol_comp_id != 0) {
4819                         loa->loa_comp_id = le32_to_cpu(ol->ol_comp_id);
4820                         loa->loa_comp_start = le64_to_cpu(ol->ol_comp_start);
4821                         loa->loa_comp_end = le64_to_cpu(ol->ol_comp_end);
4822                         lma->lma_compat |= LMAC_COMP_INFO;
4823                 }
4824         }
4825
4826         lustre_loa_swab(loa, false);
4827
4828         /* Store the PFID EA inside LMA. */
4829         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa, sizeof(*loa),
4830                              flags);
4831         if (!rc)
4832                 obj->oo_pfid_in_lma = 1;
4833
4834         RETURN(rc);
4835 }
4836
4837 /*
4838  * In DNE environment, the object (in spite of regular file or directory)
4839  * and its name entry may reside on different MDTs. Under such case, we will
4840  * create an agent entry on the MDT where the object resides. The agent entry
4841  * references the object locally, that makes the object to be visible to the
4842  * userspace when mounted as 'ldiskfs' directly. Then the userspace tools,
4843  * such as 'tar' can handle the object properly.
4844  *
4845  * We handle the agent entry during set linkEA that is the common interface
4846  * for both regular file and directroy, can handle kinds of cases, such as
4847  * create/link/unlink/rename, and so on.
4848  *
4849  * NOTE: we can NOT do that when ea_{insert,delete} that is only for directory.
4850  *
4851  * XXX: There are two known issues:
4852  * 1. For one object, we will create at most one agent entry even if there
4853  *    may be more than one cross-MDTs hard links on the object. So the local
4854  *    e2fsck may claim that the object's nlink is larger than the name entries
4855  *    that reference such inode. And in further, the e2fsck will fix the nlink
4856  *    attribute to match the local references. Then it will cause the object's
4857  *    nlink attribute to be inconsistent with the global references. it is bad
4858  *    but not fatal. The ref_del() can handle the zero-referenced case. On the
4859  *    other hand, the global namespace LFSCK can repair the object's attribute
4860  *    according to the linkEA.
4861  * 2. There may be too many hard links on the object as to its linkEA overflow,
4862  *    then the linkEA entry for cross-MDTs reference may be discarded. If such
4863  *    case happened, then at this point, we do not know whether there are some
4864  *    cross-MDTs reference. But there are local references, it guarantees that
4865  *    object is visible to userspace when mounted as 'ldiskfs'. That is enough.
4866  */
4867 static int osd_xattr_handle_linkea(const struct lu_env *env,
4868                                    struct osd_device *osd,
4869                                    struct osd_object *obj,
4870                                    const struct lu_buf *buf,
4871                                    struct thandle *handle)
4872 {
4873         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
4874         struct lu_fid *tfid = &osd_oti_get(env)->oti_fid3;
4875         struct linkea_data ldata = { .ld_buf = (struct lu_buf *)buf };
4876         struct lu_name tmpname;
4877         struct osd_thandle *oh;
4878         int rc;
4879         bool remote = false;
4880
4881         ENTRY;
4882
4883         oh = container_of(handle, struct osd_thandle, ot_super);
4884         LASSERT(oh->ot_handle != NULL);
4885
4886         rc = linkea_init_with_rec(&ldata);
4887         if (!rc) {
4888                 linkea_first_entry(&ldata);
4889                 while (ldata.ld_lee != NULL && !remote) {
4890                         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen,
4891                                             &tmpname, tfid);
4892                         if (osd_remote_fid(env, osd, tfid) > 0)
4893                                 remote = true;
4894                         else
4895                                 linkea_next_entry(&ldata);
4896                 }
4897         } else if (rc == -ENODATA) {
4898                 rc = 0;
4899         } else {
4900                 RETURN(rc);
4901         }
4902
4903         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu) && !remote) {
4904                 rc = osd_delete_from_remote_parent(env, osd, obj, oh, false);
4905                 if (rc)
4906                         CERROR("%s: failed to remove agent entry for "DFID
4907                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4908         } else if (!lu_object_has_agent_entry(&obj->oo_dt.do_lu) && remote) {
4909                 rc = osd_add_to_remote_parent(env, osd, obj, oh);
4910                 if (rc)
4911                         CERROR("%s: failed to create agent entry for "DFID
4912                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4913         }
4914
4915         RETURN(rc);
4916 }
4917
4918 /*
4919  * Concurrency: @dt is write locked.
4920  */
4921 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
4922                          const struct lu_buf *buf, const char *name, int fl,
4923                          struct thandle *handle)
4924 {
4925         struct osd_object *obj = osd_dt_obj(dt);
4926         struct osd_device *osd = osd_obj2dev(obj);
4927         struct inode *inode = obj->oo_inode;
4928         struct osd_thread_info *info = osd_oti_get(env);
4929         int fs_flags = 0;
4930         int len;
4931         int rc;
4932
4933         ENTRY;
4934
4935         LASSERT(handle);
4936         LASSERT(buf);
4937
4938         /* version set is not real XATTR */
4939         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4940                 dt_obj_version_t *version = buf->lb_buf;
4941
4942                 /*
4943                  * for version we are just using xattr API but change inode
4944                  * field instead
4945                  */
4946                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
4947
4948                 CDEBUG(D_INODE, "Set version %#llx (old %#llx) for inode %lu\n",
4949                        *version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4950
4951                 LDISKFS_I(inode)->i_fs_version = *version;
4952                 /*
4953                  * Version is set after all inode operations are finished,
4954                  * so we should mark it dirty here
4955                  */
4956                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4957
4958                 RETURN(0);
4959         }
4960
4961         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zu\n",
4962                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
4963
4964         len = buf->lb_len;
4965         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4966
4967         /*
4968          * For the OST device with 256 bytes inode size by default,
4969          * the PFID EA will be stored together with LMA EA to avoid
4970          * performance trouble. Otherwise the PFID EA can be stored
4971          * independently. LU-8998
4972          */
4973         if (strcmp(name, XATTR_NAME_FID) == 0 && osd->od_is_ost &&
4974             (LDISKFS_INODE_SIZE(inode->i_sb) <= 256 || obj->oo_pfid_in_lma)) {
4975                 LASSERT(buf->lb_buf);
4976
4977                 fl = osd_xattr_set_pfid(env, obj, buf, fl, handle);
4978                 if (fl <= 0)
4979                         RETURN(fl);
4980         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
4981                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4982                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4983
4984                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4985                 if (rc)
4986                         RETURN(rc);
4987
4988                 lma->lma_incompat |= LMAI_STRIPED;
4989                 lustre_lma_swab(lma);
4990                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4991                                      sizeof(*lma), XATTR_REPLACE);
4992                 if (rc != 0)
4993                         RETURN(rc);
4994         } else if (strcmp(name, XATTR_NAME_LINK) == 0) {
4995                 LASSERT(!osd->od_is_ost);
4996
4997                 rc = osd_xattr_handle_linkea(env, osd, obj, buf, handle);
4998                 if (rc)
4999                         RETURN(rc);
5000         }
5001
5002         if (fl & LU_XATTR_REPLACE)
5003                 fs_flags |= XATTR_REPLACE;
5004
5005         if (fl & LU_XATTR_CREATE)
5006                 fs_flags |= XATTR_CREATE;
5007
5008         if (strcmp(name, LL_XATTR_NAME_ENCRYPTION_CONTEXT) == 0) {
5009                 /* Set enc context xattr directly in ldiskfs instead of going
5010                  * through the VFS, as there is no xattr handler for
5011                  * "encryption.".
5012                  */
5013                 struct osd_thandle *oth = container_of(handle,
5014                                                        struct osd_thandle,
5015                                                        ot_super);
5016
5017                 if (!oth->ot_handle)
5018                         /* this should be already part of a transaction */
5019                         RETURN(-EPROTO);
5020
5021                 rc = ldiskfs_xattr_set_handle(oth->ot_handle, inode,
5022                                           LDISKFS_XATTR_INDEX_ENCRYPTION,
5023                                           LDISKFS_XATTR_NAME_ENCRYPTION_CONTEXT,
5024                                           buf->lb_buf, len, fs_flags);
5025         } else {
5026                 rc = __osd_xattr_set(info, inode, name,
5027                                      buf->lb_buf, len, fs_flags);
5028         }
5029         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
5030
5031         if (rc == 0 &&
5032             (strcmp(name, XATTR_NAME_LOV) == 0 ||
5033              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
5034                 osd_oxc_add(obj, name, buf->lb_buf, buf->lb_len);
5035
5036         return rc;
5037 }
5038
5039 /*
5040  * Concurrency: @dt is read locked.
5041  */
5042 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
5043                           const struct lu_buf *buf)
5044 {
5045         struct osd_object *obj = osd_dt_obj(dt);
5046         struct osd_device *dev = osd_obj2dev(obj);
5047         struct inode *inode = obj->oo_inode;
5048         struct osd_thread_info *info = osd_oti_get(env);
5049         struct dentry *dentry = &info->oti_obj_dentry;
5050         int rc;
5051
5052         if (!dt_object_exists(dt))
5053                 return -ENOENT;
5054
5055         LASSERT(!dt_object_remote(dt));
5056         LASSERT(inode->i_op != NULL);
5057         LASSERT(inode->i_op->listxattr != NULL);
5058
5059         dentry->d_inode = inode;
5060         dentry->d_sb = inode->i_sb;
5061         rc = inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
5062
5063         if (rc < 0 || buf->lb_buf == NULL)
5064                 return rc;
5065
5066         /* Hide virtual project ID xattr from list if disabled */
5067         if (!dev->od_enable_projid_xattr) {
5068                 char *end = (char *)buf->lb_buf + rc;
5069                 char *p = buf->lb_buf;
5070
5071                 while (p < end) {
5072                         char *next = p + strlen(p) + 1;
5073
5074                         if (strcmp(p, XATTR_NAME_PROJID) == 0) {
5075                                 if (end - next > 0)
5076                                         memmove(p, next, end - next);
5077                                 rc -= next - p;
5078                                 break;
5079                         }
5080
5081                         p = next;
5082                 }
5083         }
5084
5085         return rc;
5086 }
5087
5088 static int osd_declare_xattr_del(const struct lu_env *env,
5089                                  struct dt_object *dt, const char *name,
5090                                  struct thandle *handle)
5091 {
5092         struct osd_thandle *oh;
5093         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
5094
5095         LASSERT(!dt_object_remote(dt));
5096         LASSERT(handle != NULL);
5097
5098         oh = container_of(handle, struct osd_thandle, ot_super);
5099         LASSERT(oh->ot_handle == NULL);
5100
5101         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
5102                              osd_dto_credits_noquota[DTO_XATTR_SET]);
5103         /*
5104          * xattr del may involve inode quota change, reserve credits for
5105          * dquot_initialize()
5106          */
5107         oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
5108
5109         return 0;
5110 }
5111
5112 /*
5113  * Concurrency: @dt is write locked.
5114  */
5115 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
5116                          const char *name, struct thandle *handle)
5117 {
5118         struct osd_object *obj = osd_dt_obj(dt);
5119         struct inode *inode = obj->oo_inode;
5120         struct osd_thread_info *info = osd_oti_get(env);
5121         struct dentry *dentry = &info->oti_obj_dentry;
5122         int rc;
5123
5124         if (!dt_object_exists(dt))
5125                 return -ENOENT;
5126
5127         LASSERT(!dt_object_remote(dt));
5128         LASSERT(inode->i_op != NULL);
5129         LASSERT(handle != NULL);
5130 #ifdef HAVE_IOP_XATTR
5131         LASSERT(inode->i_op->removexattr != NULL);
5132 #endif
5133
5134         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
5135
5136         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
5137                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
5138
5139                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
5140                                  &info->oti_ost_attrs);
5141                 if (!rc) {
5142                         LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
5143
5144                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
5145                         lustre_lma_swab(lma);
5146                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
5147                                              sizeof(*lma), XATTR_REPLACE);
5148                         if (!rc)
5149                                 obj->oo_pfid_in_lma = 0;
5150                 }
5151         } else {
5152                 dquot_initialize(inode);
5153                 dentry->d_inode = inode;
5154                 dentry->d_sb = inode->i_sb;
5155                 rc = ll_vfs_removexattr(dentry, inode, name);
5156         }
5157
5158         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
5159
5160         if (rc == 0 &&
5161             (strcmp(name, XATTR_NAME_LOV) == 0 ||
5162              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
5163                 osd_oxc_del(obj, name);
5164
5165         return rc;
5166 }
5167
5168 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt,
5169                            __u64 start, __u64 end)
5170 {
5171         struct osd_object *obj = osd_dt_obj(dt);
5172         struct osd_device *dev = osd_obj2dev(obj);
5173         struct inode *inode = obj->oo_inode;
5174         struct file *file;
5175         int rc;
5176
5177         ENTRY;
5178         file = alloc_file_pseudo(inode, dev->od_mnt, "/", O_NOATIME,
5179                                  inode->i_fop);
5180         if (IS_ERR(file))
5181                 RETURN(PTR_ERR(file));
5182
5183         file->f_mode |= FMODE_64BITHASH;
5184         rc = vfs_fsync_range(file, start, end, 0);
5185         ihold(inode);
5186         fput(file);
5187
5188         RETURN(rc);
5189 }
5190
5191 static int osd_invalidate(const struct lu_env *env, struct dt_object *dt)
5192 {
5193         return 0;
5194 }
5195
5196 static bool osd_check_stale(struct dt_object *dt)
5197 {
5198         return false;
5199 }
5200 /*
5201  * Index operations.
5202  */
5203
5204 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
5205                                const struct dt_index_features *feat)
5206 {
5207         struct iam_descr *descr;
5208
5209         if (osd_object_is_root(o))
5210                 return feat == &dt_directory_features;
5211
5212         LASSERT(o->oo_dir != NULL);
5213
5214         descr = o->oo_dir->od_container.ic_descr;
5215         if (feat == &dt_directory_features) {
5216                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
5217                         return 1;
5218                 else
5219                         return 0;
5220         } else {
5221                 return feat->dif_keysize_min <= descr->id_key_size &&
5222                        descr->id_key_size <= feat->dif_keysize_max &&
5223                        feat->dif_recsize_min <= descr->id_rec_size &&
5224                        descr->id_rec_size <= feat->dif_recsize_max &&
5225                        !(feat->dif_flags & (DT_IND_VARKEY |
5226                                             DT_IND_VARREC | DT_IND_NONUNQ)) &&
5227                        ergo(feat->dif_flags & DT_IND_UPDATE,
5228                             1 /* XXX check that object (and fs) is writable */);
5229         }
5230 }
5231
5232 static int osd_iam_container_init(const struct lu_env *env,
5233                                   struct osd_object *obj,
5234                                   struct osd_directory *dir)
5235 {
5236         struct iam_container *bag = &dir->od_container;
5237         int result;
5238
5239         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
5240         if (result != 0)
5241                 return result;
5242
5243         result = iam_container_setup(bag);
5244         if (result == 0)
5245                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
5246         else
5247                 iam_container_fini(bag);
5248
5249         return result;
5250 }
5251
5252
5253 /*
5254  * Concurrency: no external locking is necessary.
5255  */
5256 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
5257                          const struct dt_index_features *feat)
5258 {
5259         int result;
5260         int skip_iam = 0;
5261         struct osd_object *obj = osd_dt_obj(dt);
5262
5263         LINVRNT(osd_invariant(obj));
5264
5265         if (osd_object_is_root(obj)) {
5266                 dt->do_index_ops = &osd_index_ea_ops;
5267                 result = 0;
5268         } else if (feat == &dt_directory_features) {
5269                 dt->do_index_ops = &osd_index_ea_ops;
5270                 if (obj->oo_inode == NULL || S_ISDIR(obj->oo_inode->i_mode))
5271                         result = 0;
5272                 else
5273                         result = -ENOTDIR;
5274                 skip_iam = 1;
5275         } else if (unlikely(feat == &dt_otable_features)) {
5276                 dt->do_index_ops = &osd_otable_ops;
5277                 return 0;
5278         } else if (unlikely(feat == &dt_acct_features)) {
5279                 dt->do_index_ops = &osd_acct_index_ops;
5280                 result = 0;
5281                 skip_iam = 1;
5282         } else if (!osd_has_index(obj)) {
5283                 struct osd_directory *dir;
5284                 struct osd_device *osd = osd_obj2dev(obj);
5285                 const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
5286
5287                 OBD_ALLOC_PTR(dir);
5288                 if (dir) {
5289
5290                         spin_lock(&obj->oo_guard);
5291                         if (obj->oo_dir == NULL)
5292                                 obj->oo_dir = dir;
5293                         else
5294                                 /*
5295                                  * Concurrent thread allocated container data.
5296                                  */
5297                                 OBD_FREE_PTR(dir);
5298                         spin_unlock(&obj->oo_guard);
5299                         /*
5300                          * Now, that we have container data, serialize its
5301                          * initialization.
5302                          */
5303                         down_write(&obj->oo_ext_idx_sem);
5304                         /*
5305                          * recheck under lock.
5306                          */
5307
5308                         if (osd_has_index(obj)) {
5309                                 result = 0;
5310                                 goto unlock;
5311                         }
5312
5313                         result = osd_iam_container_init(env, obj, obj->oo_dir);
5314                         if (result || feat == &dt_lfsck_namespace_features ||
5315                             feat == &dt_lfsck_layout_orphan_features ||
5316                             feat == &dt_lfsck_layout_dangling_features)
5317                                 goto unlock;
5318
5319                         result = osd_index_register(osd, fid,
5320                                                     feat->dif_keysize_max,
5321                                                     feat->dif_recsize_max);
5322                         if (result < 0)
5323                                 CWARN("%s: failed to register index "
5324                                       DFID": rc = %d\n",
5325                                       osd_name(osd), PFID(fid), result);
5326                         else if (result > 0)
5327                                 result = 0;
5328                         else
5329                                 CDEBUG(D_LFSCK, "%s: index object "DFID
5330                                        " (%d/%d) registered\n",
5331                                        osd_name(osd), PFID(fid),
5332                                        (int)feat->dif_keysize_max,
5333                                        (int)feat->dif_recsize_max);
5334
5335 unlock:
5336                         up_write(&obj->oo_ext_idx_sem);
5337                 } else {
5338                         result = -ENOMEM;
5339                 }
5340         } else {
5341                 result = 0;
5342         }
5343
5344         if (result == 0 && skip_iam == 0) {
5345                 if (!osd_iam_index_probe(env, obj, feat))
5346                         result = -ENOTDIR;
5347         }
5348         LINVRNT(osd_invariant(obj));
5349
5350         return result;
5351 }
5352
5353 static int osd_otable_it_attr_get(const struct lu_env *env,
5354                                  struct dt_object *dt,
5355                                  struct lu_attr *attr)
5356 {
5357         attr->la_valid = 0;
5358         return 0;
5359 }
5360
5361 static const struct dt_object_operations osd_obj_ops = {
5362         .do_read_lock           = osd_read_lock,
5363         .do_write_lock          = osd_write_lock,
5364         .do_read_unlock         = osd_read_unlock,
5365         .do_write_unlock        = osd_write_unlock,
5366         .do_write_locked        = osd_write_locked,
5367         .do_attr_get            = osd_attr_get,
5368         .do_declare_attr_set    = osd_declare_attr_set,
5369         .do_attr_set            = osd_attr_set,
5370         .do_ah_init             = osd_ah_init,
5371         .do_declare_create      = osd_declare_create,
5372         .do_create              = osd_create,
5373         .do_declare_destroy     = osd_declare_destroy,
5374         .do_destroy             = osd_destroy,
5375         .do_index_try           = osd_index_try,
5376         .do_declare_ref_add     = osd_declare_ref_add,
5377         .do_ref_add             = osd_ref_add,
5378         .do_declare_ref_del     = osd_declare_ref_del,
5379         .do_ref_del             = osd_ref_del,
5380         .do_xattr_get           = osd_xattr_get,
5381         .do_declare_xattr_set   = osd_declare_xattr_set,
5382         .do_xattr_set           = osd_xattr_set,
5383         .do_declare_xattr_del   = osd_declare_xattr_del,
5384         .do_xattr_del           = osd_xattr_del,
5385         .do_xattr_list          = osd_xattr_list,
5386         .do_object_sync         = osd_object_sync,
5387         .do_invalidate          = osd_invalidate,
5388         .do_check_stale         = osd_check_stale,
5389 };
5390
5391 static const struct dt_object_operations osd_obj_otable_it_ops = {
5392         .do_attr_get    = osd_otable_it_attr_get,
5393         .do_index_try   = osd_index_try,
5394 };
5395
5396 static int osd_index_declare_iam_delete(const struct lu_env *env,
5397                                         struct dt_object *dt,
5398                                         const struct dt_key *key,
5399                                         struct thandle *handle)
5400 {
5401         struct osd_thandle *oh;
5402
5403         oh = container_of(handle, struct osd_thandle, ot_super);
5404         LASSERT(oh->ot_handle == NULL);
5405
5406         /* Recycle  may cause additional three blocks to be changed. */
5407         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
5408                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
5409
5410         return 0;
5411 }
5412
5413 /**
5414  *      delete a (key, value) pair from index \a dt specified by \a key
5415  *
5416  *      \param  dt      osd index object
5417  *      \param  key     key for index
5418  *      \param  rec     record reference
5419  *      \param  handle  transaction handler
5420  *
5421  *      \retval  0  success
5422  *      \retval -ve   failure
5423  */
5424 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
5425                                 const struct dt_key *key,
5426                                 struct thandle *handle)
5427 {
5428         struct osd_thread_info *oti = osd_oti_get(env);
5429         struct osd_object *obj = osd_dt_obj(dt);
5430         struct osd_thandle *oh;
5431         struct iam_path_descr *ipd;
5432         struct iam_container *bag = &obj->oo_dir->od_container;
5433         int rc;
5434
5435         ENTRY;
5436
5437         if (!dt_object_exists(dt))
5438                 RETURN(-ENOENT);
5439
5440         LINVRNT(osd_invariant(obj));
5441         LASSERT(!dt_object_remote(dt));
5442         LASSERT(bag->ic_object == obj->oo_inode);
5443         LASSERT(handle != NULL);
5444
5445         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5446
5447         ipd = osd_idx_ipd_get(env, bag);
5448         if (unlikely(ipd == NULL))
5449                 RETURN(-ENOMEM);
5450
5451         oh = container_of(handle, struct osd_thandle, ot_super);
5452         LASSERT(oh->ot_handle != NULL);
5453         LASSERT(oh->ot_handle->h_transaction != NULL);
5454
5455         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5456                 /* swab quota uid/gid provided by caller */
5457                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5458                 key = (const struct dt_key *)&oti->oti_quota_id;
5459         }
5460
5461         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
5462         osd_ipd_put(env, bag, ipd);
5463         LINVRNT(osd_invariant(obj));
5464         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5465         RETURN(rc);
5466 }
5467
5468 static int osd_index_declare_ea_delete(const struct lu_env *env,
5469                                        struct dt_object *dt,
5470                                        const struct dt_key *key,
5471                                        struct thandle *handle)
5472 {
5473         struct osd_thandle *oh;
5474         struct inode *inode;
5475         int rc, credits;
5476
5477         ENTRY;
5478
5479         LASSERT(!dt_object_remote(dt));
5480         LASSERT(handle != NULL);
5481
5482         oh = container_of(handle, struct osd_thandle, ot_super);
5483         LASSERT(oh->ot_handle == NULL);
5484
5485         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE];
5486         osd_trans_declare_op(env, oh, OSD_OT_DELETE, credits);
5487
5488         inode = osd_dt_obj(dt)->oo_inode;
5489         if (inode == NULL)
5490                 RETURN(-ENOENT);
5491
5492         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
5493                                    i_projid_read(inode), 0, oh, osd_dt_obj(dt),
5494                                    NULL, OSD_QID_BLK);
5495         RETURN(rc);
5496 }
5497
5498 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
5499                                           struct dt_rec *fid)
5500 {
5501         struct osd_fid_pack *rec;
5502         int rc = -ENODATA;
5503
5504         if (de->file_type & LDISKFS_DIRENT_LUFID) {
5505                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
5506                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
5507                 if (rc == 0 && unlikely(!fid_is_sane((struct lu_fid *)fid)))
5508                         rc = -EINVAL;
5509         }
5510         return rc;
5511 }
5512
5513 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
5514                           const struct lu_fid *fid)
5515 {
5516         struct seq_server_site *ss = osd_seq_site(osd);
5517
5518         ENTRY;
5519
5520         /* FID seqs not in FLDB, must be local seq */
5521         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
5522                 RETURN(0);
5523
5524         /*
5525          * If FLD is not being initialized yet, it only happens during the
5526          * initialization, likely during mgs initialization, and we assume
5527          * this is local FID.
5528          */
5529         if (ss == NULL || ss->ss_server_fld == NULL)
5530                 RETURN(0);
5531
5532         /* Only check the local FLDB here */
5533         if (osd_seq_exists(env, osd, fid_seq(fid)))
5534                 RETURN(0);
5535
5536         RETURN(1);
5537 }
5538
5539 static void osd_take_care_of_agent(const struct lu_env *env,
5540                                    struct osd_device *osd,
5541                                    struct osd_thandle *oh,
5542                                    struct ldiskfs_dir_entry_2 *de)
5543 {
5544         struct lu_fid *fid = &osd_oti_get(env)->oti_fid;
5545         struct osd_idmap_cache *idc;
5546         int rc, schedule = 0;
5547
5548         LASSERT(de != NULL);
5549
5550         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
5551         if (likely(rc == 0)) {
5552                 idc = osd_idc_find_or_init(env, osd, fid);
5553                 if (IS_ERR(idc) || idc->oic_remote)
5554                         schedule = 1;
5555         } else if (rc == -ENODATA) {
5556                 /*
5557                  * can't get FID, postpone to the end of the
5558                  * transaction when iget() is safe
5559                  */
5560                 schedule = 1;
5561         } else {
5562                 CERROR("%s: can't get FID: rc = %d\n", osd_name(osd), rc);
5563         }
5564         if (schedule)
5565                 osd_schedule_agent_inode_removal(env, oh,
5566                                                  le32_to_cpu(de->inode));
5567 }
5568
5569 /**
5570  * Utility function to get real name from object name
5571  *
5572  * \param[in] obj      pointer to the object to be handled
5573  * \param[in] name     object name
5574  * \param[in] len      object name len
5575  * \param[out]ln       pointer to the struct lu_name to hold the real name
5576  *
5577  * If file is not encrypted, real name is just the object name.
5578  * If file is encrypted, object name needs to be decoded. In
5579  * this case a new buffer is allocated, and ln->ln_name needs to be freed by
5580  * the caller.
5581  *
5582  * \retval   0, on success
5583  * \retval -ve, on error
5584  */
5585 static int obj_name2lu_name(struct osd_object *obj, const char *name,
5586                             int len, struct lu_name *ln)
5587 {
5588         if (!(obj->oo_lma_flags & LUSTRE_ENCRYPT_FL)) {
5589                 ln->ln_name = name;
5590                 ln->ln_namelen = len;
5591         } else {
5592                 char *buf = kmalloc(len, GFP_NOFS);
5593
5594                 if (!buf)
5595                         return -ENOMEM;
5596
5597                 len = critical_decode(name, len, buf);
5598                 ln->ln_name = buf;
5599                 ln->ln_namelen = len;
5600         }
5601
5602         return 0;
5603 }
5604
5605 /**
5606  * Index delete function for interoperability mode (b11826).
5607  * It will remove the directory entry added by osd_index_ea_insert().
5608  * This entry is needed to maintain name->fid mapping.
5609  *
5610  * \param key,  key i.e. file entry to be deleted
5611  *
5612  * \retval   0, on success
5613  * \retval -ve, on error
5614  */
5615 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
5616                                const struct dt_key *key, struct thandle *handle)
5617 {
5618         struct osd_object *obj = osd_dt_obj(dt);
5619         struct inode *dir = obj->oo_inode;
5620         struct dentry *dentry;
5621         struct osd_thandle *oh;
5622         struct ldiskfs_dir_entry_2 *de = NULL;
5623         struct buffer_head *bh;
5624         struct htree_lock *hlock = NULL;
5625         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
5626         struct lu_name ln;
5627         int rc;
5628
5629         ENTRY;
5630
5631         if (!dt_object_exists(dt))
5632                 RETURN(-ENOENT);
5633
5634         LINVRNT(osd_invariant(obj));
5635         LASSERT(!dt_object_remote(dt));
5636         LASSERT(handle != NULL);
5637
5638         rc = obj_name2lu_name(obj, (char *)key, strlen((char *)key), &ln);
5639         if (rc)
5640                 RETURN(rc);
5641
5642         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5643
5644         oh = container_of(handle, struct osd_thandle, ot_super);
5645         LASSERT(oh->ot_handle != NULL);
5646         LASSERT(oh->ot_handle->h_transaction != NULL);
5647
5648         dquot_initialize(dir);
5649         dentry = osd_child_dentry_get(env, obj, ln.ln_name, ln.ln_namelen);
5650
5651         if (obj->oo_hl_head != NULL) {
5652                 hlock = osd_oti_get(env)->oti_hlock;
5653                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5654                                    dir, LDISKFS_HLOCK_DEL);
5655         } else {
5656                 down_write(&obj->oo_ext_idx_sem);
5657         }
5658
5659         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5660         if (!IS_ERR(bh)) {
5661                 /*
5662                  * If this is not the ".." entry, it might be a remote DNE
5663                  * entry and  we need to check if the FID is for a remote
5664                  * MDT.  If the FID is  not in the directory entry (e.g.
5665                  * upgraded 1.8 filesystem without dirdata enabled) then
5666                  * we need to get the FID from the LMA. For a remote directory
5667                  * there HAS to be an LMA, it cannot be an IGIF inode in this
5668                  * case.
5669                  *
5670                  * Delete the entry before the agent inode in order to
5671                  * simplify error handling.  At worst an error after deleting
5672                  * the entry first might leak the agent inode afterward. The
5673                  * reverse would need filesystem abort in case of error deleting
5674                  * the entry after the agent had been removed, or leave a
5675                  * dangling entry pointing at a random inode.
5676                  */
5677                 if (strcmp((char *)key, dotdot) != 0)
5678                         osd_take_care_of_agent(env, osd, oh, de);
5679                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
5680                 brelse(bh);
5681         } else {
5682                 rc = PTR_ERR(bh);
5683         }
5684
5685         if (!rc && fid_is_namespace_visible(lu_object_fid(&dt->do_lu)) &&
5686             obj->oo_dirent_count != LU_DIRENT_COUNT_UNSET) {
5687                 /* NB, dirent count may not be accurate, because it's counted
5688                  * without lock.
5689                  */
5690                 if (obj->oo_dirent_count)
5691                         obj->oo_dirent_count--;
5692                 else
5693                         obj->oo_dirent_count = LU_DIRENT_COUNT_UNSET;
5694         }
5695         if (hlock != NULL)
5696                 ldiskfs_htree_unlock(hlock);
5697         else
5698                 up_write(&obj->oo_ext_idx_sem);
5699         GOTO(out, rc);
5700 out:
5701         LASSERT(osd_invariant(obj));
5702         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5703         if (ln.ln_name != (char *)key)
5704                 kfree(ln.ln_name);
5705         RETURN(rc);
5706 }
5707
5708 /**
5709  *      Lookup index for \a key and copy record to \a rec.
5710  *
5711  *      \param  dt      osd index object
5712  *      \param  key     key for index
5713  *      \param  rec     record reference
5714  *
5715  *      \retval  +ve  success : exact mach
5716  *      \retval  0    return record with key not greater than \a key
5717  *      \retval -ve   failure
5718  */
5719 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
5720                                 struct dt_rec *rec, const struct dt_key *key)
5721 {
5722         struct osd_object *obj = osd_dt_obj(dt);
5723         struct iam_path_descr *ipd;
5724         struct iam_container *bag = &obj->oo_dir->od_container;
5725         struct osd_thread_info *oti = osd_oti_get(env);
5726         struct iam_iterator *it = &oti->oti_idx_it;
5727         struct iam_rec *iam_rec;
5728         int rc;
5729
5730         ENTRY;
5731
5732         if (!dt_object_exists(dt))
5733                 RETURN(-ENOENT);
5734
5735         LASSERT(osd_invariant(obj));
5736         LASSERT(!dt_object_remote(dt));
5737         LASSERT(bag->ic_object == obj->oo_inode);
5738
5739         ipd = osd_idx_ipd_get(env, bag);
5740         if (IS_ERR(ipd))
5741                 RETURN(-ENOMEM);
5742
5743         /* got ipd now we can start iterator. */
5744         iam_it_init(it, bag, 0, ipd);
5745
5746         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5747                 /* swab quota uid/gid provided by caller */
5748                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5749                 key = (const struct dt_key *)&oti->oti_quota_id;
5750         }
5751
5752         rc = iam_it_get(it, (struct iam_key *)key);
5753         if (rc >= 0) {
5754                 if (S_ISDIR(obj->oo_inode->i_mode))
5755                         iam_rec = (struct iam_rec *)oti->oti_ldp;
5756                 else
5757                         iam_rec = (struct iam_rec *)rec;
5758
5759                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
5760
5761                 if (S_ISDIR(obj->oo_inode->i_mode))
5762                         osd_fid_unpack((struct lu_fid *)rec,
5763                                        (struct osd_fid_pack *)iam_rec);
5764                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
5765                         osd_quota_unpack(obj, rec);
5766         }
5767
5768         iam_it_put(it);
5769         iam_it_fini(it);
5770         osd_ipd_put(env, bag, ipd);
5771
5772         LINVRNT(osd_invariant(obj));
5773
5774         RETURN(rc);
5775 }
5776
5777 static int osd_index_declare_iam_insert(const struct lu_env *env,
5778                                         struct dt_object *dt,
5779                                         const struct dt_rec *rec,
5780                                         const struct dt_key *key,
5781                                         struct thandle *handle)
5782 {
5783         struct osd_thandle *oh;
5784
5785         LASSERT(handle != NULL);
5786
5787         oh = container_of(handle, struct osd_thandle, ot_super);
5788         LASSERT(oh->ot_handle == NULL);
5789
5790         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
5791                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
5792
5793         return 0;
5794 }
5795
5796 /**
5797  *      Inserts (key, value) pair in \a dt index object.
5798  *
5799  *      \param  dt      osd index object
5800  *      \param  key     key for index
5801  *      \param  rec     record reference
5802  *      \param  th      transaction handler
5803  *
5804  *      \retval  0  success
5805  *      \retval -ve failure
5806  */
5807 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
5808                                 const struct dt_rec *rec,
5809                                 const struct dt_key *key, struct thandle *th)
5810 {
5811         struct osd_object *obj = osd_dt_obj(dt);
5812         struct iam_path_descr *ipd;
5813         struct osd_thandle *oh;
5814         struct iam_container *bag;
5815         struct osd_thread_info *oti = osd_oti_get(env);
5816         struct iam_rec *iam_rec;
5817         int rc;
5818
5819         ENTRY;
5820
5821         if (!dt_object_exists(dt))
5822                 RETURN(-ENOENT);
5823
5824         LINVRNT(osd_invariant(obj));
5825         LASSERT(!dt_object_remote(dt));
5826
5827         bag = &obj->oo_dir->od_container;
5828         LASSERT(bag->ic_object == obj->oo_inode);
5829         LASSERT(th != NULL);
5830
5831         osd_trans_exec_op(env, th, OSD_OT_INSERT);
5832
5833         ipd = osd_idx_ipd_get(env, bag);
5834         if (unlikely(ipd == NULL))
5835                 RETURN(-ENOMEM);
5836
5837         oh = container_of(th, struct osd_thandle, ot_super);
5838         LASSERT(oh->ot_handle != NULL);
5839         LASSERT(oh->ot_handle->h_transaction != NULL);
5840         if (S_ISDIR(obj->oo_inode->i_mode)) {
5841                 iam_rec = (struct iam_rec *)oti->oti_ldp;
5842                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec,
5843                              &oti->oti_fid);
5844         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5845                 /* pack quota uid/gid */
5846                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5847                 key = (const struct dt_key *)&oti->oti_quota_id;
5848                 /* pack quota record */
5849                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
5850                 iam_rec = (struct iam_rec *)rec;
5851         } else {
5852                 iam_rec = (struct iam_rec *)rec;
5853         }
5854
5855         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
5856                         iam_rec, ipd);
5857         osd_ipd_put(env, bag, ipd);
5858         LINVRNT(osd_invariant(obj));
5859         osd_trans_exec_check(env, th, OSD_OT_INSERT);
5860         RETURN(rc);
5861 }
5862
5863 /**
5864  * Calls ldiskfs_add_entry() to add directory entry
5865  * into the directory. This is required for
5866  * interoperability mode (b11826)
5867  *
5868  * \retval   0, on success
5869  * \retval -ve, on error
5870  */
5871 static int __osd_ea_add_rec(struct osd_thread_info *info,
5872                             struct osd_object *pobj, struct inode  *cinode,
5873                             const char *name, const struct lu_fid *fid,
5874                             struct htree_lock *hlock, struct thandle *th)
5875 {
5876         struct ldiskfs_dentry_param *ldp;
5877         struct dentry *child;
5878         struct osd_thandle *oth;
5879         struct lu_name ln;
5880         int rc;
5881
5882         oth = container_of(th, struct osd_thandle, ot_super);
5883         LASSERT(oth->ot_handle != NULL);
5884         LASSERT(oth->ot_handle->h_transaction != NULL);
5885         LASSERT(pobj->oo_inode);
5886
5887         rc = obj_name2lu_name(pobj, name, strlen(name), &ln);
5888         if (rc)
5889                 RETURN(rc);
5890
5891         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
5892         if (unlikely(osd_object_is_root(pobj)))
5893                 ldp->edp_magic = 0;
5894         else
5895                 osd_get_ldiskfs_dirent_param(ldp, fid);
5896         child = osd_child_dentry_get(info->oti_env, pobj,
5897                                      ln.ln_name, ln.ln_namelen);
5898         child->d_fsdata = (void *)ldp;
5899         dquot_initialize(pobj->oo_inode);
5900         rc = osd_ldiskfs_add_entry(info, osd_obj2dev(pobj), oth->ot_handle,
5901                                    child, cinode, hlock);
5902         if (rc == 0 && OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_TYPE)) {
5903                 struct ldiskfs_dir_entry_2      *de;
5904                 struct buffer_head              *bh;
5905                 int                              rc1;
5906
5907                 bh = osd_ldiskfs_find_entry(pobj->oo_inode, &child->d_name, &de,
5908                                             NULL, hlock);
5909                 if (!IS_ERR(bh)) {
5910                         rc1 = osd_ldiskfs_journal_get_write_access(
5911                                 oth->ot_handle, pobj->oo_inode->i_sb, bh,
5912                                 LDISKFS_JTR_NONE);
5913                         if (rc1 == 0) {
5914                                 if (S_ISDIR(cinode->i_mode))
5915                                         de->file_type = LDISKFS_DIRENT_LUFID |
5916                                                         LDISKFS_FT_REG_FILE;
5917                                 else
5918                                         de->file_type = LDISKFS_DIRENT_LUFID |
5919                                                         LDISKFS_FT_DIR;
5920                                 ldiskfs_handle_dirty_metadata(oth->ot_handle,
5921                                                               NULL, bh);
5922                         }
5923                         brelse(bh);
5924                 }
5925         }
5926
5927         if (ln.ln_name != name)
5928                 kfree(ln.ln_name);
5929         RETURN(rc);
5930 }
5931
5932 /**
5933  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
5934  * into the directory.Also sets flags into osd object to
5935  * indicate dot and dotdot are created. This is required for
5936  * interoperability mode (b11826)
5937  *
5938  * \param dir   directory for dot and dotdot fixup.
5939  * \param obj   child object for linking
5940  *
5941  * \retval   0, on success
5942  * \retval -ve, on error
5943  */
5944 static int osd_add_dot_dotdot(struct osd_thread_info *info,
5945                               struct osd_object *dir,
5946                               struct inode *parent_dir, const char *name,
5947                               const struct lu_fid *dot_fid,
5948                               const struct lu_fid *dot_dot_fid,
5949                               struct thandle *th)
5950 {
5951         struct inode *inode = dir->oo_inode;
5952         struct osd_thandle *oth;
5953         int result = 0;
5954
5955         oth = container_of(th, struct osd_thandle, ot_super);
5956         LASSERT(oth->ot_handle->h_transaction != NULL);
5957         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
5958
5959         if (strcmp(name, dot) == 0) {
5960                 if (dir->oo_compat_dot_created) {
5961                         result = -EEXIST;
5962                 } else {
5963                         LASSERT(inode->i_ino == parent_dir->i_ino);
5964                         dir->oo_compat_dot_created = 1;
5965                         result = 0;
5966                 }
5967         } else if (strcmp(name, dotdot) == 0) {
5968                 if (!dir->oo_compat_dot_created)
5969                         return -EINVAL;
5970                 /* in case of rename, dotdot is already created */
5971                 if (dir->oo_compat_dotdot_created) {
5972                         return __osd_ea_add_rec(info, dir, parent_dir, name,
5973                                                 dot_dot_fid, NULL, th);
5974                 }
5975
5976                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
5977                         struct lu_fid tfid = *dot_dot_fid;
5978
5979                         tfid.f_oid--;
5980                         result = osd_add_dot_dotdot_internal(info,
5981                                         dir->oo_inode, parent_dir, dot_fid,
5982                                         &tfid, oth);
5983                 } else {
5984                         result = osd_add_dot_dotdot_internal(info,
5985                                         dir->oo_inode, parent_dir, dot_fid,
5986                                         dot_dot_fid, oth);
5987                 }
5988
5989                 if (result == 0)
5990                         dir->oo_compat_dotdot_created = 1;
5991         }
5992
5993         return result;
5994 }
5995
5996
5997 /**
5998  * It will call the appropriate osd_add* function and return the
5999  * value, return by respective functions.
6000  */
6001 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
6002                           struct inode *cinode, const char *name,
6003                           const struct lu_fid *fid, struct thandle *th)
6004 {
6005         struct osd_thread_info *info = osd_oti_get(env);
6006         struct htree_lock *hlock;
6007         int rc;
6008
6009         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
6010
6011         if (name[0] == '.' && (name[1] == '\0' ||
6012                                (name[1] == '.' && name[2] == '\0'))) {
6013                 if (hlock != NULL) {
6014                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
6015                                            pobj->oo_inode, 0);
6016                 } else {
6017                         down_write(&pobj->oo_ext_idx_sem);
6018                 }
6019
6020                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
6021                                         lu_object_fid(&pobj->oo_dt.do_lu),
6022                                         fid, th);
6023         } else {
6024                 if (hlock != NULL) {
6025                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
6026                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
6027                 } else {
6028                         down_write(&pobj->oo_ext_idx_sem);
6029                 }
6030
6031                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
6032                         struct lu_fid *tfid = &info->oti_fid;
6033
6034                         *tfid = *fid;
6035                         tfid->f_ver = ~0;
6036                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
6037                                               tfid, hlock, th);
6038                 } else {
6039                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
6040                                               hlock, th);
6041                 }
6042         }
6043         if (!rc && fid_is_namespace_visible(lu_object_fid(&pobj->oo_dt.do_lu))
6044             && pobj->oo_dirent_count != LU_DIRENT_COUNT_UNSET)
6045                 pobj->oo_dirent_count++;
6046
6047         if (hlock != NULL)
6048                 ldiskfs_htree_unlock(hlock);
6049         else
6050                 up_write(&pobj->oo_ext_idx_sem);
6051
6052         return rc;
6053 }
6054
6055 static int
6056 osd_ldiskfs_consistency_check(struct osd_thread_info *oti,
6057                               struct osd_device *dev,
6058                               const struct lu_fid *fid,
6059                               struct osd_inode_id *id)
6060 {
6061         struct lustre_scrub *scrub = &dev->od_scrub.os_scrub;
6062         struct inode *inode = NULL;
6063         int once = 0;
6064         bool insert;
6065         int rc;
6066
6067         ENTRY;
6068         if (!scrub_needs_check(scrub, fid, id->oii_ino))
6069                 RETURN(0);
6070 again:
6071         rc = osd_oi_lookup(oti, dev, fid, &oti->oti_id, 0);
6072         if (rc == -ENOENT) {
6073                 __u32 gen = id->oii_gen;
6074
6075                 insert = true;
6076                 if (inode != NULL)
6077                         goto trigger;
6078
6079                 inode = osd_iget(oti, dev, id);
6080                 /* The inode has been removed (by race maybe). */
6081                 if (IS_ERR(inode)) {
6082                         rc = PTR_ERR(inode);
6083
6084                         RETURN(rc == -ESTALE ? -ENOENT : rc);
6085                 }
6086
6087                 /* The OI mapping is lost. */
6088                 if (gen != OSD_OII_NOGEN)
6089                         goto trigger;
6090
6091                 /*
6092                  * The inode may has been reused by others, we do not know,
6093                  * leave it to be handled by subsequent osd_fid_lookup().
6094                  */
6095                 GOTO(out, rc = 0);
6096         } else if (rc || osd_id_eq(id, &oti->oti_id)) {
6097                 GOTO(out, rc);
6098         }
6099
6100         insert = false;
6101
6102 trigger:
6103         if (scrub->os_running) {
6104                 if (inode == NULL) {
6105                         inode = osd_iget(oti, dev, id);
6106                         /* The inode has been removed (by race maybe). */
6107                         if (IS_ERR(inode)) {
6108                                 rc = PTR_ERR(inode);
6109
6110                                 RETURN(rc == -ESTALE ? -ENOENT : rc);
6111                         }
6112                 }
6113
6114                 rc = osd_scrub_oi_insert(dev, fid, id, insert);
6115                 /*
6116                  * There is race condition between osd_oi_lookup and OI scrub.
6117                  * The OI scrub finished just after osd_oi_lookup() failure.
6118                  * Under such case, it is unnecessary to trigger OI scrub again,
6119                  * but try to call osd_oi_lookup() again.
6120                  */
6121                 if (unlikely(rc == -EAGAIN))
6122                         goto again;
6123
6124                 if (!S_ISDIR(inode->i_mode))
6125                         rc = 0;
6126                 else
6127                         rc = osd_check_lmv(oti, dev, inode);
6128
6129                 GOTO(out, rc);
6130         }
6131
6132         if (dev->od_scrub.os_scrub.os_auto_scrub_interval != AS_NEVER &&
6133             ++once == 1) {
6134                 rc = osd_scrub_start(oti->oti_env, dev, SS_AUTO_PARTIAL |
6135                                      SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT);
6136                 CDEBUG_LIMIT(D_LFSCK | D_CONSOLE | D_WARNING,
6137                              "%s: trigger partial OI scrub for RPC inconsistency, checking FID "DFID"/%u: rc = %d\n",
6138                              osd_dev2name(dev), PFID(fid), id->oii_ino, rc);
6139                 if (rc == 0 || rc == -EALREADY)
6140                         goto again;
6141         }
6142
6143         GOTO(out, rc);
6144
6145 out:
6146         iput(inode);
6147
6148         RETURN(rc);
6149 }
6150
6151 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
6152                                struct osd_device *dev,
6153                                struct lu_fid *fid, __u32 ino)
6154 {
6155         struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
6156         struct osd_idmap_cache *oic = &oti->oti_cache;
6157         struct inode *inode;
6158         int rc;
6159
6160         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
6161         inode = osd_iget(oti, dev, &oic->oic_lid);
6162         if (IS_ERR(inode)) {
6163                 fid_zero(&oic->oic_fid);
6164                 return PTR_ERR(inode);
6165         }
6166
6167         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, loa);
6168         iput(inode);
6169         if (rc != 0)
6170                 fid_zero(&oic->oic_fid);
6171         else
6172                 *fid = oic->oic_fid = loa->loa_lma.lma_self_fid;
6173         return rc;
6174 }
6175
6176 void osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
6177                       struct osd_inode_id *id, const struct lu_fid *fid)
6178 {
6179         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
6180                id->oii_ino, id->oii_gen, info);
6181         info->oti_cache.oic_lid = *id;
6182         info->oti_cache.oic_fid = *fid;
6183         info->oti_cache.oic_dev = osd;
6184 }
6185
6186 /**
6187  * Get parent FID from the linkEA.
6188  *
6189  * For a directory which parent resides on remote MDT, to satisfy the
6190  * local e2fsck, we insert it into the /REMOTE_PARENT_DIR locally. On
6191  * the other hand, to make the lookup(..) on the directory can return
6192  * the real parent FID, we append the real parent FID after its ".."
6193  * name entry in the /REMOTE_PARENT_DIR.
6194  *
6195  * Unfortunately, such PFID-in-dirent cannot be preserved via file-level
6196  * backup. So after the restore, we cannot get the right parent FID from
6197  * its ".." name entry in the /REMOTE_PARENT_DIR. Under such case, since
6198  * we have stored the real parent FID in the directory object's linkEA,
6199  * we can parse the linkEA for the real parent FID.
6200  *
6201  * \param[in] env       pointer to the thread context
6202  * \param[in] obj       pointer to the object to be handled
6203  * \param[out]fid       pointer to the buffer to hold the parent FID
6204  *
6205  * \retval              0 for getting the real parent FID successfully
6206  * \retval              negative error number on failure
6207  */
6208 static int osd_get_pfid_from_linkea(const struct lu_env *env,
6209                                     struct osd_object *obj,
6210                                     struct lu_fid *fid)
6211 {
6212         struct osd_thread_info *oti = osd_oti_get(env);
6213         struct lu_buf *buf = &oti->oti_big_buf;
6214         struct dentry *dentry = &oti->oti_obj_dentry;
6215         struct inode *inode = obj->oo_inode;
6216         struct linkea_data ldata = { NULL };
6217         int rc;
6218
6219         ENTRY;
6220
6221         fid_zero(fid);
6222         if (!S_ISDIR(inode->i_mode))
6223                 RETURN(-EIO);
6224
6225 again:
6226         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6227                              buf->lb_buf, buf->lb_len);
6228         if (rc == -ERANGE) {
6229                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6230                                      NULL, 0);
6231                 if (rc > 0) {
6232                         lu_buf_realloc(buf, rc);
6233                         if (buf->lb_buf == NULL)
6234                                 RETURN(-ENOMEM);
6235
6236                         goto again;
6237                 }
6238         }
6239
6240         if (unlikely(rc == 0))
6241                 RETURN(-ENODATA);
6242
6243         if (rc < 0)
6244                 RETURN(rc);
6245
6246         if (unlikely(buf->lb_buf == NULL)) {
6247                 lu_buf_realloc(buf, rc);
6248                 if (buf->lb_buf == NULL)
6249                         RETURN(-ENOMEM);
6250
6251                 goto again;
6252         }
6253
6254         ldata.ld_buf = buf;
6255         rc = linkea_init_with_rec(&ldata);
6256         if (!rc) {
6257                 linkea_first_entry(&ldata);
6258                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, NULL, fid);
6259         }
6260
6261         RETURN(rc);
6262 }
6263
6264 static int osd_verify_ent_by_linkea(const struct lu_env *env,
6265                                     struct inode *inode,
6266                                     const struct lu_fid *pfid,
6267                                     const char *name, const int namelen)
6268 {
6269         struct osd_thread_info *oti = osd_oti_get(env);
6270         struct lu_buf *buf = &oti->oti_big_buf;
6271         struct dentry *dentry = &oti->oti_obj_dentry;
6272         struct linkea_data ldata = { NULL };
6273         struct lu_name cname = { .ln_name = name,
6274                                  .ln_namelen = namelen };
6275         int rc;
6276
6277         ENTRY;
6278
6279 again:
6280         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6281                              buf->lb_buf, buf->lb_len);
6282         if (rc == -ERANGE)
6283                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK, NULL, 0);
6284
6285         if (rc < 0)
6286                 RETURN(rc);
6287
6288         if (unlikely(rc == 0))
6289                 RETURN(-ENODATA);
6290
6291         if (buf->lb_len < rc) {
6292                 lu_buf_realloc(buf, rc);
6293                 if (buf->lb_buf == NULL)
6294                         RETURN(-ENOMEM);
6295
6296                 goto again;
6297         }
6298
6299         ldata.ld_buf = buf;
6300         rc = linkea_init_with_rec(&ldata);
6301         if (!rc)
6302                 rc = linkea_links_find(&ldata, &cname, pfid);
6303
6304         RETURN(rc);
6305 }
6306
6307 /**
6308  * Calls ->lookup() to find dentry. From dentry get inode and
6309  * read inode's ea to get fid. This is required for  interoperability
6310  * mode (b11826)
6311  *
6312  * \retval   0, on success
6313  * \retval -ve, on error
6314  */
6315 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
6316                              struct dt_rec *rec, const struct dt_key *key)
6317 {
6318         struct inode *dir = obj->oo_inode;
6319         struct dentry *dentry;
6320         struct ldiskfs_dir_entry_2 *de;
6321         struct buffer_head *bh;
6322         struct lu_fid *fid = (struct lu_fid *)rec;
6323         struct htree_lock *hlock = NULL;
6324         struct lu_name ln;
6325         int ino;
6326         int rc;
6327
6328         ENTRY;
6329
6330         LASSERT(dir->i_op != NULL);
6331         LASSERT(dir->i_op->lookup != NULL);
6332
6333         rc = obj_name2lu_name(obj, (char *)key, strlen((char *)key), &ln);
6334         if (rc)
6335                 RETURN(rc);
6336
6337         dentry = osd_child_dentry_get(env, obj, ln.ln_name, ln.ln_namelen);
6338
6339         if (obj->oo_hl_head != NULL) {
6340                 hlock = osd_oti_get(env)->oti_hlock;
6341                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
6342                                    dir, LDISKFS_HLOCK_LOOKUP);
6343         } else {
6344                 down_read(&obj->oo_ext_idx_sem);
6345         }
6346
6347         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
6348         if (!IS_ERR(bh)) {
6349                 struct osd_thread_info *oti = osd_oti_get(env);
6350                 struct osd_inode_id *id = &oti->oti_id;
6351                 struct osd_device *dev = osd_obj2dev(obj);
6352
6353                 ino = le32_to_cpu(de->inode);
6354                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
6355                         brelse(bh);
6356                         rc = osd_fail_fid_lookup(oti, dev, fid, ino);
6357                         GOTO(out, rc);
6358                 }
6359
6360                 rc = osd_get_fid_from_dentry(de, rec);
6361
6362                 /* done with de, release bh */
6363                 brelse(bh);
6364                 if (rc != 0) {
6365                         if (unlikely(is_remote_parent_ino(dev, ino))) {
6366                                 const char *name = (const char *)key;
6367
6368                                 /*
6369                                  * If the parent is on remote MDT, and there
6370                                  * is no FID-in-dirent, then we have to get
6371                                  * the parent FID from the linkEA.
6372                                  */
6373                                 if (likely(strlen(name) == 2 &&
6374                                            name[0] == '.' && name[1] == '.'))
6375                                         rc = osd_get_pfid_from_linkea(env, obj,
6376                                                                       fid);
6377                         } else {
6378                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
6379                         }
6380                 } else {
6381                         osd_id_gen(id, ino, OSD_OII_NOGEN);
6382                 }
6383
6384                 if (rc != 0 || osd_remote_fid(env, dev, fid))
6385                         GOTO(out, rc);
6386
6387                 rc = osd_ldiskfs_consistency_check(oti, dev, fid, id);
6388                 if (rc != -ENOENT) {
6389                         /* Other error should not affect lookup result. */
6390                         rc = 0;
6391
6392                         /* Normal file mapping should be added into OI cache
6393                          * after FID in LMA check, but for local files like
6394                          * hsm_actions, their FIDs are not stored in OI files,
6395                          * see osd_initial_OI_scrub(), and here is the only
6396                          * place to load mapping into OI cache.
6397                          */
6398                         if (!fid_is_namespace_visible(fid))
6399                                 osd_add_oi_cache(osd_oti_get(env),
6400                                                  osd_obj2dev(obj), id, fid);
6401                 }
6402                 CDEBUG(D_INODE, DFID"/"DNAME" => "DFID"\n",
6403                        PFID(lu_object_fid(&obj->oo_dt.do_lu)), PNAME(&ln),
6404                        PFID(fid));
6405         } else {
6406                 rc = PTR_ERR(bh);
6407         }
6408
6409         GOTO(out, rc);
6410
6411 out:
6412         if (hlock != NULL)
6413                 ldiskfs_htree_unlock(hlock);
6414         else
6415                 up_read(&obj->oo_ext_idx_sem);
6416         if (ln.ln_name != (char *)key)
6417                 kfree(ln.ln_name);
6418         RETURN(rc);
6419 }
6420
6421 static int osd_index_declare_ea_insert(const struct lu_env *env,
6422                                        struct dt_object *dt,
6423                                        const struct dt_rec *rec,
6424                                        const struct dt_key *key,
6425                                        struct thandle *handle)
6426 {
6427         struct osd_thandle *oh;
6428         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
6429         struct dt_insert_rec *rec1 = (struct dt_insert_rec *)rec;
6430         const struct lu_fid *fid = rec1->rec_fid;
6431         int credits, rc = 0;
6432         struct osd_idmap_cache *idc;
6433
6434         ENTRY;
6435
6436         LASSERT(!dt_object_remote(dt));
6437         LASSERT(handle != NULL);
6438         LASSERT(fid != NULL);
6439         LASSERT(rec1->rec_type != 0);
6440
6441         oh = container_of(handle, struct osd_thandle, ot_super);
6442         LASSERT(oh->ot_handle == NULL);
6443
6444         credits = osd_dto_credits_noquota[DTO_INDEX_INSERT];
6445
6446         /*
6447          * we can't call iget() while a transactions is running
6448          * (this can lead to a deadlock), but we need to know
6449          * inum and object type. so we find this information at
6450          * declaration and cache in per-thread info
6451          */
6452         idc = osd_idc_find_or_init(env, osd, fid);
6453         if (IS_ERR(idc))
6454                 RETURN(PTR_ERR(idc));
6455         if (idc->oic_remote) {
6456                 /*
6457                  * a reference to remote inode is represented by an
6458                  * agent inode which we have to create
6459                  */
6460                 credits += osd_dto_credits_noquota[DTO_OBJECT_CREATE];
6461                 credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
6462         }
6463
6464         osd_trans_declare_op(env, oh, OSD_OT_INSERT, credits);
6465
6466         if (osd_dt_obj(dt)->oo_inode != NULL) {
6467                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
6468
6469                 /*
6470                  * We ignore block quota on meta pool (MDTs), so needn't
6471                  * calculate how many blocks will be consumed by this index
6472                  * insert
6473                  */
6474                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
6475                                            i_gid_read(inode),
6476                                            i_projid_read(inode), 0,
6477                                            oh, osd_dt_obj(dt), NULL,
6478                                            OSD_QID_BLK);
6479                 if (rc)
6480                         RETURN(rc);
6481
6482 #ifdef HAVE_PROJECT_QUOTA
6483                 /*
6484                  * Reserve credits for local agent inode to transfer
6485                  * to 0, quota enforcement is ignored in this case.
6486                  */
6487                 if (idc->oic_remote &&
6488                     LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
6489                     i_projid_read(inode) != 0)
6490                         rc = osd_declare_attr_qid(env, osd_dt_obj(dt), oh,
6491                                                   0, i_projid_read(inode),
6492                                                   0, false, PRJQUOTA);
6493 #endif
6494         }
6495
6496         RETURN(rc);
6497 }
6498
6499 /**
6500  * Index add function for interoperability mode (b11826).
6501  * It will add the directory entry.This entry is needed to
6502  * maintain name->fid mapping.
6503  *
6504  * \param key it is key i.e. file entry to be inserted
6505  * \param rec it is value of given key i.e. fid
6506  *
6507  * \retval   0, on success
6508  * \retval -ve, on error
6509  */
6510 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
6511                                const struct dt_rec *rec,
6512                                const struct dt_key *key, struct thandle *th)
6513 {
6514         struct osd_object *obj = osd_dt_obj(dt);
6515         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
6516         struct dt_insert_rec *rec1 = (struct dt_insert_rec *)rec;
6517         const struct lu_fid *fid = rec1->rec_fid;
6518         const char *name = (const char *)key;
6519         struct osd_thread_info *oti = osd_oti_get(env);
6520         struct inode *child_inode = NULL;
6521         struct osd_idmap_cache *idc;
6522         int rc;
6523
6524         ENTRY;
6525
6526         if (!dt_object_exists(dt))
6527                 RETURN(-ENOENT);
6528
6529         LASSERT(osd_invariant(obj));
6530         LASSERT(!dt_object_remote(dt));
6531         LASSERT(th != NULL);
6532
6533         osd_trans_exec_op(env, th, OSD_OT_INSERT);
6534
6535         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!\n", PFID(fid));
6536
6537         idc = osd_idc_find(env, osd, fid);
6538         if (unlikely(idc == NULL)) {
6539                 idc = osd_idc_find_or_init(env, osd, fid);
6540                 if (IS_ERR(idc)) {
6541                         /*
6542                          * this dt_insert() wasn't declared properly, so
6543                          * FID is missing in OI cache. we better do not
6544                          * lookup FID in FLDB/OI and don't risk to deadlock,
6545                          * but in some special cases (lfsck testing, etc)
6546                          * it's much simpler than fixing a caller.
6547                          *
6548                          * normally this error should be placed after the first
6549                          * find, but migrate may attach source stripes to
6550                          * target, which doesn't create stripes.
6551                          */
6552                         CERROR("%s: "DFID" wasn't declared for insert\n",
6553                                osd_name(osd), PFID(fid));
6554                         dump_stack();
6555                         RETURN(PTR_ERR(idc));
6556                 }
6557         }
6558
6559         if (idc->oic_remote) {
6560                 /* Insert remote entry */
6561                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
6562                         child_inode =
6563                         igrab(osd->od_mdt_map->omm_remote_parent->d_inode);
6564                 } else {
6565                         child_inode = osd_create_local_agent_inode(env, osd,
6566                                         obj, fid, rec1->rec_type & S_IFMT, th);
6567                         if (IS_ERR(child_inode))
6568                                 RETURN(PTR_ERR(child_inode));
6569                 }
6570         } else {
6571                 /* Insert local entry */
6572                 if (unlikely(idc->oic_lid.oii_ino == 0)) {
6573                         /* for a reason OI cache wasn't filled properly */
6574                         CERROR("%s: OIC for "DFID" isn't filled\n",
6575                                osd_name(osd), PFID(fid));
6576                         RETURN(-EINVAL);
6577                 }
6578                 child_inode = oti->oti_inode;
6579                 if (unlikely(child_inode == NULL)) {
6580                         struct ldiskfs_inode_info *lii;
6581
6582                         OBD_ALLOC_PTR(lii);
6583                         if (lii == NULL)
6584                                 RETURN(-ENOMEM);
6585                         child_inode = oti->oti_inode = &lii->vfs_inode;
6586                 }
6587                 child_inode->i_sb = osd_sb(osd);
6588                 child_inode->i_ino = idc->oic_lid.oii_ino;
6589                 child_inode->i_mode = rec1->rec_type & S_IFMT;
6590         }
6591
6592         rc = osd_ea_add_rec(env, obj, child_inode, name, fid, th);
6593
6594         CDEBUG(D_INODE, "parent %lu insert %s:%lu rc = %d\n",
6595                obj->oo_inode->i_ino, name, child_inode->i_ino, rc);
6596
6597         if (child_inode && child_inode != oti->oti_inode)
6598                 iput(child_inode);
6599         LASSERT(osd_invariant(obj));
6600         osd_trans_exec_check(env, th, OSD_OT_INSERT);
6601
6602         RETURN(rc);
6603 }
6604
6605 /**
6606  *  Initialize osd Iterator for given osd index object.
6607  *
6608  *  \param  dt      osd index object
6609  */
6610
6611 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
6612                                      struct dt_object *dt,
6613                                      __u32 unused)
6614 {
6615         struct osd_it_iam *it;
6616         struct osd_object *obj = osd_dt_obj(dt);
6617         struct lu_object *lo = &dt->do_lu;
6618         struct iam_path_descr *ipd;
6619         struct iam_container *bag = &obj->oo_dir->od_container;
6620
6621         if (!dt_object_exists(dt))
6622                 return ERR_PTR(-ENOENT);
6623
6624         OBD_ALLOC_PTR(it);
6625         if (it == NULL)
6626                 return ERR_PTR(-ENOMEM);
6627
6628         ipd = osd_it_ipd_get(env, bag);
6629         if (likely(ipd != NULL)) {
6630                 it->oi_obj = obj;
6631                 it->oi_ipd = ipd;
6632                 lu_object_get(lo);
6633                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
6634                 return (struct dt_it *)it;
6635         } else {
6636                 OBD_FREE_PTR(it);
6637                 return ERR_PTR(-ENOMEM);
6638         }
6639 }
6640
6641 /**
6642  * free given Iterator.
6643  */
6644 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
6645 {
6646         struct osd_it_iam *it  = (struct osd_it_iam *)di;
6647         struct osd_object *obj = it->oi_obj;
6648
6649         iam_it_fini(&it->oi_it);
6650         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
6651         osd_object_put(env, obj);
6652         OBD_FREE_PTR(it);
6653 }
6654
6655 /**
6656  *  Move Iterator to record specified by \a key
6657  *
6658  *  \param  di      osd iterator
6659  *  \param  key     key for index
6660  *
6661  *  \retval +ve  di points to record with least key not larger than key
6662  *  \retval  0   di points to exact matched key
6663  *  \retval -ve  failure
6664  */
6665
6666 static int osd_it_iam_get(const struct lu_env *env,
6667                           struct dt_it *di, const struct dt_key *key)
6668 {
6669         struct osd_thread_info *oti = osd_oti_get(env);
6670         struct osd_it_iam *it = (struct osd_it_iam *)di;
6671
6672         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
6673                 /* swab quota uid/gid */
6674                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
6675                 key = (struct dt_key *)&oti->oti_quota_id;
6676         }
6677
6678         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
6679 }
6680
6681 /**
6682  *  Release Iterator
6683  *
6684  *  \param  di      osd iterator
6685  */
6686 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
6687 {
6688         struct osd_it_iam *it = (struct osd_it_iam *)di;
6689
6690         iam_it_put(&it->oi_it);
6691 }
6692
6693 /**
6694  *  Move iterator by one record
6695  *
6696  *  \param  di      osd iterator
6697  *
6698  *  \retval +1   end of container reached
6699  *  \retval  0   success
6700  *  \retval -ve  failure
6701  */
6702
6703 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
6704 {
6705         struct osd_it_iam *it = (struct osd_it_iam *)di;
6706
6707         return iam_it_next(&it->oi_it);
6708 }
6709
6710 /**
6711  * Return pointer to the key under iterator.
6712  */
6713
6714 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
6715                                      const struct dt_it *di)
6716 {
6717         struct osd_thread_info *oti = osd_oti_get(env);
6718         struct osd_it_iam *it = (struct osd_it_iam *)di;
6719         struct osd_object *obj = it->oi_obj;
6720         struct dt_key *key;
6721
6722         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
6723
6724         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
6725                 /* swab quota uid/gid */
6726                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
6727                 key = (struct dt_key *)&oti->oti_quota_id;
6728         }
6729
6730         return key;
6731 }
6732
6733 /**
6734  * Return size of key under iterator (in bytes)
6735  */
6736
6737 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
6738 {
6739         struct osd_it_iam *it = (struct osd_it_iam *)di;
6740
6741         return iam_it_key_size(&it->oi_it);
6742 }
6743
6744 static inline void
6745 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
6746 {
6747         /* check if file type is required */
6748         if (ent->lde_attrs & LUDA_TYPE) {
6749                 struct luda_type *lt;
6750                 int align = sizeof(*lt) - 1;
6751
6752                 len = (len + align) & ~align;
6753                 lt = (struct luda_type *)(ent->lde_name + len);
6754                 lt->lt_type = cpu_to_le16(DTTOIF(type));
6755         }
6756
6757         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
6758 }
6759
6760 /**
6761  * build lu direct from backend fs dirent.
6762  */
6763
6764 static inline void
6765 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
6766                    char *name, __u16 namelen, __u16 type, __u32 attr)
6767 {
6768         ent->lde_attrs = attr | LUDA_FID;
6769         fid_cpu_to_le(&ent->lde_fid, fid);
6770
6771         ent->lde_hash = cpu_to_le64(offset);
6772         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
6773
6774         strncpy(ent->lde_name, name, namelen);
6775         ent->lde_name[namelen] = '\0';
6776         ent->lde_namelen = cpu_to_le16(namelen);
6777
6778         /* append lustre attributes */
6779         osd_it_append_attrs(ent, namelen, type);
6780 }
6781
6782 /**
6783  * Return pointer to the record under iterator.
6784  */
6785 static int osd_it_iam_rec(const struct lu_env *env,
6786                           const struct dt_it *di,
6787                           struct dt_rec *dtrec, __u32 attr)
6788 {
6789         struct osd_it_iam *it = (struct osd_it_iam *)di;
6790         struct osd_thread_info *info = osd_oti_get(env);
6791
6792         ENTRY;
6793
6794         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
6795                 const struct osd_fid_pack *rec;
6796                 struct lu_fid *fid = &info->oti_fid;
6797                 struct lu_dirent *lde = (struct lu_dirent *)dtrec;
6798                 char *name;
6799                 int namelen;
6800                 __u64 hash;
6801                 int rc;
6802
6803                 name = (char *)iam_it_key_get(&it->oi_it);
6804                 if (IS_ERR(name))
6805                         RETURN(PTR_ERR(name));
6806
6807                 namelen = iam_it_key_size(&it->oi_it);
6808
6809                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
6810                 if (IS_ERR(rec))
6811                         RETURN(PTR_ERR(rec));
6812
6813                 rc = osd_fid_unpack(fid, rec);
6814                 if (rc)
6815                         RETURN(rc);
6816
6817                 hash = iam_it_store(&it->oi_it);
6818
6819                 /* IAM does not store object type in IAM index (dir) */
6820                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
6821                                    0, LUDA_FID);
6822         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
6823                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
6824                            (struct iam_rec *)dtrec);
6825                 osd_quota_unpack(it->oi_obj, dtrec);
6826         } else {
6827                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
6828                            (struct iam_rec *)dtrec);
6829         }
6830
6831         RETURN(0);
6832 }
6833
6834 /**
6835  * Returns cookie for current Iterator position.
6836  */
6837 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
6838 {
6839         struct osd_it_iam *it = (struct osd_it_iam *)di;
6840
6841         return iam_it_store(&it->oi_it);
6842 }
6843
6844 /**
6845  * Restore iterator from cookie.
6846  *
6847  * \param  di      osd iterator
6848  * \param  hash    Iterator location cookie
6849  *
6850  * \retval +ve  di points to record with least key not larger than key.
6851  * \retval  0   di points to exact matched key
6852  * \retval -ve  failure
6853  */
6854
6855 static int osd_it_iam_load(const struct lu_env *env,
6856                            const struct dt_it *di, __u64 hash)
6857 {
6858         struct osd_it_iam *it = (struct osd_it_iam *)di;
6859
6860         return iam_it_load(&it->oi_it, hash);
6861 }
6862
6863 static const struct dt_index_operations osd_index_iam_ops = {
6864         .dio_lookup         = osd_index_iam_lookup,
6865         .dio_declare_insert = osd_index_declare_iam_insert,
6866         .dio_insert         = osd_index_iam_insert,
6867         .dio_declare_delete = osd_index_declare_iam_delete,
6868         .dio_delete         = osd_index_iam_delete,
6869         .dio_it     = {
6870                 .init     = osd_it_iam_init,
6871                 .fini     = osd_it_iam_fini,
6872                 .get      = osd_it_iam_get,
6873                 .put      = osd_it_iam_put,
6874                 .next     = osd_it_iam_next,
6875                 .key      = osd_it_iam_key,
6876                 .key_size = osd_it_iam_key_size,
6877                 .rec      = osd_it_iam_rec,
6878                 .store    = osd_it_iam_store,
6879                 .load     = osd_it_iam_load
6880         }
6881 };
6882
6883 struct osd_it_ea *osd_it_dir_init(const struct lu_env *env,
6884                                   struct osd_device *dev,
6885                                   struct inode *inode, u32 attr)
6886 {
6887         struct osd_thread_info *info = osd_oti_get(env);
6888         struct osd_it_ea *oie;
6889         struct file *file;
6890
6891         ENTRY;
6892         file = alloc_file_pseudo(inode, dev->od_mnt, "/", O_NOATIME,
6893                                  inode->i_fop);
6894         if (IS_ERR(file))
6895                 RETURN(ERR_CAST(file));
6896
6897         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
6898         if (attr & LUDA_64BITHASH)
6899                 file->f_mode |= FMODE_64BITHASH;
6900         else
6901                 file->f_mode |= FMODE_32BITHASH;
6902         ihold(inode);
6903
6904         OBD_SLAB_ALLOC_PTR(oie, osd_itea_cachep);
6905         if (!oie)
6906                 goto out_fput;
6907
6908         oie->oie_rd_dirent       = 0;
6909         oie->oie_it_dirent       = 0;
6910         oie->oie_dirent          = NULL;
6911         if (unlikely(!info->oti_it_ea_buf_used)) {
6912                 oie->oie_buf = info->oti_it_ea_buf;
6913                 info->oti_it_ea_buf_used = 1;
6914         } else {
6915                 OBD_ALLOC(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6916                 if (!oie->oie_buf)
6917                         goto out_free;
6918         }
6919         oie->oie_obj = NULL;
6920         oie->oie_file = file;
6921
6922         RETURN(oie);
6923
6924 out_free:
6925         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
6926 out_fput:
6927         fput(file);
6928
6929         return ERR_PTR(-ENOMEM);
6930 }
6931
6932 /**
6933  * Creates or initializes iterator context.
6934  *
6935  * \retval struct osd_it_ea, iterator structure on success
6936  *
6937  */
6938 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
6939                                     struct dt_object *dt,
6940                                     __u32 attr)
6941 {
6942         struct osd_object *obj = osd_dt_obj(dt);
6943         struct osd_device *dev = osd_obj2dev(obj);
6944         struct lu_object *lo = &dt->do_lu;
6945         struct osd_it_ea *oie;
6946
6947         ENTRY;
6948
6949         if (!dt_object_exists(dt) || obj->oo_destroyed)
6950                 RETURN(ERR_PTR(-ENOENT));
6951
6952         oie = osd_it_dir_init(env, dev, obj->oo_inode, attr);
6953         if (IS_ERR(oie))
6954                 RETURN(ERR_CAST(oie));
6955
6956         oie->oie_obj = obj;
6957         lu_object_get(lo);
6958         RETURN((struct dt_it *)oie);
6959 }
6960
6961 void osd_it_dir_fini(const struct lu_env *env, struct osd_it_ea *oie,
6962                      struct inode *inode)
6963 {
6964         struct osd_thread_info *info = osd_oti_get(env);
6965
6966         ENTRY;
6967         fput(oie->oie_file);
6968         if (unlikely(oie->oie_buf != info->oti_it_ea_buf))
6969                 OBD_FREE(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6970         else
6971                 info->oti_it_ea_buf_used = 0;
6972         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
6973         EXIT;
6974 }
6975
6976 /**
6977  * Destroy or finishes iterator context.
6978  *
6979  * \param di iterator structure to be destroyed
6980  */
6981 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
6982 {
6983         struct osd_it_ea *oie = (struct osd_it_ea *)di;
6984         struct osd_object *obj = oie->oie_obj;
6985         struct inode *inode = obj->oo_inode;
6986
6987         ENTRY;
6988         osd_it_dir_fini(env, (struct osd_it_ea *)di, inode);
6989         osd_object_put(env, obj);
6990         EXIT;
6991 }
6992
6993 /**
6994  * It position the iterator at given key, so that next lookup continues from
6995  * that key Or it is similar to dio_it->load() but based on a key,
6996  * rather than file position.
6997  *
6998  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
6999  * to the beginning.
7000  *
7001  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
7002  */
7003 static int osd_it_ea_get(const struct lu_env *env,
7004                          struct dt_it *di, const struct dt_key *key)
7005 {
7006         struct osd_it_ea *it = (struct osd_it_ea *)di;
7007
7008         ENTRY;
7009         LASSERT(((const char *)key)[0] == '\0');
7010         it->oie_file->f_pos = 0;
7011         it->oie_rd_dirent = 0;
7012         it->oie_it_dirent = 0;
7013         it->oie_dirent = NULL;
7014
7015         RETURN(+1);
7016 }
7017
7018 /**
7019  * Does nothing
7020  */
7021 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
7022 {
7023 }
7024
7025 struct osd_filldir_cbs {
7026         struct dir_context ctx;
7027         struct osd_it_ea  *it;
7028 };
7029 /**
7030  * It is called internally by ->iterate*(). It fills the
7031  * iterator's in-memory data structure with required
7032  * information i.e. name, namelen, rec_size etc.
7033  *
7034  * \param buf in which information to be filled in.
7035  * \param name name of the file in given dir
7036  *
7037  * \retval 0 on success
7038  * \retval 1 on buffer full
7039  */
7040 #ifdef HAVE_FILLDIR_USE_CTX
7041 static int osd_ldiskfs_filldir(struct dir_context *ctx,
7042 #else
7043 static int osd_ldiskfs_filldir(void *ctx,
7044 #endif
7045                                const char *name, int namelen,
7046                                loff_t offset, __u64 ino, unsigned int d_type)
7047 {
7048         struct osd_it_ea *it = ((struct osd_filldir_cbs *)ctx)->it;
7049         struct osd_object *obj = it->oie_obj;
7050         struct osd_it_ea_dirent *ent = it->oie_dirent;
7051         struct lu_fid *fid = &ent->oied_fid;
7052         char *buf = it->oie_buf;
7053         struct osd_fid_pack *rec;
7054         ENTRY;
7055
7056         /* this should never happen */
7057         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
7058                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
7059                 RETURN(-EIO);
7060         }
7061
7062         /* Check for enough space. Note oied_name is not NUL terminated. */
7063         if (&ent->oied_name[namelen] > buf + OSD_IT_EA_BUFSIZE)
7064                 RETURN(1);
7065
7066         /* "." is just the object itself. */
7067         if (namelen == 1 && name[0] == '.') {
7068                 if (obj != NULL)
7069                         *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
7070         } else if (d_type & LDISKFS_DIRENT_LUFID) {
7071                 rec = (struct osd_fid_pack *)(name + namelen + 1);
7072                 if (osd_fid_unpack(fid, rec) != 0)
7073                         fid_zero(fid);
7074         } else {
7075                 fid_zero(fid);
7076         }
7077         d_type &= ~LDISKFS_DIRENT_LUFID;
7078
7079         /* NOT export local root. */
7080         if (obj != NULL &&
7081             unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
7082                 ino = obj->oo_inode->i_ino;
7083                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
7084         }
7085
7086         if (obj == NULL || !(obj->oo_lma_flags & LUSTRE_ENCRYPT_FL)) {
7087                 ent->oied_namelen = namelen;
7088                 memcpy(ent->oied_name, name, namelen);
7089         } else {
7090                 int encoded_namelen = critical_chars(name, namelen);
7091
7092                 /* Check again for enough space. */
7093                 if (&ent->oied_name[encoded_namelen] > buf + OSD_IT_EA_BUFSIZE)
7094                         RETURN(1);
7095
7096                 ent->oied_namelen = encoded_namelen;
7097
7098                 if (encoded_namelen == namelen)
7099                         memcpy(ent->oied_name, name, namelen);
7100                 else
7101                         critical_encode(name, namelen, ent->oied_name);
7102         }
7103
7104         ent->oied_ino     = ino;
7105         ent->oied_off     = offset;
7106         ent->oied_type    = d_type;
7107
7108         it->oie_rd_dirent++;
7109         it->oie_dirent = (void *)ent + cfs_size_round(sizeof(*ent) + ent->oied_namelen);
7110         RETURN(0);
7111 }
7112
7113 /**
7114  * Calls ->iterate*() to load a directory entry at a time
7115  * and stored it in iterator's in-memory data structure.
7116  *
7117  * \param di iterator's in memory structure
7118  *
7119  * \retval   0 on success
7120  * \retval -ve on error
7121  * \retval +1 reach the end of entry
7122  */
7123 int osd_ldiskfs_it_fill(const struct lu_env *env, const struct dt_it *di)
7124 {
7125         struct osd_it_ea *it = (struct osd_it_ea *)di;
7126         struct osd_object *obj = it->oie_obj;
7127         struct htree_lock *hlock = NULL;
7128         struct file *filp = it->oie_file;
7129         int rc = 0;
7130         struct osd_filldir_cbs buf = {
7131                 .ctx.actor = osd_ldiskfs_filldir,
7132                 .it = it
7133         };
7134
7135         ENTRY;
7136         it->oie_dirent = it->oie_buf;
7137         it->oie_rd_dirent = 0;
7138
7139         if (obj) {
7140                 if (obj->oo_hl_head != NULL) {
7141                         hlock = osd_oti_get(env)->oti_hlock;
7142                         ldiskfs_htree_lock(hlock, obj->oo_hl_head,
7143                                            obj->oo_inode,
7144                                            LDISKFS_HLOCK_READDIR);
7145                 } else {
7146                         down_read(&obj->oo_ext_idx_sem);
7147                 }
7148         }
7149
7150         rc = iterate_dir(filp, &buf.ctx);
7151         if (rc)
7152                 GOTO(unlock, rc);
7153
7154         if (it->oie_rd_dirent == 0) {
7155                 /*
7156                  * If it does not get any dirent, it means it has been reached
7157                  * to the end of the dir
7158                  */
7159                 it->oie_file->f_pos = ldiskfs_get_htree_eof(it->oie_file);
7160                 if (rc == 0)
7161                         rc = 1;
7162         } else {
7163                 it->oie_dirent = it->oie_buf;
7164                 it->oie_it_dirent = 1;
7165         }
7166 unlock:
7167         if (obj) {
7168                 if (hlock != NULL)
7169                         ldiskfs_htree_unlock(hlock);
7170                 else
7171                         up_read(&obj->oo_ext_idx_sem);
7172         }
7173
7174         RETURN(rc);
7175 }
7176
7177 /**
7178  * It calls osd_ldiskfs_it_fill() which will use ->iterate*()
7179  * to load a directory entry at a time and stored it in
7180  * iterator's in-memory data structure.
7181  *
7182  * \param di iterator's in memory structure
7183  *
7184  * \retval +ve iterator reached to end
7185  * \retval   0 iterator not reached to end
7186  * \retval -ve on error
7187  */
7188 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
7189 {
7190         struct osd_it_ea *it = (struct osd_it_ea *)di;
7191         int rc;
7192
7193         ENTRY;
7194
7195         if (it->oie_it_dirent < it->oie_rd_dirent) {
7196                 it->oie_dirent =
7197                         (void *)it->oie_dirent +
7198                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
7199                                        it->oie_dirent->oied_namelen);
7200                 it->oie_it_dirent++;
7201                 rc = 0;
7202         } else {
7203                 if (it->oie_file->f_pos == ldiskfs_get_htree_eof(it->oie_file))
7204                         rc = 1;
7205                 else
7206                         rc = osd_ldiskfs_it_fill(env, di);
7207         }
7208
7209         RETURN(rc);
7210 }
7211
7212 /**
7213  * Returns the key at current position from iterator's in memory structure.
7214  *
7215  * \param di iterator's in memory structure
7216  *
7217  * \retval key i.e. struct dt_key on success
7218  */
7219 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
7220                                     const struct dt_it *di)
7221 {
7222         struct osd_it_ea *it = (struct osd_it_ea *)di;
7223
7224         return (struct dt_key *)it->oie_dirent->oied_name;
7225 }
7226
7227 /**
7228  * Returns key's size at current position from iterator's in memory structure.
7229  *
7230  * \param di iterator's in memory structure
7231  *
7232  * \retval key_size i.e. struct dt_key on success
7233  */
7234 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
7235 {
7236         struct osd_it_ea *it = (struct osd_it_ea *)di;
7237
7238         return it->oie_dirent->oied_namelen;
7239 }
7240
7241 #if defined LDISKFS_DIR_ENTRY_LEN && defined LDISKFS_DIR_ENTRY_LEN_
7242 #undef LDISKFS_DIR_REC_LEN
7243 # if defined LDISKFS_DIR_REC_LEN_WITH_DIR
7244 #  define LDISKFS_DIR_REC_LEN(de, dir)  LDISKFS_DIR_ENTRY_LEN_((de), (dir))
7245 # else
7246 #  define LDISKFS_DIR_REC_LEN(de)       LDISKFS_DIR_ENTRY_LEN_((de))
7247 # endif
7248 #endif
7249
7250 #if defined LDISKFS_DIR_REC_LEN_WITH_DIR
7251 # define LDISKFS_DIR_REC_LEN_DIR(de)    LDISKFS_DIR_REC_LEN((de), NULL)
7252 #else
7253 # define LDISKFS_DIR_REC_LEN_DIR(de)    LDISKFS_DIR_REC_LEN((de))
7254 #endif
7255
7256 static inline bool osd_dotdot_has_space(struct ldiskfs_dir_entry_2 *de)
7257 {
7258         if (LDISKFS_DIR_REC_LEN_DIR(de) >=
7259             __LDISKFS_DIR_REC_LEN(2 + 1 + sizeof(struct osd_fid_pack)))
7260                 return true;
7261
7262         return false;
7263 }
7264
7265 static inline bool
7266 osd_dirent_has_space(struct ldiskfs_dir_entry_2 *de, __u16 namelen,
7267                      unsigned int blocksize, bool dotdot)
7268 {
7269         if (dotdot)
7270                 return osd_dotdot_has_space(de);
7271
7272         if (ldiskfs_rec_len_from_disk(de->rec_len, blocksize) >=
7273             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
7274                 return true;
7275
7276         return false;
7277 }
7278
7279 static int
7280 osd_dirent_reinsert(const struct lu_env *env, struct osd_device *dev,
7281                     handle_t *jh, struct dentry *dentry,
7282                     const struct lu_fid *fid, struct buffer_head *bh,
7283                     struct ldiskfs_dir_entry_2 *de, struct htree_lock *hlock,
7284                     bool dotdot)
7285 {
7286         struct inode *dir = dentry->d_parent->d_inode;
7287         struct inode *inode = dentry->d_inode;
7288         struct osd_fid_pack *rec;
7289         struct ldiskfs_dentry_param *ldp;
7290         int namelen = dentry->d_name.len;
7291         int rc;
7292         struct osd_thread_info *info = osd_oti_get(env);
7293
7294         ENTRY;
7295
7296         if (!ldiskfs_has_feature_dirdata(inode->i_sb))
7297                 RETURN(0);
7298
7299         /* There is enough space to hold the FID-in-dirent. */
7300         if (osd_dirent_has_space(de, namelen, dir->i_sb->s_blocksize, dotdot)) {
7301                 rc = osd_ldiskfs_journal_get_write_access(jh, dir->i_sb, bh,
7302                                                           LDISKFS_JTR_NONE);
7303                 if (rc != 0)
7304                         RETURN(rc);
7305
7306                 de->name[namelen] = 0;
7307                 rec = (struct osd_fid_pack *)(de->name + namelen + 1);
7308                 rec->fp_len = sizeof(struct lu_fid) + 1;
7309                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
7310                 de->file_type |= LDISKFS_DIRENT_LUFID;
7311                 rc = ldiskfs_handle_dirty_metadata(jh, NULL, bh);
7312
7313                 RETURN(rc);
7314         }
7315
7316         LASSERT(!dotdot);
7317
7318         rc = ldiskfs_delete_entry(jh, dir, de, bh);
7319         if (rc != 0)
7320                 RETURN(rc);
7321
7322         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
7323         osd_get_ldiskfs_dirent_param(ldp, fid);
7324         dentry->d_fsdata = (void *)ldp;
7325         dquot_initialize(dir);
7326         rc = osd_ldiskfs_add_entry(info, dev, jh, dentry, inode, hlock);
7327         /*
7328          * It is too bad, we cannot reinsert the name entry back.
7329          * That means we lose it!
7330          */
7331         if (rc != 0)
7332                 CDEBUG(D_LFSCK,
7333                        "%s: fail to reinsert the dirent, dir = %lu/%u, name = %.*s, "DFID": rc = %d\n",
7334                        osd_ino2name(inode), dir->i_ino, dir->i_generation,
7335                        namelen, dentry->d_name.name, PFID(fid), rc);
7336
7337         RETURN(rc);
7338 }
7339
7340 static int
7341 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
7342                         struct osd_it_ea *it, struct lu_fid *fid,
7343                         struct osd_inode_id *id, __u32 *attr)
7344 {
7345         struct osd_thread_info *info = osd_oti_get(env);
7346         struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
7347         struct osd_device *dev = osd_obj2dev(obj);
7348         struct super_block *sb = osd_sb(dev);
7349         const char *devname = osd_name(dev);
7350         struct osd_it_ea_dirent *ent = it->oie_dirent;
7351         struct inode *dir = obj->oo_inode;
7352         struct htree_lock *hlock = NULL;
7353         struct buffer_head *bh = NULL;
7354         handle_t *jh = NULL;
7355         struct ldiskfs_dir_entry_2 *de;
7356         struct dentry *dentry;
7357         struct inode *inode;
7358         const struct lu_fid *pfid = lu_object_fid(&obj->oo_dt.do_lu);
7359         int credits;
7360         int rc;
7361         bool dotdot = false;
7362         bool dirty = false;
7363         struct lu_name ln;
7364
7365         ENTRY;
7366
7367         if (ent->oied_name[0] == '.') {
7368                 if (ent->oied_namelen == 1)
7369                         RETURN(0);
7370
7371                 if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
7372                         dotdot = true;
7373         }
7374
7375         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
7376         inode = osd_iget(info, dev, id);
7377         if (IS_ERR(inode)) {
7378                 rc = PTR_ERR(inode);
7379                 if (rc == -ENOENT || rc == -ESTALE) {
7380                         /*
7381                          * Maybe dangling name entry, or
7382                          * corrupted directory entry.
7383                          */
7384                         *attr |= LUDA_UNKNOWN;
7385                         rc = 0;
7386                 } else {
7387                         CDEBUG(D_LFSCK, "%s: fail to iget() for dirent "
7388                                "check_repair, dir = %lu/%u, name = %.*s, "
7389                                "ino = %llu, rc = %d\n",
7390                                devname, dir->i_ino, dir->i_generation,
7391                                ent->oied_namelen, ent->oied_name,
7392                                ent->oied_ino, rc);
7393                 }
7394
7395                 RETURN(rc);
7396         }
7397
7398         rc = obj_name2lu_name(obj, ent->oied_name, ent->oied_namelen, &ln);
7399         if (rc)
7400                 RETURN(rc);
7401
7402         dentry = osd_child_dentry_by_inode(env, dir, ln.ln_name, ln.ln_namelen);
7403         rc = osd_get_lma(info, inode, dentry, &info->oti_ost_attrs);
7404         if (rc == -ENODATA || !fid_is_sane(&lma->lma_self_fid))
7405                 lma = NULL;
7406         else if (rc != 0)
7407                 GOTO(out, rc);
7408
7409         /*
7410          * We need to ensure that the name entry is still valid.
7411          * Because it may be removed or renamed by other already.
7412          *
7413          * The unlink or rename operation will start journal before PDO lock,
7414          * so to avoid deadlock, here we need to start journal handle before
7415          * related PDO lock also. But because we do not know whether there
7416          * will be something to be repaired before PDO lock, we just start
7417          * journal without conditions.
7418          *
7419          * We may need to remove the name entry firstly, then insert back.
7420          * One credit is for user quota file update.
7421          * One credit is for group quota file update.
7422          * Two credits are for dirty inode.
7423          */
7424         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
7425                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
7426
7427         if (dev->od_dirent_journal != 0) {
7428
7429 again:
7430                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
7431                 if (IS_ERR(jh)) {
7432                         rc = PTR_ERR(jh);
7433                         CDEBUG(D_LFSCK, "%s: fail to start trans for dirent "
7434                                "check_repair, dir = %lu/%u, credits = %d, "
7435                                "name = %.*s, ino = %llu: rc = %d\n",
7436                                devname, dir->i_ino, dir->i_generation, credits,
7437                                ent->oied_namelen, ent->oied_name,
7438                                ent->oied_ino, rc);
7439
7440                         GOTO(out_inode, rc);
7441                 }
7442
7443                 if (obj->oo_hl_head != NULL) {
7444                         hlock = osd_oti_get(env)->oti_hlock;
7445                         /*
7446                          * "0" means exclusive lock for the whole directory.
7447                          * We need to prevent others access such name entry
7448                          * during the delete + insert. Neither HLOCK_ADD nor
7449                          * HLOCK_DEL cannot guarantee the atomicity.
7450                          */
7451                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
7452                 } else {
7453                         down_write(&obj->oo_ext_idx_sem);
7454                 }
7455         } else {
7456                 if (obj->oo_hl_head != NULL) {
7457                         hlock = osd_oti_get(env)->oti_hlock;
7458                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
7459                                            LDISKFS_HLOCK_LOOKUP);
7460                 } else {
7461                         down_read(&obj->oo_ext_idx_sem);
7462                 }
7463         }
7464
7465         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
7466         if (IS_ERR(bh) || le32_to_cpu(de->inode) != inode->i_ino) {
7467                 *attr |= LUDA_IGNORE;
7468
7469                 GOTO(out, rc = 0);
7470         }
7471
7472         /*
7473          * For dotdot entry, if there is not enough space to hold the
7474          * FID-in-dirent, just keep them there. It only happens when the
7475          * device upgraded from 1.8 or restored from MDT file-level backup.
7476          * For the whole directory, only dotdot entry have no FID-in-dirent
7477          * and needs to get FID from LMA when readdir, it will not affect the
7478          * performance much.
7479          */
7480         if (dotdot && !osd_dotdot_has_space(de)) {
7481                 *attr |= LUDA_UNKNOWN;
7482
7483                 GOTO(out, rc = 0);
7484         }
7485
7486         if (lma != NULL) {
7487                 if (lu_fid_eq(fid, &lma->lma_self_fid))
7488                         GOTO(out, rc = 0);
7489
7490                 if (unlikely(lma->lma_compat & LMAC_NOT_IN_OI)) {
7491                         struct lu_fid *tfid = &lma->lma_self_fid;
7492
7493                         if (likely(dotdot &&
7494                                    fid_seq(tfid) == FID_SEQ_LOCAL_FILE &&
7495                                    fid_oid(tfid) == REMOTE_PARENT_DIR_OID)) {
7496                                 /*
7497                                  * It must be REMOTE_PARENT_DIR and as the
7498                                  * 'dotdot' entry of remote directory
7499                                  */
7500                                 *attr |= LUDA_IGNORE;
7501                         } else {
7502                                 CDEBUG(D_LFSCK, "%s: expect remote agent "
7503                                        "parent directory, but got %.*s under "
7504                                        "dir = %lu/%u with the FID "DFID"\n",
7505                                        devname, ent->oied_namelen,
7506                                        ent->oied_name, dir->i_ino,
7507                                        dir->i_generation, PFID(tfid));
7508
7509                                 *attr |= LUDA_UNKNOWN;
7510                         }
7511
7512                         GOTO(out, rc = 0);
7513                 }
7514         }
7515
7516         if (!fid_is_zero(fid)) {
7517                 rc = osd_verify_ent_by_linkea(env, inode, pfid, ent->oied_name,
7518                                               ent->oied_namelen);
7519                 if (rc == -ENOENT ||
7520                     (rc == -ENODATA &&
7521                      !(dev->od_scrub.os_scrub.os_file.sf_flags & SF_UPGRADE))) {
7522                         /*
7523                          * linkEA does not recognize the dirent entry,
7524                          * it may because the dirent entry corruption
7525                          * and points to other's inode.
7526                          */
7527                         CDEBUG(D_LFSCK, "%s: the target inode does not "
7528                                "recognize the dirent, dir = %lu/%u, "
7529                                " name = %.*s, ino = %llu, "
7530                                DFID": rc = %d\n", devname, dir->i_ino,
7531                                dir->i_generation, ent->oied_namelen,
7532                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
7533                         *attr |= LUDA_UNKNOWN;
7534
7535                         GOTO(out, rc = 0);
7536                 }
7537
7538                 if (rc && rc != -ENODATA) {
7539                         CDEBUG(D_LFSCK, "%s: fail to verify FID in the dirent, "
7540                                "dir = %lu/%u, name = %.*s, ino = %llu, "
7541                                DFID": rc = %d\n", devname, dir->i_ino,
7542                                dir->i_generation, ent->oied_namelen,
7543                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
7544                         *attr |= LUDA_UNKNOWN;
7545
7546                         GOTO(out, rc = 0);
7547                 }
7548         }
7549
7550         if (lma != NULL) {
7551                 /*
7552                  * linkEA recognizes the dirent entry, the FID-in-LMA is
7553                  * valid, trusted, in spite of fid_is_sane(fid) or not.
7554                  */
7555                 if (*attr & LUDA_VERIFY_DRYRUN) {
7556                         *fid = lma->lma_self_fid;
7557                         *attr |= LUDA_REPAIR;
7558
7559                         GOTO(out, rc = 0);
7560                 }
7561
7562                 if (jh == NULL) {
7563                         brelse(bh);
7564                         dev->od_dirent_journal = 1;
7565                         if (hlock != NULL) {
7566                                 ldiskfs_htree_unlock(hlock);
7567                                 hlock = NULL;
7568                         } else {
7569                                 up_read(&obj->oo_ext_idx_sem);
7570                         }
7571
7572                         goto again;
7573                 }
7574
7575                 *fid = lma->lma_self_fid;
7576                 dirty = true;
7577                 /* Update or append the FID-in-dirent. */
7578                 rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
7579                                          bh, de, hlock, dotdot);
7580                 if (rc == 0)
7581                         *attr |= LUDA_REPAIR;
7582                 else
7583                         CDEBUG(D_LFSCK, "%s: fail to re-insert FID after "
7584                                "the dirent, dir = %lu/%u, name = %.*s, "
7585                                "ino = %llu, "DFID": rc = %d\n",
7586                                devname, dir->i_ino, dir->i_generation,
7587                                ent->oied_namelen, ent->oied_name,
7588                                ent->oied_ino, PFID(fid), rc);
7589         } else {
7590                 /* lma is NULL, trust the FID-in-dirent if it is valid. */
7591                 if (*attr & LUDA_VERIFY_DRYRUN) {
7592                         if (fid_is_sane(fid)) {
7593                                 *attr |= LUDA_REPAIR;
7594                         } else if (dev->od_index == 0) {
7595                                 lu_igif_build(fid, inode->i_ino,
7596                                               inode->i_generation);
7597                                 *attr |= LUDA_UPGRADE;
7598                         }
7599
7600                         GOTO(out, rc = 0);
7601                 }
7602
7603                 if (jh == NULL) {
7604                         brelse(bh);
7605                         dev->od_dirent_journal = 1;
7606                         if (hlock != NULL) {
7607                                 ldiskfs_htree_unlock(hlock);
7608                                 hlock = NULL;
7609                         } else {
7610                                 up_read(&obj->oo_ext_idx_sem);
7611                         }
7612
7613                         goto again;
7614                 }
7615
7616                 dirty = true;
7617                 if (unlikely(fid_is_sane(fid))) {
7618                         /*
7619                          * FID-in-dirent exists, but FID-in-LMA is lost.
7620                          * Trust the FID-in-dirent, and add FID-in-LMA.
7621                          */
7622                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
7623                         if (rc == 0)
7624                                 *attr |= LUDA_REPAIR;
7625                         else
7626                                 CDEBUG(D_LFSCK, "%s: fail to set LMA for "
7627                                        "update dirent, dir = %lu/%u, "
7628                                        "name = %.*s, ino = %llu, "
7629                                        DFID": rc = %d\n",
7630                                        devname, dir->i_ino, dir->i_generation,
7631                                        ent->oied_namelen, ent->oied_name,
7632                                        ent->oied_ino, PFID(fid), rc);
7633                 } else if (dev->od_index == 0) {
7634                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
7635                         /*
7636                          * It is probably IGIF object. Only aappend the
7637                          * FID-in-dirent. OI scrub will process FID-in-LMA.
7638                          */
7639                         rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
7640                                                  bh, de, hlock, dotdot);
7641                         if (rc == 0)
7642                                 *attr |= LUDA_UPGRADE;
7643                         else
7644                                 CDEBUG(D_LFSCK, "%s: fail to append IGIF "
7645                                        "after the dirent, dir = %lu/%u, "
7646                                        "name = %.*s, ino = %llu, "
7647                                        DFID": rc = %d\n",
7648                                        devname, dir->i_ino, dir->i_generation,
7649                                        ent->oied_namelen, ent->oied_name,
7650                                        ent->oied_ino, PFID(fid), rc);
7651                 }
7652         }
7653
7654         GOTO(out, rc);
7655
7656 out:
7657         if (!IS_ERR(bh))
7658                 brelse(bh);
7659         if (hlock != NULL) {
7660                 ldiskfs_htree_unlock(hlock);
7661         } else {
7662                 if (dev->od_dirent_journal != 0)
7663                         up_write(&obj->oo_ext_idx_sem);
7664                 else
7665                         up_read(&obj->oo_ext_idx_sem);
7666         }
7667
7668         if (jh != NULL)
7669                 ldiskfs_journal_stop(jh);
7670
7671 out_inode:
7672         iput(inode);
7673         if (rc >= 0 && !dirty)
7674                 dev->od_dirent_journal = 0;
7675         if (ln.ln_name != ent->oied_name)
7676                 kfree(ln.ln_name);
7677
7678         return rc;
7679 }
7680
7681 /**
7682  * Returns the value at current position from iterator's in memory structure.
7683  *
7684  * \param di struct osd_it_ea, iterator's in memory structure
7685  * \param attr attr requested for dirent.
7686  * \param lde lustre dirent
7687  *
7688  * \retval   0 no error and \param lde has correct lustre dirent.
7689  * \retval -ve on error
7690  */
7691 static inline int osd_it_ea_rec(const struct lu_env *env,
7692                                 const struct dt_it *di,
7693                                 struct dt_rec *dtrec, __u32 attr)
7694 {
7695         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
7696         struct osd_object      *obj   = it->oie_obj;
7697         struct osd_device      *dev   = osd_obj2dev(obj);
7698         struct osd_thread_info *oti   = osd_oti_get(env);
7699         struct osd_inode_id    *id    = &oti->oti_id;
7700         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
7701         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
7702         __u32 ino = it->oie_dirent->oied_ino;
7703         int rc = 0;
7704
7705         ENTRY;
7706
7707         LASSERT(!is_remote_parent_ino(dev, obj->oo_inode->i_ino));
7708
7709         if (attr & LUDA_VERIFY) {
7710                 if (unlikely(is_remote_parent_ino(dev, ino))) {
7711                         attr |= LUDA_IGNORE;
7712                         /*
7713                          * If the parent is on remote MDT, and there
7714                          * is no FID-in-dirent, then we have to get
7715                          * the parent FID from the linkEA.
7716                          */
7717                         if (!fid_is_sane(fid) &&
7718                             it->oie_dirent->oied_namelen == 2 &&
7719                             it->oie_dirent->oied_name[0] == '.' &&
7720                             it->oie_dirent->oied_name[1] == '.')
7721                                 osd_get_pfid_from_linkea(env, obj, fid);
7722                 } else {
7723                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
7724                                                      &attr);
7725                 }
7726
7727                 if (!fid_is_sane(fid))
7728                         attr |= LUDA_UNKNOWN;
7729         } else {
7730                 attr &= ~LU_DIRENT_ATTRS_MASK;
7731                 if (!fid_is_sane(fid)) {
7732                         bool is_dotdot = false;
7733
7734                         if (it->oie_dirent->oied_namelen == 2 &&
7735                             it->oie_dirent->oied_name[0] == '.' &&
7736                             it->oie_dirent->oied_name[1] == '.')
7737                                 is_dotdot = true;
7738                         /*
7739                          * If the parent is on remote MDT, and there
7740                          * is no FID-in-dirent, then we have to get
7741                          * the parent FID from the linkEA.
7742                          */
7743                         if (is_remote_parent_ino(dev, ino) && is_dotdot) {
7744                                 rc = osd_get_pfid_from_linkea(env, obj, fid);
7745                         } else {
7746                                 if (is_dotdot == false &&
7747                                     OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
7748                                         RETURN(-ENOENT);
7749
7750                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
7751                         }
7752                 }
7753         }
7754
7755         /* Pack the entry anyway, at least the offset is right. */
7756         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
7757                            it->oie_dirent->oied_name,
7758                            it->oie_dirent->oied_namelen,
7759                            it->oie_dirent->oied_type, attr);
7760
7761         RETURN(rc > 0 ? 0 : rc);
7762 }
7763
7764 /**
7765  * Returns the record size size at current position.
7766  *
7767  * This function will return record(lu_dirent) size in bytes.
7768  *
7769  * \param[in] env       execution environment
7770  * \param[in] di        iterator's in memory structure
7771  * \param[in] attr      attribute of the entry, only requires LUDA_TYPE to
7772  *                      calculate the lu_dirent size.
7773  *
7774  * \retval      record size(in bytes & in memory) of the current lu_dirent
7775  *              entry.
7776  */
7777 static int osd_it_ea_rec_size(const struct lu_env *env, const struct dt_it *di,
7778                               __u32 attr)
7779 {
7780         struct osd_it_ea *it = (struct osd_it_ea *)di;
7781
7782         return lu_dirent_calc_size(it->oie_dirent->oied_namelen, attr);
7783 }
7784
7785 /**
7786  * Returns a cookie for current position of the iterator head, so that
7787  * user can use this cookie to load/start the iterator next time.
7788  *
7789  * \param di iterator's in memory structure
7790  *
7791  * \retval cookie for current position, on success
7792  */
7793 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
7794 {
7795         struct osd_it_ea *it = (struct osd_it_ea *)di;
7796
7797         return it->oie_dirent->oied_off;
7798 }
7799
7800 /**
7801  * It calls osd_ldiskfs_it_fill() which will use ->iterate*()
7802  * to load a directory entry at a time and stored it i inn,
7803  * in iterator's in-memory data structure.
7804  *
7805  * \param di struct osd_it_ea, iterator's in memory structure
7806  *
7807  * \retval +ve on success
7808  * \retval -ve on error
7809  */
7810 static int osd_it_ea_load(const struct lu_env *env,
7811                           const struct dt_it *di, __u64 hash)
7812 {
7813         struct osd_it_ea *it = (struct osd_it_ea *)di;
7814         int rc;
7815
7816         ENTRY;
7817         it->oie_file->f_pos = hash;
7818
7819         rc =  osd_ldiskfs_it_fill(env, di);
7820         if (rc > 0)
7821                 rc = -ENODATA;
7822
7823         if (rc == 0)
7824                 rc = 1;
7825
7826         RETURN(rc);
7827 }
7828
7829 /**
7830  * Index lookup function for interoperability mode (b11826).
7831  *
7832  * \param key,  key i.e. file name to be searched
7833  *
7834  * \retval +ve, on success
7835  * \retval -ve, on error
7836  */
7837 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
7838                                struct dt_rec *rec, const struct dt_key *key)
7839 {
7840         struct osd_object *obj = osd_dt_obj(dt);
7841         int rc = 0;
7842
7843         ENTRY;
7844
7845         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
7846         LINVRNT(osd_invariant(obj));
7847
7848         rc = osd_ea_lookup_rec(env, obj, rec, key);
7849         if (rc == 0)
7850                 rc = 1;
7851         RETURN(rc);
7852 }
7853
7854 /**
7855  * Index and Iterator operations for interoperability
7856  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
7857  */
7858 static const struct dt_index_operations osd_index_ea_ops = {
7859         .dio_lookup         = osd_index_ea_lookup,
7860         .dio_declare_insert = osd_index_declare_ea_insert,
7861         .dio_insert         = osd_index_ea_insert,
7862         .dio_declare_delete = osd_index_declare_ea_delete,
7863         .dio_delete         = osd_index_ea_delete,
7864         .dio_it     = {
7865                 .init     = osd_it_ea_init,
7866                 .fini     = osd_it_ea_fini,
7867                 .get      = osd_it_ea_get,
7868                 .put      = osd_it_ea_put,
7869                 .next     = osd_it_ea_next,
7870                 .key      = osd_it_ea_key,
7871                 .key_size = osd_it_ea_key_size,
7872                 .rec      = osd_it_ea_rec,
7873                 .rec_size = osd_it_ea_rec_size,
7874                 .store    = osd_it_ea_store,
7875                 .load     = osd_it_ea_load
7876         }
7877 };
7878
7879 static void *osd_key_init(const struct lu_context *ctx,
7880                           struct lu_context_key *key)
7881 {
7882         struct osd_thread_info *info;
7883
7884         OBD_ALLOC_PTR(info);
7885         if (info == NULL)
7886                 return ERR_PTR(-ENOMEM);
7887
7888         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7889         if (info->oti_it_ea_buf == NULL)
7890                 goto out_free_info;
7891
7892         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
7893
7894         info->oti_hlock = ldiskfs_htree_lock_alloc();
7895         if (info->oti_hlock == NULL)
7896                 goto out_free_ea;
7897
7898         return info;
7899
7900 out_free_ea:
7901         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7902 out_free_info:
7903         OBD_FREE_PTR(info);
7904         return ERR_PTR(-ENOMEM);
7905 }
7906
7907 static void osd_key_fini(const struct lu_context *ctx,
7908                          struct lu_context_key *key, void *data)
7909 {
7910         struct osd_thread_info *info = data;
7911         struct ldiskfs_inode_info *lli = LDISKFS_I(info->oti_inode);
7912         struct osd_idmap_cache *idc = info->oti_ins_cache;
7913
7914         if (info->oti_dio_pages) {
7915                 int i;
7916                 for (i = 0; i < PTLRPC_MAX_BRW_PAGES; i++) {
7917                         struct page *page = info->oti_dio_pages[i];
7918                         if (page) {
7919                                 LASSERT(PagePrivate2(page));
7920                                 LASSERT(PageLocked(page));
7921                                 ClearPagePrivate2(page);
7922                                 unlock_page(page);
7923                                 __free_page(page);
7924                         }
7925                 }
7926                 OBD_FREE_PTR_ARRAY_LARGE(info->oti_dio_pages,
7927                                          PTLRPC_MAX_BRW_PAGES);
7928         }
7929
7930         if (info->oti_inode != NULL)
7931                 OBD_FREE_PTR(lli);
7932         if (info->oti_hlock != NULL)
7933                 ldiskfs_htree_lock_free(info->oti_hlock);
7934         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7935         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
7936         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
7937         lu_buf_free(&info->oti_iobuf.dr_lnb_buf);
7938         lu_buf_free(&info->oti_big_buf);
7939         if (idc != NULL) {
7940                 LASSERT(info->oti_ins_cache_size > 0);
7941                 OBD_FREE_PTR_ARRAY_LARGE(idc, info->oti_ins_cache_size);
7942                 info->oti_ins_cache = NULL;
7943                 info->oti_ins_cache_size = 0;
7944         }
7945         OBD_FREE_PTR(info);
7946 }
7947
7948 static void osd_key_exit(const struct lu_context *ctx,
7949                          struct lu_context_key *key, void *data)
7950 {
7951         struct osd_thread_info *info = data;
7952
7953         LASSERT(info->oti_r_locks == 0);
7954         LASSERT(info->oti_w_locks == 0);
7955         LASSERT(info->oti_txns    == 0);
7956         LASSERTF(info->oti_dio_pages_used == 0, "%d\n",
7957                  info->oti_dio_pages_used);
7958 }
7959
7960 /* type constructor/destructor: osd_type_init, osd_type_fini */
7961 LU_TYPE_INIT_FINI(osd, &osd_key);
7962
7963 struct lu_context_key osd_key = {
7964         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
7965         .lct_init = osd_key_init,
7966         .lct_fini = osd_key_fini,
7967         .lct_exit = osd_key_exit
7968 };
7969
7970
7971 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
7972                            const char *name, struct lu_device *next)
7973 {
7974         struct osd_device *osd = osd_dev(d);
7975
7976         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname)) >=
7977             sizeof(osd->od_svname))
7978                 return -E2BIG;
7979         return osd_procfs_init(osd, name);
7980 }
7981
7982 static int osd_fid_init(const struct lu_env *env, struct osd_device *osd)
7983 {
7984         struct seq_server_site *ss = osd_seq_site(osd);
7985         int rc = 0;
7986
7987         ENTRY;
7988
7989         if (osd->od_is_ost || osd->od_cl_seq != NULL)
7990                 RETURN(0);
7991
7992         if (unlikely(ss == NULL))
7993                 RETURN(-ENODEV);
7994
7995         OBD_ALLOC_PTR(osd->od_cl_seq);
7996         if (osd->od_cl_seq == NULL)
7997                 RETURN(-ENOMEM);
7998
7999         seq_client_init(osd->od_cl_seq, NULL, LUSTRE_SEQ_METADATA,
8000                         osd->od_svname, ss->ss_server_seq);
8001
8002         if (ss->ss_node_id == 0) {
8003                 /*
8004                  * If the OSD on the sequence controller(MDT0), then allocate
8005                  * sequence here, otherwise allocate sequence after connected
8006                  * to MDT0 (see mdt_register_lwp_callback()).
8007                  */
8008                 rc = seq_server_alloc_meta(osd->od_cl_seq->lcs_srv,
8009                                    &osd->od_cl_seq->lcs_space, env);
8010         }
8011
8012         RETURN(rc);
8013 }
8014
8015 static void osd_fid_fini(const struct lu_env *env, struct osd_device *osd)
8016 {
8017         if (osd->od_cl_seq == NULL)
8018                 return;
8019
8020         seq_client_fini(osd->od_cl_seq);
8021         OBD_FREE_PTR(osd->od_cl_seq);
8022         osd->od_cl_seq = NULL;
8023 }
8024
8025 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
8026 {
8027         ENTRY;
8028
8029         /* shutdown quota slave instance associated with the device */
8030         if (o->od_quota_slave_md != NULL) {
8031                 struct qsd_instance *qsd = o->od_quota_slave_md;
8032
8033                 o->od_quota_slave_md = NULL;
8034                 qsd_fini(env, qsd);
8035         }
8036
8037         if (o->od_quota_slave_dt != NULL) {
8038                 struct qsd_instance *qsd = o->od_quota_slave_dt;
8039
8040                 o->od_quota_slave_dt = NULL;
8041                 qsd_fini(env, qsd);
8042         }
8043
8044         osd_fid_fini(env, o);
8045         osd_scrub_cleanup(env, o);
8046
8047         RETURN(0);
8048 }
8049
8050 static void osd_umount(const struct lu_env *env, struct osd_device *o)
8051 {
8052         ENTRY;
8053
8054         if (o->od_mnt != NULL) {
8055                 shrink_dcache_sb(osd_sb(o));
8056                 osd_sync(env, &o->od_dt_dev);
8057                 wait_event(o->od_commit_cb_done,
8058                           !atomic_read(&o->od_commit_cb_in_flight));
8059
8060                 mntput(o->od_mnt);
8061                 o->od_mnt = NULL;
8062         }
8063
8064         EXIT;
8065 }
8066
8067 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
8068 # ifndef LDISKFS_HAS_INCOMPAT_FEATURE
8069 /* Newer kernels provide the ldiskfs_set_feature_largedir() wrapper already,
8070  * which calls ldiskfs_update_dynamic_rev() to update ancient filesystems.
8071  * All ldiskfs filesystems are already v2, so it is a no-op and unnecessary.
8072  * This avoids maintaining patches to export this otherwise-useless function.
8073  */
8074 void ldiskfs_update_dynamic_rev(struct super_block *sb)
8075 {
8076         /* do nothing */
8077 }
8078 # endif
8079 #endif
8080
8081 static int osd_mount(const struct lu_env *env,
8082                      struct osd_device *o, struct lustre_cfg *cfg)
8083 {
8084         const char *name = lustre_cfg_string(cfg, 0);
8085         const char *dev = lustre_cfg_string(cfg, 1);
8086         const char *opts;
8087         unsigned long page, s_flags = 0, lmd_flags = 0;
8088         struct page *__page;
8089         struct file_system_type *type;
8090         char *options = NULL;
8091         const char *str;
8092         struct osd_thread_info *info = osd_oti_get(env);
8093         struct lu_fid *fid = &info->oti_fid;
8094         struct inode *inode;
8095         int rc = 0, force_over_1024tb = 0;
8096
8097         ENTRY;
8098
8099         if (o->od_mnt != NULL)
8100                 RETURN(0);
8101
8102         if (strlen(dev) >= sizeof(o->od_mntdev))
8103                 RETURN(-E2BIG);
8104         strcpy(o->od_mntdev, dev);
8105
8106         str = lustre_cfg_buf(cfg, 2);
8107         sscanf(str, "%lu:%lu", &s_flags, &lmd_flags);
8108
8109         opts = lustre_cfg_string(cfg, 3);
8110 #ifdef __BIG_ENDIAN
8111         if (opts == NULL || strstr(opts, "bigendian_extents") == NULL) {
8112                 CERROR("%s: device %s extents feature is not guaranteed to "
8113                        "work on big-endian systems. Use \"bigendian_extents\" "
8114                        "mount option to override.\n", name, dev);
8115                 RETURN(-EINVAL);
8116         }
8117 #endif
8118 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
8119         if (opts != NULL && strstr(opts, "force_over_128tb") != NULL) {
8120                 CWARN("force_over_128tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force option. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
8121         }
8122 #endif
8123 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 1, 53, 0)
8124         if (opts != NULL && strstr(opts, "force_over_256tb") != NULL) {
8125                 CWARN("force_over_256tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force options. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
8126         }
8127 #endif
8128 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
8129         if (opts != NULL && strstr(opts, "force_over_512tb") != NULL) {
8130                 CWARN("force_over_512tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force options. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
8131         }
8132 #endif
8133
8134         if (opts != NULL && strstr(opts, "force_over_1024tb") != NULL)
8135                 force_over_1024tb = 1;
8136
8137         __page = alloc_page(GFP_KERNEL);
8138         if (__page == NULL)
8139                 GOTO(out, rc = -ENOMEM);
8140         page = (unsigned long)page_address(__page);
8141         options = (char *)page;
8142         *options = '\0';
8143         if (opts != NULL) {
8144                 /* strip out the options for back compatiblity */
8145                 static const char * const sout[] = {
8146                         "mballoc",
8147                         "iopen",
8148                         "noiopen",
8149                         "iopen_nopriv",
8150                         "extents",
8151                         "noextents",
8152                         /* strip out option we processed in osd */
8153                         "bigendian_extents",
8154                         "force_over_128tb",
8155                         "force_over_256tb",
8156                         "force_over_512tb",
8157                         "force_over_1024tb",
8158                         "resetoi",
8159                         NULL
8160                 };
8161                 strncat(options, opts, PAGE_SIZE);
8162                 for (rc = 0, str = options; sout[rc]; ) {
8163                         char *op = strstr(str, sout[rc]);
8164
8165                         if (op == NULL) {
8166                                 rc++;
8167                                 str = options;
8168                                 continue;
8169                         }
8170                         if (op == options || *(op - 1) == ',') {
8171                                 str = op + strlen(sout[rc]);
8172                                 if (*str == ',' || *str == '\0') {
8173                                         *str == ',' ? str++ : str;
8174                                         memmove(op, str, strlen(str) + 1);
8175                                 }
8176                         }
8177                         for (str = op; *str != ',' && *str != '\0'; str++)
8178                                 ;
8179                 }
8180         } else {
8181                 strncat(options, "user_xattr,acl", PAGE_SIZE);
8182         }
8183
8184         /* Glom up mount options */
8185         if (*options != '\0')
8186                 strncat(options, ",", PAGE_SIZE);
8187         strncat(options, "no_mbcache,nodelalloc", PAGE_SIZE);
8188
8189         type = get_fs_type("ldiskfs");
8190         if (!type) {
8191                 CERROR("%s: cannot find ldiskfs module\n", name);
8192                 GOTO(out, rc = -ENODEV);
8193         }
8194
8195         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
8196         module_put(type->owner);
8197
8198         if (IS_ERR(o->od_mnt)) {
8199                 rc = PTR_ERR(o->od_mnt);
8200                 o->od_mnt = NULL;
8201                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
8202                 GOTO(out, rc);
8203         }
8204
8205         if (ldiskfs_blocks_count(LDISKFS_SB(osd_sb(o))->s_es) <<
8206                                  osd_sb(o)->s_blocksize_bits > 1024ULL << 40 &&
8207                                  force_over_1024tb == 0) {
8208                 CERROR("%s: device %s LDISKFS has not been tested on filesystems larger than 1024TB and may cause data corruption. Use 'force_over_1024tb' mount option to override.\n",
8209                        name, dev);
8210                 GOTO(out_mnt, rc = -EINVAL);
8211         }
8212
8213         if (lmd_flags & LMD_FLG_DEV_RDONLY) {
8214                 LCONSOLE_WARN("%s: not support dev_rdonly on this device\n",
8215                               name);
8216
8217                 GOTO(out_mnt, rc = -EOPNOTSUPP);
8218         }
8219
8220         if (!ldiskfs_has_feature_journal(o->od_mnt->mnt_sb)) {
8221                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
8222                 GOTO(out_mnt, rc = -EINVAL);
8223         }
8224
8225         if (ldiskfs_has_feature_fast_commit(o->od_mnt->mnt_sb)) {
8226                 CERROR("%s: device %s is mounted with fast_commit that breaks recovery\n",
8227                        name, dev);
8228                 GOTO(out_mnt, rc = -EOPNOTSUPP);
8229         }
8230
8231 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
8232 #ifdef LDISKFS_MOUNT_DIRDATA
8233         if (ldiskfs_has_feature_dirdata(o->od_mnt->mnt_sb))
8234                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
8235         else if (strstr(name, "MDT")) /* don't complain for MGT or OSTs */
8236                 CWARN("%s: device %s was upgraded from Lustre-1.x without "
8237                       "enabling the dirdata feature. If you do not want to "
8238                       "downgrade to Lustre-1.x again, you can enable it via "
8239                       "'tune2fs -O dirdata device'\n", name, dev);
8240 #endif
8241         /* enable large_dir on MDTs to avoid REMOTE_PARENT_DIR overflow,
8242          * and on very large OSTs to avoid object directory overflow */
8243         if (unlikely(!ldiskfs_has_feature_largedir(o->od_mnt->mnt_sb) &&
8244                      !strstr(name, "MGS"))) {
8245                 ldiskfs_set_feature_largedir(o->od_mnt->mnt_sb);
8246                 LCONSOLE_INFO("%s: enabled 'large_dir' feature on device %s\n",
8247                               name, dev);
8248         }
8249 #endif
8250         inode = osd_sb(o)->s_root->d_inode;
8251         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
8252         if (!o->od_dt_dev.dd_rdonly) {
8253                 rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
8254                 if (rc != 0) {
8255                         CERROR("%s: failed to set lma on %s root inode\n",
8256                                name, dev);
8257                         GOTO(out_mnt, rc);
8258                 }
8259         }
8260
8261         if (lmd_flags & LMD_FLG_NOSCRUB)
8262                 o->od_scrub.os_scrub.os_auto_scrub_interval = AS_NEVER;
8263
8264         if (blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev))) {
8265                 /* do not use pagecache with flash-backed storage */
8266                 o->od_writethrough_cache = 0;
8267                 o->od_read_cache = 0;
8268         }
8269
8270         GOTO(out, rc = 0);
8271
8272 out_mnt:
8273         mntput(o->od_mnt);
8274         o->od_mnt = NULL;
8275
8276 out:
8277         if (__page)
8278                 __free_page(__page);
8279
8280         return rc;
8281 }
8282
8283 static struct lu_device *osd_device_fini(const struct lu_env *env,
8284                                          struct lu_device *d)
8285 {
8286         struct osd_device *o = osd_dev(d);
8287
8288         ENTRY;
8289
8290         osd_index_backup(env, o, false);
8291         osd_shutdown(env, o);
8292         osd_procfs_fini(o);
8293         if (o->od_oi_table != NULL)
8294                 osd_oi_fini(osd_oti_get(env), o);
8295         if (o->od_extent_bytes_percpu)
8296                 free_percpu(o->od_extent_bytes_percpu);
8297         osd_obj_map_fini(o);
8298         osd_umount(env, o);
8299
8300         RETURN(NULL);
8301 }
8302
8303 static int osd_device_init0(const struct lu_env *env,
8304                             struct osd_device *o,
8305                             struct lustre_cfg *cfg)
8306 {
8307         struct lu_device *l = osd2lu_dev(o);
8308         struct osd_thread_info *info;
8309         int cplen = 0;
8310         char *opts = NULL;
8311         bool restored = false;
8312         int rc;
8313
8314         /* if the module was re-loaded, env can loose its keys */
8315         rc = lu_env_refill((struct lu_env *)env);
8316         if (rc)
8317                 GOTO(out, rc);
8318         info = osd_oti_get(env);
8319         LASSERT(info);
8320
8321         l->ld_ops = &osd_lu_ops;
8322         o->od_dt_dev.dd_ops = &osd_dt_ops;
8323
8324         spin_lock_init(&o->od_osfs_lock);
8325         mutex_init(&o->od_otable_mutex);
8326         INIT_LIST_HEAD(&o->od_orphan_list);
8327         INIT_LIST_HEAD(&o->od_index_backup_list);
8328         INIT_LIST_HEAD(&o->od_index_restore_list);
8329         spin_lock_init(&o->od_lock);
8330         o->od_index_backup_policy = LIBP_NONE;
8331         o->od_t10_type = 0;
8332         init_waitqueue_head(&o->od_commit_cb_done);
8333
8334         o->od_read_cache = 1;
8335         o->od_writethrough_cache = 1;
8336         o->od_enable_projid_xattr = 0;
8337         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
8338         o->od_readcache_max_iosize = OSD_READCACHE_MAX_IO_MB << 20;
8339         o->od_writethrough_max_iosize = OSD_WRITECACHE_MAX_IO_MB << 20;
8340         o->od_scrub.os_scrub.os_auto_scrub_interval = AS_DEFAULT;
8341         /* default fallocate to unwritten extents: LU-14326/LU-14333 */
8342         o->od_fallocate_zero_blocks = 0;
8343
8344         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
8345                         sizeof(o->od_svname));
8346         if (cplen >= sizeof(o->od_svname)) {
8347                 rc = -E2BIG;
8348                 GOTO(out, rc);
8349         }
8350
8351         o->od_index_backup_stop = 0;
8352         o->od_index = -1; /* -1 means index is invalid */
8353         rc = server_name2index(o->od_svname, &o->od_index, NULL);
8354         if (rc == LDD_F_SV_TYPE_OST)
8355                 o->od_is_ost = 1;
8356
8357         o->od_full_scrub_ratio = OFSR_DEFAULT;
8358         o->od_full_scrub_threshold_rate = FULL_SCRUB_THRESHOLD_RATE_DEFAULT;
8359         rc = osd_mount(env, o, cfg);
8360         if (rc != 0)
8361                 GOTO(out, rc);
8362
8363         /* Can only check block device after mount */
8364         o->od_nonrotational =
8365                 blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev));
8366
8367         rc = osd_obj_map_init(env, o);
8368         if (rc != 0)
8369                 GOTO(out_mnt, rc);
8370
8371         rc = lu_site_init(&o->od_site, l);
8372         if (rc != 0)
8373                 GOTO(out_compat, rc);
8374         o->od_site.ls_bottom_dev = l;
8375
8376         rc = lu_site_init_finish(&o->od_site);
8377         if (rc != 0)
8378                 GOTO(out_site, rc);
8379
8380         opts = lustre_cfg_string(cfg, 3);
8381         if (opts && strstr(opts, "resetoi"))
8382                 restored = true;
8383
8384         INIT_LIST_HEAD(&o->od_ios_list);
8385
8386         rc = lprocfs_init_brw_stats(&o->od_brw_stats);
8387         if (rc)
8388                 GOTO(out_brw_stats, rc);
8389
8390         /* setup scrub, including OI files initialization */
8391         o->od_in_init = 1;
8392         rc = osd_scrub_setup(env, o, restored);
8393         o->od_in_init = 0;
8394         if (rc < 0)
8395                 GOTO(out_brw_stats, rc);
8396
8397         rc = osd_procfs_init(o, o->od_svname);
8398         if (rc != 0) {
8399                 CERROR("%s: can't initialize procfs: rc = %d\n",
8400                        o->od_svname, rc);
8401                 GOTO(out_scrub, rc);
8402         }
8403
8404         LASSERT(l->ld_site->ls_linkage.next != NULL);
8405         LASSERT(l->ld_site->ls_linkage.prev != NULL);
8406
8407         /* initialize quota slave instance */
8408         /* currently it's no need to prepare qsd_instance_md for OST */
8409         if (!o->od_is_ost) {
8410                 o->od_quota_slave_md = qsd_init(env, o->od_svname,
8411                                                 &o->od_dt_dev, o->od_proc_entry,
8412                                                 true, true);
8413                 if (IS_ERR(o->od_quota_slave_md)) {
8414                         rc = PTR_ERR(o->od_quota_slave_md);
8415                         o->od_quota_slave_md = NULL;
8416                         GOTO(out_procfs, rc);
8417                 }
8418         }
8419
8420         o->od_quota_slave_dt = qsd_init(env, o->od_svname, &o->od_dt_dev,
8421                                         o->od_proc_entry, false, true);
8422
8423         if (IS_ERR(o->od_quota_slave_dt)) {
8424                 if (o->od_quota_slave_md != NULL) {
8425                         qsd_fini(env, o->od_quota_slave_md);
8426                         o->od_quota_slave_md = NULL;
8427                 }
8428
8429                 rc = PTR_ERR(o->od_quota_slave_dt);
8430                 o->od_quota_slave_dt = NULL;
8431                 GOTO(out_procfs, rc);
8432         }
8433
8434         o->od_extent_bytes_percpu = alloc_percpu(unsigned int);
8435         if (!o->od_extent_bytes_percpu) {
8436                 rc = -ENOMEM;
8437                 GOTO(out_procfs, rc);
8438         }
8439
8440         RETURN(0);
8441
8442 out_procfs:
8443         osd_procfs_fini(o);
8444 out_scrub:
8445         osd_scrub_cleanup(env, o);
8446 out_brw_stats:
8447         lprocfs_fini_brw_stats(&o->od_brw_stats);
8448 out_site:
8449         lu_site_fini(&o->od_site);
8450 out_compat:
8451         osd_obj_map_fini(o);
8452 out_mnt:
8453         osd_umount(env, o);
8454 out:
8455         return rc;
8456 }
8457
8458 static struct lu_device *osd_device_alloc(const struct lu_env *env,
8459                                           struct lu_device_type *t,
8460                                           struct lustre_cfg *cfg)
8461 {
8462         struct osd_device *o;
8463         int rc;
8464
8465         OBD_ALLOC_PTR(o);
8466         if (o == NULL)
8467                 return ERR_PTR(-ENOMEM);
8468
8469         rc = dt_device_init(&o->od_dt_dev, t);
8470         if (rc == 0) {
8471                 /*
8472                  * Because the ctx might be revived in dt_device_init,
8473                  * refill the env here
8474                  */
8475                 lu_env_refill((struct lu_env *)env);
8476                 rc = osd_device_init0(env, o, cfg);
8477                 if (rc)
8478                         dt_device_fini(&o->od_dt_dev);
8479         }
8480
8481         if (unlikely(rc != 0))
8482                 OBD_FREE_PTR(o);
8483
8484         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
8485 }
8486
8487 static struct lu_device *osd_device_free(const struct lu_env *env,
8488                                          struct lu_device *d)
8489 {
8490         struct osd_device *o = osd_dev(d);
8491
8492         ENTRY;
8493
8494         /* XXX: make osd top device in order to release reference */
8495         d->ld_site->ls_top_dev = d;
8496         lu_site_purge(env, d->ld_site, -1);
8497         lu_site_print(env, d->ld_site, &d->ld_site->ls_obj_hash.nelems,
8498                       D_ERROR, lu_cdebug_printer);
8499         lu_site_fini(&o->od_site);
8500         dt_device_fini(&o->od_dt_dev);
8501         OBD_FREE_PTR(o);
8502         RETURN(NULL);
8503 }
8504
8505 static int osd_process_config(const struct lu_env *env,
8506                               struct lu_device *d, struct lustre_cfg *cfg)
8507 {
8508         struct osd_device *o = osd_dev(d);
8509         ssize_t count;
8510         int rc;
8511
8512         ENTRY;
8513
8514         switch (cfg->lcfg_command) {
8515         case LCFG_SETUP:
8516                 rc = osd_mount(env, o, cfg);
8517                 break;
8518         case LCFG_CLEANUP:
8519                 /*
8520                  * For the case LCFG_PRE_CLEANUP is not called in advance,
8521                  * that may happend if hit failure during mount process.
8522                  */
8523                 osd_index_backup(env, o, false);
8524                 lu_dev_del_linkage(d->ld_site, d);
8525                 rc = osd_shutdown(env, o);
8526                 break;
8527         case LCFG_PARAM:
8528                 LASSERT(&o->od_dt_dev);
8529                 count  = class_modify_config(cfg, PARAM_OSD,
8530                                              &o->od_dt_dev.dd_kobj);
8531                 if (count < 0)
8532                         count = class_modify_config(cfg, PARAM_OST,
8533                                                     &o->od_dt_dev.dd_kobj);
8534                 rc = count > 0 ? 0 : count;
8535                 break;
8536         case LCFG_PRE_CLEANUP:
8537                 osd_scrub_stop(o);
8538                 osd_index_backup(env, o,
8539                                  o->od_index_backup_policy != LIBP_NONE);
8540                 rc = 0;
8541                 break;
8542         default:
8543                 rc = -ENOSYS;
8544         }
8545
8546         RETURN(rc);
8547 }
8548
8549 static int osd_recovery_complete(const struct lu_env *env,
8550                                  struct lu_device *d)
8551 {
8552         struct osd_device *osd = osd_dev(d);
8553         int rc = 0;
8554
8555         ENTRY;
8556
8557         if (osd->od_quota_slave_md == NULL && osd->od_quota_slave_dt == NULL)
8558                 RETURN(0);
8559
8560         /*
8561          * start qsd instance on recovery completion, this notifies the quota
8562          * slave code that we are about to process new requests now
8563          */
8564         rc = qsd_start(env, osd->od_quota_slave_dt);
8565         if (rc == 0 && osd->od_quota_slave_md != NULL)
8566                 rc = qsd_start(env, osd->od_quota_slave_md);
8567
8568         RETURN(rc);
8569 }
8570
8571 /*
8572  * we use exports to track all osd users
8573  */
8574 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
8575                            struct obd_device *obd, struct obd_uuid *cluuid,
8576                            struct obd_connect_data *data, void *localdata)
8577 {
8578         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8579         struct lustre_handle conn;
8580         int rc;
8581
8582         ENTRY;
8583
8584         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
8585
8586         rc = class_connect(&conn, obd, cluuid);
8587         if (rc)
8588                 RETURN(rc);
8589
8590         *exp = class_conn2export(&conn);
8591
8592         spin_lock(&osd->od_osfs_lock);
8593         osd->od_connects++;
8594         spin_unlock(&osd->od_osfs_lock);
8595
8596         RETURN(0);
8597 }
8598
8599 /*
8600  * once last export (we don't count self-export) disappeared
8601  * osd can be released
8602  */
8603 static int osd_obd_disconnect(struct obd_export *exp)
8604 {
8605         struct obd_device *obd = exp->exp_obd;
8606         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8607         int rc, release = 0;
8608
8609         ENTRY;
8610
8611         /* Only disconnect the underlying layers on the final disconnect. */
8612         spin_lock(&osd->od_osfs_lock);
8613         osd->od_connects--;
8614         if (osd->od_connects == 0)
8615                 release = 1;
8616         spin_unlock(&osd->od_osfs_lock);
8617
8618         rc = class_disconnect(exp); /* bz 9811 */
8619
8620         if (rc == 0 && release)
8621                 class_manual_cleanup(obd);
8622         RETURN(rc);
8623 }
8624
8625 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
8626                        struct lu_device *dev)
8627 {
8628         struct osd_device *osd = osd_dev(dev);
8629         struct lr_server_data *lsd =
8630                         &osd->od_dt_dev.dd_lu_dev.ld_site->ls_tgt->lut_lsd;
8631         int result = 0;
8632
8633         ENTRY;
8634
8635         if (osd->od_quota_slave_md != NULL) {
8636                 /* set up quota slave objects for inode */
8637                 result = qsd_prepare(env, osd->od_quota_slave_md);
8638                 if (result != 0)
8639                         RETURN(result);
8640         }
8641
8642         if (osd->od_quota_slave_dt != NULL) {
8643                 /* set up quota slave objects for block */
8644                 result = qsd_prepare(env, osd->od_quota_slave_dt);
8645                 if (result != 0)
8646                         RETURN(result);
8647         }
8648
8649
8650         if (lsd->lsd_feature_incompat & OBD_COMPAT_OST) {
8651 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 52, 0)
8652                 if (lsd->lsd_feature_rocompat & OBD_ROCOMPAT_IDX_IN_IDIF) {
8653                         osd->od_index_in_idif = 1;
8654                 } else {
8655                         osd->od_index_in_idif = 0;
8656                         result = osd_register_proc_index_in_idif(osd);
8657                         if (result != 0)
8658                                 RETURN(result);
8659                 }
8660 #else
8661                 osd->od_index_in_idif = 1;
8662 #endif
8663         }
8664
8665         result = osd_fid_init(env, osd);
8666
8667         RETURN(result);
8668 }
8669
8670 /**
8671  * Implementation of lu_device_operations::ldo_fid_alloc() for OSD
8672  *
8673  * Allocate FID.
8674  *
8675  * see include/lu_object.h for the details.
8676  */
8677 static int osd_fid_alloc(const struct lu_env *env, struct lu_device *d,
8678                          struct lu_fid *fid, struct lu_object *parent,
8679                          const struct lu_name *name)
8680 {
8681         struct osd_device *osd = osd_dev(d);
8682
8683         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
8684 }
8685
8686 static const struct lu_object_operations osd_lu_obj_ops = {
8687         .loo_object_init      = osd_object_init,
8688         .loo_object_delete    = osd_object_delete,
8689         .loo_object_release   = osd_object_release,
8690         .loo_object_free      = osd_object_free,
8691         .loo_object_print     = osd_object_print,
8692         .loo_object_invariant = osd_object_invariant
8693 };
8694
8695 const struct lu_device_operations osd_lu_ops = {
8696         .ldo_object_alloc      = osd_object_alloc,
8697         .ldo_process_config    = osd_process_config,
8698         .ldo_recovery_complete = osd_recovery_complete,
8699         .ldo_prepare           = osd_prepare,
8700         .ldo_fid_alloc         = osd_fid_alloc,
8701 };
8702
8703 static const struct lu_device_type_operations osd_device_type_ops = {
8704         .ldto_init = osd_type_init,
8705         .ldto_fini = osd_type_fini,
8706
8707         .ldto_start = osd_type_start,
8708         .ldto_stop  = osd_type_stop,
8709
8710         .ldto_device_alloc = osd_device_alloc,
8711         .ldto_device_free  = osd_device_free,
8712
8713         .ldto_device_init = osd_device_init,
8714         .ldto_device_fini = osd_device_fini
8715 };
8716
8717 static struct lu_device_type osd_device_type = {
8718         .ldt_tags     = LU_DEVICE_DT,
8719         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
8720         .ldt_ops      = &osd_device_type_ops,
8721         .ldt_ctx_tags = LCT_LOCAL,
8722 };
8723
8724 static int osd_health_check(const struct lu_env *env, struct obd_device *obd)
8725 {
8726         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8727         struct super_block *sb = osd_sb(osd);
8728
8729         return (osd->od_mnt == NULL || sb->s_flags & SB_RDONLY);
8730 }
8731
8732 /*
8733  * lprocfs legacy support.
8734  */
8735 static const struct obd_ops osd_obd_device_ops = {
8736         .o_owner = THIS_MODULE,
8737         .o_connect      = osd_obd_connect,
8738         .o_disconnect   = osd_obd_disconnect,
8739         .o_health_check = osd_health_check,
8740 };
8741
8742 static ssize_t track_declares_assert_show(struct kobject *kobj,
8743                                    struct attribute *attr,
8744                                    char *buf)
8745 {
8746         return sprintf(buf, "%d\n", ldiskfs_track_declares_assert);
8747 }
8748
8749 static ssize_t track_declares_assert_store(struct kobject *kobj,
8750                                            struct attribute *attr,
8751                                            const char *buffer, size_t count)
8752 {
8753         bool track_declares_assert;
8754         int rc;
8755
8756         rc = kstrtobool(buffer, &track_declares_assert);
8757         if (rc)
8758                 return rc;
8759
8760         ldiskfs_track_declares_assert = track_declares_assert;
8761
8762         return count;
8763 }
8764 LUSTRE_RW_ATTR(track_declares_assert);
8765
8766 static int __init osd_init(void)
8767 {
8768         struct kobject *kobj;
8769         int rc;
8770
8771         BUILD_BUG_ON(BH_DXLock >=
8772                      sizeof(((struct buffer_head *)0)->b_state) * 8);
8773 #if !defined(CONFIG_DEBUG_MUTEXES) && !defined(CONFIG_DEBUG_SPINLOCK)
8774         /* please, try to keep osd_thread_info smaller than a page */
8775         BUILD_BUG_ON(sizeof(struct osd_thread_info) > PAGE_SIZE);
8776 #endif
8777
8778         osd_oi_mod_init();
8779
8780         rc = lu_kmem_init(ldiskfs_caches);
8781         if (rc)
8782                 return rc;
8783
8784         rc = class_register_type(&osd_obd_device_ops, NULL, true,
8785                                  LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
8786         if (rc) {
8787                 lu_kmem_fini(ldiskfs_caches);
8788                 return rc;
8789         }
8790
8791         kobj = kset_find_obj(lustre_kset, LUSTRE_OSD_LDISKFS_NAME);
8792         if (kobj) {
8793                 rc = sysfs_create_file(kobj,
8794                                        &lustre_attr_track_declares_assert.attr);
8795                 kobject_put(kobj);
8796                 if (rc) {
8797                         CWARN("osd-ldiskfs: track_declares_assert failed to register with sysfs\n");
8798                         rc = 0;
8799                 }
8800         }
8801
8802         return rc;
8803 }
8804
8805 static void __exit osd_exit(void)
8806 {
8807         struct kobject *kobj;
8808
8809         kobj = kset_find_obj(lustre_kset, LUSTRE_OSD_LDISKFS_NAME);
8810         if (kobj) {
8811                 sysfs_remove_file(kobj,
8812                                   &lustre_attr_track_declares_assert.attr);
8813                 kobject_put(kobj);
8814         }
8815         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
8816         lu_kmem_fini(ldiskfs_caches);
8817 }
8818
8819 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
8820 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
8821 MODULE_VERSION(LUSTRE_VERSION_STRING);
8822 MODULE_LICENSE("GPL");
8823
8824 module_init(osd_init);
8825 module_exit(osd_exit);