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