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