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