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