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