Whamcloud - gitweb
LU-1346 libcfs: replace cfs_ memory wrappers
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osd/osd_handler.c
37  *
38  * Top-level entry points into osd module
39  *
40  * Author: Nikita Danilov <nikita@clusterfs.com>
41  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
42  */
43
44 #define DEBUG_SUBSYSTEM S_MDS
45
46 #include <linux/module.h>
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 /*
58  * struct OBD_{ALLOC,FREE}*()
59  * OBD_FAIL_CHECK
60  */
61 #include <obd_support.h>
62 /* struct ptlrpc_thread */
63 #include <lustre_net.h>
64 #include <lustre_fid.h>
65
66 #include "osd_internal.h"
67
68 /* llo_* api support */
69 #include <md_object.h>
70 #include <lustre_quota.h>
71
72 int ldiskfs_pdo = 1;
73 CFS_MODULE_PARM(ldiskfs_pdo, "i", int, 0644,
74                 "ldiskfs with parallel directory operations");
75
76 int ldiskfs_track_declares_assert;
77 CFS_MODULE_PARM(ldiskfs_track_declares_assert, "i", int, 0644,
78                 "LBUG during tracking of declares");
79
80 static const char dot[] = ".";
81 static const char dotdot[] = "..";
82 static const char remote_obj_dir[] = "REM_OBJ_DIR";
83
84 static const struct lu_object_operations      osd_lu_obj_ops;
85 static const struct dt_object_operations      osd_obj_ops;
86 static const struct dt_object_operations      osd_obj_ea_ops;
87 static const struct dt_object_operations      osd_obj_otable_it_ops;
88 static const struct dt_index_operations       osd_index_iam_ops;
89 static const struct dt_index_operations       osd_index_ea_ops;
90
91 int osd_trans_declare_op2rb[] = {
92         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
93         [OSD_OT_PUNCH]          = OSD_OT_MAX,
94         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
95         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
96         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
97         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
98         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
99         [OSD_OT_WRITE]          = OSD_OT_WRITE,
100         [OSD_OT_INSERT]         = OSD_OT_DELETE,
101         [OSD_OT_DELETE]         = OSD_OT_INSERT,
102         [OSD_OT_QUOTA]          = OSD_OT_MAX,
103 };
104
105 static int osd_has_index(const struct osd_object *obj)
106 {
107         return obj->oo_dt.do_index_ops != NULL;
108 }
109
110 static int osd_object_invariant(const struct lu_object *l)
111 {
112         return osd_invariant(osd_obj(l));
113 }
114
115 /*
116  * Concurrency: doesn't matter
117  */
118 static int osd_read_locked(const struct lu_env *env, struct osd_object *o)
119 {
120         return osd_oti_get(env)->oti_r_locks > 0;
121 }
122
123 /*
124  * Concurrency: doesn't matter
125  */
126 static int osd_write_locked(const struct lu_env *env, struct osd_object *o)
127 {
128         struct osd_thread_info *oti = osd_oti_get(env);
129         return oti->oti_w_locks > 0 && o->oo_owner == env;
130 }
131
132 /*
133  * Concurrency: doesn't access mutable data
134  */
135 static int osd_root_get(const struct lu_env *env,
136                         struct dt_device *dev, struct lu_fid *f)
137 {
138         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
139         return 0;
140 }
141
142 /*
143  * OSD object methods.
144  */
145
146 /*
147  * Concurrency: no concurrent access is possible that early in object
148  * life-cycle.
149  */
150 static struct lu_object *osd_object_alloc(const struct lu_env *env,
151                                           const struct lu_object_header *hdr,
152                                           struct lu_device *d)
153 {
154         struct osd_object *mo;
155
156         OBD_ALLOC_PTR(mo);
157         if (mo != NULL) {
158                 struct lu_object *l;
159
160                 l = &mo->oo_dt.do_lu;
161                 dt_object_init(&mo->oo_dt, NULL, d);
162                 mo->oo_dt.do_ops = &osd_obj_ea_ops;
163                 l->lo_ops = &osd_lu_obj_ops;
164                 init_rwsem(&mo->oo_sem);
165                 init_rwsem(&mo->oo_ext_idx_sem);
166                 spin_lock_init(&mo->oo_guard);
167                 return l;
168         } else {
169                 return NULL;
170         }
171 }
172
173 static inline int __osd_xattr_get(struct inode *inode, struct dentry *dentry,
174                                   const char *name, void *buf, int len)
175 {
176         dentry->d_inode = inode;
177         dentry->d_sb = inode->i_sb;
178         return inode->i_op->getxattr(dentry, name, buf, len);
179 }
180
181 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
182                 struct dentry *dentry, struct lustre_mdt_attrs *lma)
183 {
184         int rc;
185
186         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
187         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
188                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
189         if (rc > 0) {
190                 if ((void *)lma != (void *)info->oti_mdt_attrs_old)
191                         memcpy(lma, info->oti_mdt_attrs_old, sizeof(*lma));
192                 rc = 0;
193                 lustre_lma_swab(lma);
194                 /* Check LMA compatibility */
195                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
196                         CWARN("%.16s: unsupported incompat LMA feature(s) %#x "
197                               "for fid = "DFID", ino = %lu\n",
198                               LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
199                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
200                               PFID(&lma->lma_self_fid), inode->i_ino);
201                         rc = -EOPNOTSUPP;
202                 }
203         } else if (rc == 0) {
204                 rc = -ENODATA;
205         }
206
207         return rc;
208 }
209
210 /*
211  * retrieve object from backend ext fs.
212  **/
213 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
214                        struct osd_inode_id *id)
215 {
216         struct inode *inode = NULL;
217
218         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
219         if (IS_ERR(inode)) {
220                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
221                        id->oii_ino, PTR_ERR(inode));
222         } else if (id->oii_gen != OSD_OII_NOGEN &&
223                    inode->i_generation != id->oii_gen) {
224                 CDEBUG(D_INODE, "unmatched inode: ino = %u, gen0 = %u, "
225                        "gen1 = %u\n",
226                        id->oii_ino, id->oii_gen, inode->i_generation);
227                 iput(inode);
228                 inode = ERR_PTR(-ESTALE);
229         } else if (inode->i_nlink == 0) {
230                 /* due to parallel readdir and unlink,
231                 * we can have dead inode here. */
232                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
233                 make_bad_inode(inode);
234                 iput(inode);
235                 inode = ERR_PTR(-ESTALE);
236         } else if (is_bad_inode(inode)) {
237                 CWARN("%.16s: bad inode: ino = %u\n",
238                 LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, id->oii_ino);
239                 iput(inode);
240                 inode = ERR_PTR(-ENOENT);
241         } else {
242                 if (id->oii_gen == OSD_OII_NOGEN)
243                         osd_id_gen(id, inode->i_ino, inode->i_generation);
244
245                 /* Do not update file c/mtime in ldiskfs.
246                  * NB: we don't have any lock to protect this because we don't
247                  * have reference on osd_object now, but contention with
248                  * another lookup + attr_set can't happen in the tiny window
249                  * between if (...) and set S_NOCMTIME. */
250                 if (!(inode->i_flags & S_NOCMTIME))
251                         inode->i_flags |= S_NOCMTIME;
252         }
253         return inode;
254 }
255
256 static struct inode *
257 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
258              struct osd_inode_id *id, struct lu_fid *fid)
259 {
260         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
261         struct inode            *inode;
262         int                      rc;
263
264         inode = osd_iget(info, dev, id);
265         if (IS_ERR(inode))
266                 return inode;
267
268         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
269         if (rc == 0) {
270                 *fid = lma->lma_self_fid;
271         } else if (rc == -ENODATA) {
272                 if (unlikely(inode == osd_sb(dev)->s_root->d_inode))
273                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
274                 else
275                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
276         } else {
277                 iput(inode);
278                 inode = ERR_PTR(rc);
279         }
280         return inode;
281 }
282
283 static struct inode *
284 osd_iget_verify(struct osd_thread_info *info, struct osd_device *dev,
285                 struct osd_inode_id *id, const struct lu_fid *fid)
286 {
287         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
288         struct inode            *inode;
289         int                      rc;
290
291         inode = osd_iget(info, dev, id);
292         if (IS_ERR(inode))
293                 return inode;
294
295         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
296         if (rc == -ENODATA)
297                 return inode;
298
299         if (rc != 0) {
300                 iput(inode);
301                 return ERR_PTR(rc);
302         }
303
304         if (!lu_fid_eq(fid, &lma->lma_self_fid)) {
305                 CDEBUG(D_LFSCK, "inconsistent obj: "DFID", %lu, "DFID"\n",
306                        PFID(&lma->lma_self_fid), inode->i_ino, PFID(fid));
307                 iput(inode);
308                 return ERR_PTR(-EREMCHG);
309         }
310
311         return inode;
312 }
313
314 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
315                           const struct lu_fid *fid,
316                           const struct lu_object_conf *conf)
317 {
318         struct osd_thread_info *info;
319         struct lu_device       *ldev   = obj->oo_dt.do_lu.lo_dev;
320         struct osd_device      *dev;
321         struct osd_idmap_cache *oic;
322         struct osd_inode_id    *id;
323         struct inode           *inode;
324         struct osd_scrub       *scrub;
325         struct scrub_file      *sf;
326         int                     result;
327         int                     saved  = 0;
328         bool                    verify = false;
329         bool                    in_oi  = false;
330         bool                    triggered = false;
331         ENTRY;
332
333         LINVRNT(osd_invariant(obj));
334         LASSERT(obj->oo_inode == NULL);
335         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID, PFID(fid));
336
337         dev = osd_dev(ldev);
338         scrub = &dev->od_scrub;
339         sf = &scrub->os_file;
340         info = osd_oti_get(env);
341         LASSERT(info);
342         oic = &info->oti_cache;
343
344         if (OBD_FAIL_CHECK(OBD_FAIL_OST_ENOENT))
345                 RETURN(-ENOENT);
346
347         /* Search order: 1. per-thread cache. */
348         if (lu_fid_eq(fid, &oic->oic_fid)) {
349                 id = &oic->oic_lid;
350                 goto iget;
351         }
352
353         id = &info->oti_id;
354         if (!cfs_list_empty(&scrub->os_inconsistent_items)) {
355                 /* Search order: 2. OI scrub pending list. */
356                 result = osd_oii_lookup(dev, fid, id);
357                 if (result == 0)
358                         goto iget;
359         }
360
361         if (sf->sf_flags & SF_INCONSISTENT)
362                 verify = true;
363
364         /*
365          * Objects are created as locking anchors or place holders for objects
366          * yet to be created. No need to osd_oi_lookup() at here because FID
367          * shouldn't never be re-used, if it's really a duplicate FID from
368          * unexpected reason, we should be able to detect it later by calling
369          * do_create->osd_oi_insert()
370          */
371         if (conf != NULL && conf->loc_flags & LOC_F_NEW)
372                 GOTO(out, result = 0);
373
374         /* Search order: 3. OI files. */
375         result = osd_oi_lookup(info, dev, fid, id, true);
376         if (result == -ENOENT) {
377                 if (!fid_is_norm(fid) || fid_is_on_ost(info, dev, fid) ||
378                     !ldiskfs_test_bit(osd_oi_fid2idx(dev,fid),
379                                       sf->sf_oi_bitmap))
380                         GOTO(out, result = 0);
381
382                 goto trigger;
383         }
384
385         if (result != 0)
386                 GOTO(out, result);
387
388         in_oi = true;
389
390 iget:
391         if (!verify)
392                 inode = osd_iget(info, dev, id);
393         else
394                 inode = osd_iget_verify(info, dev, id, fid);
395         if (IS_ERR(inode)) {
396                 result = PTR_ERR(inode);
397                 if (result == -ENOENT || result == -ESTALE) {
398                         if (!in_oi) {
399                                 fid_zero(&oic->oic_fid);
400                                 GOTO(out, result = 0);
401                         }
402
403                         /* XXX: There are three possible cases:
404                          *      1. Backup/restore caused the OI invalid.
405                          *      2. Someone unlinked the object but NOT removed
406                          *         the OI mapping, such as mount target device
407                          *         as ldiskfs, and modify something directly.
408                          *      3. Someone just removed the object between the
409                          *         former oi_lookup and the iget. It is normal.
410                          *
411                          *      It is diffcult to distinguish the 2nd from the
412                          *      1st case. Relatively speaking, the 1st case is
413                          *      common than the 2nd case, trigger OI scrub. */
414                         result = osd_oi_lookup(info, dev, fid, id, true);
415                         if (result == 0)
416                                 /* It is the case 1 or 2. */
417                                 goto trigger;
418
419                         if (result == -ENOENT)
420                                 /* It is the case 3. */
421                                 result = 0;
422                 } else if (result == -EREMCHG) {
423
424 trigger:
425                         if (unlikely(triggered))
426                                 GOTO(out, result = saved);
427
428                         triggered = true;
429                         if (thread_is_running(&scrub->os_thread)) {
430                                 result = -EINPROGRESS;
431                         } else if (!dev->od_noscrub) {
432                                 result = osd_scrub_start(dev);
433                                 LCONSOLE_ERROR("%.16s: trigger OI scrub by RPC "
434                                                "for "DFID", rc = %d [1]\n",
435                                                LDISKFS_SB(osd_sb(dev))->s_es->\
436                                                s_volume_name,PFID(fid), result);
437                                 if (result == 0 || result == -EALREADY)
438                                         result = -EINPROGRESS;
439                                 else
440                                         result = -EREMCHG;
441                         }
442
443                         /* We still have chance to get the valid inode: for the
444                          * object which is referenced by remote name entry, the
445                          * object on the local MDT will be linked under the dir
446                          * of "/REMOTE_PARENT_DIR" with its FID string as name.
447                          *
448                          * We do not know whether the object for the given FID
449                          * is referenced by some remote name entry or not, and
450                          * especially for DNE II, a multiple-linked object may
451                          * have many name entries reside on many MDTs.
452                          *
453                          * To simplify the operation, OSD will not distinguish
454                          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
455                          * only happened for the RPC from other MDT during the
456                          * OI scrub, or for the client side RPC with FID only,
457                          * such as FID to path, or from old connected client. */
458                         saved = result;
459                         result = osd_lookup_in_remote_parent(info, dev,
460                                                              fid, id);
461                         if (result == 0) {
462                                 in_oi = false;
463                                 verify = false;
464                                 goto iget;
465                         }
466
467                         result = saved;
468                 }
469
470                 GOTO(out, result);
471         }
472
473         obj->oo_inode = inode;
474         LASSERT(obj->oo_inode->i_sb == osd_sb(dev));
475
476         obj->oo_compat_dot_created = 1;
477         obj->oo_compat_dotdot_created = 1;
478
479         if (!S_ISDIR(inode->i_mode) || !ldiskfs_pdo) /* done */
480                 GOTO(out, result = 0);
481
482         LASSERT(obj->oo_hl_head == NULL);
483         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
484         if (obj->oo_hl_head == NULL) {
485                 obj->oo_inode = NULL;
486                 iput(inode);
487                 GOTO(out, result = -ENOMEM);
488         }
489         GOTO(out, result = 0);
490
491 out:
492         LINVRNT(osd_invariant(obj));
493         return result;
494 }
495
496 /*
497  * Concurrency: shouldn't matter.
498  */
499 static void osd_object_init0(struct osd_object *obj)
500 {
501         LASSERT(obj->oo_inode != NULL);
502         obj->oo_dt.do_body_ops = &osd_body_ops;
503         obj->oo_dt.do_lu.lo_header->loh_attr |=
504                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
505 }
506
507 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
508 {
509         struct osd_thread_info  *info   = osd_oti_get(env);
510         struct lustre_mdt_attrs *lma    = &info->oti_mdt_attrs;
511         int                     rc;
512         ENTRY;
513
514         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
515         rc = __osd_xattr_get(obj->oo_inode, &info->oti_obj_dentry,
516                              XATTR_NAME_LMA, info->oti_mdt_attrs_old,
517                              LMA_OLD_SIZE);
518         if (rc > 0) {
519                 rc = 0;
520                 lustre_lma_swab(lma);
521                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
522                              CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT))) {
523                         rc = -EOPNOTSUPP;
524                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
525                               "fid = "DFID", ino = %lu: rc = %d\n",
526                               osd_obj2dev(obj)->od_svname,
527                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
528                               PFID(lu_object_fid(&obj->oo_dt.do_lu)),
529                               obj->oo_inode->i_ino, rc);
530                 }
531                 if (unlikely(!lu_fid_eq(lu_object_fid(&obj->oo_dt.do_lu),
532                                         &lma->lma_self_fid))) {
533                         CDEBUG(D_INODE, "%s: FID "DFID" != self_fid "DFID"\n",
534                                osd_obj2dev(obj)->od_svname,
535                                PFID(lu_object_fid(&obj->oo_dt.do_lu)),
536                                PFID(&lma->lma_self_fid));
537                         if (obj->oo_inode != NULL) {
538                                 iput(obj->oo_inode);
539                                 obj->oo_inode = NULL;
540                         }
541                         rc = -ESTALE;
542                 }
543         } else if (rc == -ENODATA) {
544                 /* haven't initialize LMA xattr */
545                 rc = 0;
546         }
547
548         RETURN(rc);
549 }
550
551 /*
552  * Concurrency: no concurrent access is possible that early in object
553  * life-cycle.
554  */
555 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
556                            const struct lu_object_conf *conf)
557 {
558         struct osd_object *obj = osd_obj(l);
559         int result;
560
561         LINVRNT(osd_invariant(obj));
562
563         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
564                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
565                 l->lo_header->loh_attr |= LOHA_EXISTS;
566                 return 0;
567         }
568
569         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
570         obj->oo_dt.do_body_ops = &osd_body_ops_new;
571         if (result == 0 && obj->oo_inode != NULL) {
572                 result = osd_check_lma(env, obj);
573                 if (result != 0)
574                         return result;
575
576                 osd_object_init0(obj);
577         }
578
579         LINVRNT(osd_invariant(obj));
580         return result;
581 }
582
583 /*
584  * Concurrency: no concurrent access is possible that late in object
585  * life-cycle.
586  */
587 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
588 {
589         struct osd_object *obj = osd_obj(l);
590
591         LINVRNT(osd_invariant(obj));
592
593         dt_object_fini(&obj->oo_dt);
594         if (obj->oo_hl_head != NULL)
595                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
596         OBD_FREE_PTR(obj);
597 }
598
599 /*
600  * Concurrency: no concurrent access is possible that late in object
601  * life-cycle.
602  */
603 static void osd_index_fini(struct osd_object *o)
604 {
605         struct iam_container *bag;
606
607         if (o->oo_dir != NULL) {
608                 bag = &o->oo_dir->od_container;
609                 if (o->oo_inode != NULL) {
610                         if (bag->ic_object == o->oo_inode)
611                                 iam_container_fini(bag);
612                 }
613                 OBD_FREE_PTR(o->oo_dir);
614                 o->oo_dir = NULL;
615         }
616 }
617
618 /*
619  * Concurrency: no concurrent access is possible that late in object
620  * life-cycle (for all existing callers, that is. New callers have to provide
621  * their own locking.)
622  */
623 static int osd_inode_unlinked(const struct inode *inode)
624 {
625         return inode->i_nlink == 0;
626 }
627
628 enum {
629         OSD_TXN_OI_DELETE_CREDITS    = 20,
630         OSD_TXN_INODE_DELETE_CREDITS = 20
631 };
632
633 /*
634  * Journal
635  */
636
637 #if OSD_THANDLE_STATS
638 /**
639  * Set time when the handle is allocated
640  */
641 static void osd_th_alloced(struct osd_thandle *oth)
642 {
643         oth->oth_alloced = cfs_time_current();
644 }
645
646 /**
647  * Set time when the handle started
648  */
649 static void osd_th_started(struct osd_thandle *oth)
650 {
651         oth->oth_started = cfs_time_current();
652 }
653
654 /**
655  * Helper function to convert time interval to microseconds packed in
656  * long int.
657  */
658 static long interval_to_usec(cfs_time_t start, cfs_time_t end)
659 {
660         struct timeval val;
661
662         cfs_duration_usec(cfs_time_sub(end, start), &val);
663         return val.tv_sec * 1000000 + val.tv_usec;
664 }
665
666 /**
667  * Check whether the we deal with this handle for too long.
668  */
669 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
670                                 cfs_time_t alloced, cfs_time_t started,
671                                 cfs_time_t closed)
672 {
673         cfs_time_t now = cfs_time_current();
674
675         LASSERT(dev != NULL);
676
677         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
678                             interval_to_usec(alloced, started));
679         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
680                             interval_to_usec(started, closed));
681         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
682                             interval_to_usec(closed, now));
683
684         if (cfs_time_before(cfs_time_add(alloced, cfs_time_seconds(30)), now)) {
685                 CWARN("transaction handle %p was open for too long: "
686                       "now "CFS_TIME_T" ,"
687                       "alloced "CFS_TIME_T" ,"
688                       "started "CFS_TIME_T" ,"
689                       "closed "CFS_TIME_T"\n",
690                       oth, now, alloced, started, closed);
691                 libcfs_debug_dumpstack(NULL);
692         }
693 }
694
695 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
696 {                                                                       \
697         cfs_time_t __closed = cfs_time_current();                       \
698         cfs_time_t __alloced = oth->oth_alloced;                        \
699         cfs_time_t __started = oth->oth_started;                        \
700                                                                         \
701         expr;                                                           \
702         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
703 }
704
705 #else /* OSD_THANDLE_STATS */
706
707 #define osd_th_alloced(h)                  do {} while(0)
708 #define osd_th_started(h)                  do {} while(0)
709 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
710
711 #endif /* OSD_THANDLE_STATS */
712
713 /*
714  * Concurrency: doesn't access mutable data.
715  */
716 static int osd_param_is_not_sane(const struct osd_device *dev,
717                                  const struct thandle *th)
718 {
719         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
720
721         return oh->ot_credits > osd_journal(dev)->j_max_transaction_buffers;
722 }
723
724 /*
725  * Concurrency: shouldn't matter.
726  */
727 static void osd_trans_commit_cb(struct super_block *sb,
728                                 struct ldiskfs_journal_cb_entry *jcb, int error)
729 {
730         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
731         struct thandle     *th  = &oh->ot_super;
732         struct lu_device   *lud = &th->th_dev->dd_lu_dev;
733         struct dt_txn_commit_cb *dcb, *tmp;
734
735         LASSERT(oh->ot_handle == NULL);
736
737         if (error)
738                 CERROR("transaction @0x%p commit error: %d\n", th, error);
739
740         dt_txn_hook_commit(th);
741
742         /* call per-transaction callbacks if any */
743         cfs_list_for_each_entry_safe(dcb, tmp, &oh->ot_dcb_list, dcb_linkage) {
744                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
745                          "commit callback entry: magic=%x name='%s'\n",
746                          dcb->dcb_magic, dcb->dcb_name);
747                 cfs_list_del_init(&dcb->dcb_linkage);
748                 dcb->dcb_func(NULL, th, dcb, error);
749         }
750
751         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
752         lu_device_put(lud);
753         th->th_dev = NULL;
754
755         lu_context_exit(&th->th_ctx);
756         lu_context_fini(&th->th_ctx);
757         OBD_FREE_PTR(oh);
758 }
759
760 static struct thandle *osd_trans_create(const struct lu_env *env,
761                                         struct dt_device *d)
762 {
763         struct osd_thread_info *oti = osd_oti_get(env);
764         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
765         struct osd_thandle     *oh;
766         struct thandle         *th;
767         ENTRY;
768
769         /* on pending IO in this thread should left from prev. request */
770         LASSERT(cfs_atomic_read(&iobuf->dr_numreqs) == 0);
771
772         th = ERR_PTR(-ENOMEM);
773         OBD_ALLOC_GFP(oh, sizeof *oh, __GFP_IO);
774         if (oh != NULL) {
775                 oh->ot_quota_trans = &oti->oti_quota_trans;
776                 memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
777                 th = &oh->ot_super;
778                 th->th_dev = d;
779                 th->th_result = 0;
780                 th->th_tags = LCT_TX_HANDLE;
781                 oh->ot_credits = 0;
782                 oti->oti_dev = osd_dt_dev(d);
783                 CFS_INIT_LIST_HEAD(&oh->ot_dcb_list);
784                 osd_th_alloced(oh);
785
786                 memset(oti->oti_declare_ops, 0,
787                                         sizeof(oti->oti_declare_ops));
788                 memset(oti->oti_declare_ops_rb, 0,
789                                         sizeof(oti->oti_declare_ops_rb));
790                 memset(oti->oti_declare_ops_cred, 0,
791                                         sizeof(oti->oti_declare_ops_cred));
792                 oti->oti_rollback = false;
793         }
794         RETURN(th);
795 }
796
797 /*
798  * Concurrency: shouldn't matter.
799  */
800 int osd_trans_start(const struct lu_env *env, struct dt_device *d,
801                     struct thandle *th)
802 {
803         struct osd_thread_info *oti = osd_oti_get(env);
804         struct osd_device  *dev = osd_dt_dev(d);
805         handle_t           *jh;
806         struct osd_thandle *oh;
807         int rc;
808
809         ENTRY;
810
811         LASSERT(current->journal_info == NULL);
812
813         oh = container_of0(th, struct osd_thandle, ot_super);
814         LASSERT(oh != NULL);
815         LASSERT(oh->ot_handle == NULL);
816
817         rc = dt_txn_hook_start(env, d, th);
818         if (rc != 0)
819                 GOTO(out, rc);
820
821         if (unlikely(osd_param_is_not_sane(dev, th))) {
822                 static unsigned long last_printed;
823                 static int last_credits;
824
825                 CWARN("%.16s: too many transaction credits (%d > %d)\n",
826                       LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
827                       oh->ot_credits,
828                       osd_journal(dev)->j_max_transaction_buffers);
829                 CWARN("  create: %u/%u, delete: %u/%u, destroy: %u/%u\n",
830                       oti->oti_declare_ops[OSD_OT_CREATE],
831                       oti->oti_declare_ops_cred[OSD_OT_CREATE],
832                       oti->oti_declare_ops[OSD_OT_DELETE],
833                       oti->oti_declare_ops_cred[OSD_OT_DELETE],
834                       oti->oti_declare_ops[OSD_OT_DESTROY],
835                       oti->oti_declare_ops_cred[OSD_OT_DESTROY]);
836                 CWARN("  attr_set: %u/%u, xattr_set: %u/%u\n",
837                       oti->oti_declare_ops[OSD_OT_ATTR_SET],
838                       oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
839                       oti->oti_declare_ops[OSD_OT_XATTR_SET],
840                       oti->oti_declare_ops_cred[OSD_OT_XATTR_SET]);
841                 CWARN("  write: %u/%u, punch: %u/%u, quota %u/%u\n",
842                       oti->oti_declare_ops[OSD_OT_WRITE],
843                       oti->oti_declare_ops_cred[OSD_OT_WRITE],
844                       oti->oti_declare_ops[OSD_OT_PUNCH],
845                       oti->oti_declare_ops_cred[OSD_OT_PUNCH],
846                       oti->oti_declare_ops[OSD_OT_QUOTA],
847                       oti->oti_declare_ops_cred[OSD_OT_QUOTA]);
848                 CWARN("  insert: %u/%u, delete: %u/%u\n",
849                       oti->oti_declare_ops[OSD_OT_INSERT],
850                       oti->oti_declare_ops_cred[OSD_OT_INSERT],
851                       oti->oti_declare_ops[OSD_OT_DESTROY],
852                       oti->oti_declare_ops_cred[OSD_OT_DESTROY]);
853                 CWARN("  ref_add: %u/%u, ref_del: %u/%u\n",
854                       oti->oti_declare_ops[OSD_OT_REF_ADD],
855                       oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
856                       oti->oti_declare_ops[OSD_OT_REF_DEL],
857                       oti->oti_declare_ops_cred[OSD_OT_REF_DEL]);
858
859                 if (last_credits != oh->ot_credits &&
860                     time_after(jiffies, last_printed + 60 * HZ)) {
861                         libcfs_debug_dumpstack(NULL);
862                         last_credits = oh->ot_credits;
863                         last_printed = jiffies;
864                 }
865                 /* XXX Limit the credits to 'max_transaction_buffers', and
866                  *     let the underlying filesystem to catch the error if
867                  *     we really need so many credits.
868                  *
869                  *     This should be removed when we can calculate the
870                  *     credits precisely. */
871                 oh->ot_credits = osd_journal(dev)->j_max_transaction_buffers;
872         }
873
874         /*
875          * XXX temporary stuff. Some abstraction layer should
876          * be used.
877          */
878         jh = ldiskfs_journal_start_sb(osd_sb(dev), oh->ot_credits);
879         osd_th_started(oh);
880         if (!IS_ERR(jh)) {
881                 oh->ot_handle = jh;
882                 LASSERT(oti->oti_txns == 0);
883                 lu_context_init(&th->th_ctx, th->th_tags);
884                 lu_context_enter(&th->th_ctx);
885
886                 lu_device_get(&d->dd_lu_dev);
887                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
888                               "osd-tx", th);
889                 oti->oti_txns++;
890                 rc = 0;
891         } else {
892                 rc = PTR_ERR(jh);
893         }
894 out:
895         RETURN(rc);
896 }
897
898 /*
899  * Concurrency: shouldn't matter.
900  */
901 static int osd_trans_stop(const struct lu_env *env, struct thandle *th)
902 {
903         int                     rc = 0;
904         struct osd_thandle     *oh;
905         struct osd_thread_info *oti = osd_oti_get(env);
906         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
907         struct qsd_instance    *qsd = oti->oti_dev->od_quota_slave;
908         ENTRY;
909
910         oh = container_of0(th, struct osd_thandle, ot_super);
911
912         if (qsd != NULL)
913                 /* inform the quota slave device that the transaction is
914                  * stopping */
915                 qsd_op_end(env, qsd, oh->ot_quota_trans);
916         oh->ot_quota_trans = NULL;
917
918         if (oh->ot_handle != NULL) {
919                 handle_t *hdl = oh->ot_handle;
920
921                 /*
922                  * add commit callback
923                  * notice we don't do this in osd_trans_start()
924                  * as underlying transaction can change during truncate
925                  */
926                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
927                                          &oh->ot_jcb);
928
929                 LASSERT(oti->oti_txns == 1);
930                 oti->oti_txns--;
931                 rc = dt_txn_hook_stop(env, th);
932                 if (rc != 0)
933                         CERROR("Failure in transaction hook: %d\n", rc);
934
935                 /* hook functions might modify th_sync */
936                 hdl->h_sync = th->th_sync;
937
938                 oh->ot_handle = NULL;
939                 OSD_CHECK_SLOW_TH(oh, oti->oti_dev,
940                                   rc = ldiskfs_journal_stop(hdl));
941                 if (rc != 0)
942                         CERROR("Failure to stop transaction: %d\n", rc);
943         } else {
944                 OBD_FREE_PTR(oh);
945         }
946
947         /* as we want IO to journal and data IO be concurrent, we don't block
948          * awaiting data IO completion in osd_do_bio(), instead we wait here
949          * once transaction is submitted to the journal. all reqular requests
950          * don't do direct IO (except read/write), thus this wait_event becomes
951          * no-op for them.
952          *
953          * IMPORTANT: we have to wait till any IO submited by the thread is
954          * completed otherwise iobuf may be corrupted by different request
955          */
956         cfs_wait_event(iobuf->dr_wait,
957                        cfs_atomic_read(&iobuf->dr_numreqs) == 0);
958         if (!rc)
959                 rc = iobuf->dr_error;
960
961         RETURN(rc);
962 }
963
964 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
965 {
966         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
967                                                ot_super);
968
969         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
970         LASSERT(&dcb->dcb_func != NULL);
971         cfs_list_add(&dcb->dcb_linkage, &oh->ot_dcb_list);
972
973         return 0;
974 }
975
976 /*
977  * Called just before object is freed. Releases all resources except for
978  * object itself (that is released by osd_object_free()).
979  *
980  * Concurrency: no concurrent access is possible that late in object
981  * life-cycle.
982  */
983 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
984 {
985         struct osd_object *obj   = osd_obj(l);
986         struct inode      *inode = obj->oo_inode;
987
988         LINVRNT(osd_invariant(obj));
989
990         /*
991          * If object is unlinked remove fid->ino mapping from object index.
992          */
993
994         osd_index_fini(obj);
995         if (inode != NULL) {
996                 struct qsd_instance     *qsd = osd_obj2dev(obj)->od_quota_slave;
997                 qid_t                    uid = inode->i_uid;
998                 qid_t                    gid = inode->i_gid;
999
1000                 iput(inode);
1001                 obj->oo_inode = NULL;
1002
1003                 if (qsd != NULL) {
1004                         struct osd_thread_info  *info = osd_oti_get(env);
1005                         struct lquota_id_info   *qi = &info->oti_qi;
1006
1007                         /* Release granted quota to master if necessary */
1008                         qi->lqi_id.qid_uid = uid;
1009                         qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
1010
1011                         qi->lqi_id.qid_uid = gid;
1012                         qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
1013                 }
1014         }
1015 }
1016
1017 /*
1018  * Concurrency: ->loo_object_release() is called under site spin-lock.
1019  */
1020 static void osd_object_release(const struct lu_env *env,
1021                                struct lu_object *l)
1022 {
1023 }
1024
1025 /*
1026  * Concurrency: shouldn't matter.
1027  */
1028 static int osd_object_print(const struct lu_env *env, void *cookie,
1029                             lu_printer_t p, const struct lu_object *l)
1030 {
1031         struct osd_object *o = osd_obj(l);
1032         struct iam_descr  *d;
1033
1034         if (o->oo_dir != NULL)
1035                 d = o->oo_dir->od_container.ic_descr;
1036         else
1037                 d = NULL;
1038         return (*p)(env, cookie,
1039                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
1040                     o, o->oo_inode,
1041                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
1042                     o->oo_inode ? o->oo_inode->i_generation : 0,
1043                     d ? d->id_ops->id_name : "plain");
1044 }
1045
1046 /*
1047  * Concurrency: shouldn't matter.
1048  */
1049 int osd_statfs(const struct lu_env *env, struct dt_device *d,
1050                struct obd_statfs *sfs)
1051 {
1052         struct osd_device  *osd = osd_dt_dev(d);
1053         struct super_block *sb = osd_sb(osd);
1054         struct kstatfs     *ksfs;
1055         int result = 0;
1056
1057         if (unlikely(osd->od_mnt == NULL))
1058                 return -EINPROGRESS;
1059
1060         /* osd_lproc.c call this without env, allocate ksfs for that case */
1061         if (unlikely(env == NULL)) {
1062                 OBD_ALLOC_PTR(ksfs);
1063                 if (ksfs == NULL)
1064                         return -ENOMEM;
1065         } else {
1066                 ksfs = &osd_oti_get(env)->oti_ksfs;
1067         }
1068
1069         spin_lock(&osd->od_osfs_lock);
1070         /* cache 1 second */
1071         if (cfs_time_before_64(osd->od_osfs_age, cfs_time_shift_64(-1))) {
1072                 result = sb->s_op->statfs(sb->s_root, ksfs);
1073                 if (likely(result == 0)) { /* N.B. statfs can't really fail */
1074                         osd->od_osfs_age = cfs_time_current_64();
1075                         statfs_pack(&osd->od_statfs, ksfs);
1076                         if (sb->s_flags & MS_RDONLY)
1077                                 sfs->os_state = OS_STATE_READONLY;
1078                 }
1079         }
1080
1081         if (likely(result == 0))
1082                 *sfs = osd->od_statfs;
1083         spin_unlock(&osd->od_osfs_lock);
1084
1085         if (unlikely(env == NULL))
1086                 OBD_FREE_PTR(ksfs);
1087
1088         return result;
1089 }
1090
1091 /**
1092  * Estimate space needed for file creations. We assume the largest filename
1093  * which is 2^64 - 1, hence a filename of 20 chars.
1094  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
1095  */
1096 #ifdef __LDISKFS_DIR_REC_LEN
1097 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
1098 #else
1099 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
1100 #endif
1101
1102 /*
1103  * Concurrency: doesn't access mutable data.
1104  */
1105 static void osd_conf_get(const struct lu_env *env,
1106                          const struct dt_device *dev,
1107                          struct dt_device_param *param)
1108 {
1109         struct super_block *sb = osd_sb(osd_dt_dev(dev));
1110
1111         /*
1112          * XXX should be taken from not-yet-existing fs abstraction layer.
1113          */
1114         param->ddp_mnt = osd_dt_dev(dev)->od_mnt;
1115         param->ddp_max_name_len = LDISKFS_NAME_LEN;
1116         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
1117         param->ddp_block_shift  = sb->s_blocksize_bits;
1118         param->ddp_mount_type     = LDD_MT_LDISKFS;
1119         param->ddp_maxbytes       = sb->s_maxbytes;
1120         /* Overhead estimate should be fairly accurate, so we really take a tiny
1121          * error margin which also avoids fragmenting the filesystem too much */
1122         param->ddp_grant_reserved = 2; /* end up to be 1.9% after conversion */
1123         /* inode are statically allocated, so per-inode space consumption
1124          * is the space consumed by the directory entry */
1125         param->ddp_inodespace     = PER_OBJ_USAGE;
1126         /* per-fragment overhead to be used by the client code */
1127         param->ddp_grant_frag     = 6 * LDISKFS_BLOCK_SIZE(sb);
1128         param->ddp_mntopts      = 0;
1129         if (test_opt(sb, XATTR_USER))
1130                 param->ddp_mntopts |= MNTOPT_USERXATTR;
1131         if (test_opt(sb, POSIX_ACL))
1132                 param->ddp_mntopts |= MNTOPT_ACL;
1133
1134 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
1135         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EA_INODE))
1136                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE;
1137         else
1138 #endif
1139                 param->ddp_max_ea_size = sb->s_blocksize;
1140
1141 }
1142
1143 /*
1144  * Concurrency: shouldn't matter.
1145  */
1146 static int osd_sync(const struct lu_env *env, struct dt_device *d)
1147 {
1148         CDEBUG(D_HA, "syncing OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1149         return ldiskfs_force_commit(osd_sb(osd_dt_dev(d)));
1150 }
1151
1152 /**
1153  * Start commit for OSD device.
1154  *
1155  * An implementation of dt_commit_async method for OSD device.
1156  * Asychronously starts underlayng fs sync and thereby a transaction
1157  * commit.
1158  *
1159  * \param env environment
1160  * \param d dt device
1161  *
1162  * \see dt_device_operations
1163  */
1164 static int osd_commit_async(const struct lu_env *env,
1165                             struct dt_device *d)
1166 {
1167         struct super_block *s = osd_sb(osd_dt_dev(d));
1168         ENTRY;
1169
1170         CDEBUG(D_HA, "async commit OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1171         RETURN(s->s_op->sync_fs(s, 0));
1172 }
1173
1174 /*
1175  * Concurrency: shouldn't matter.
1176  */
1177
1178 static int osd_ro(const struct lu_env *env, struct dt_device *d)
1179 {
1180         struct super_block *sb = osd_sb(osd_dt_dev(d));
1181         struct block_device *dev = sb->s_bdev;
1182 #ifdef HAVE_DEV_SET_RDONLY
1183         struct block_device *jdev = LDISKFS_SB(sb)->journal_bdev;
1184         int rc = 0;
1185 #else
1186         int rc = -EOPNOTSUPP;
1187 #endif
1188         ENTRY;
1189
1190 #ifdef HAVE_DEV_SET_RDONLY
1191         CERROR("*** setting %s read-only ***\n", osd_dt_dev(d)->od_svname);
1192
1193         if (jdev && (jdev != dev)) {
1194                 CDEBUG(D_IOCTL | D_HA, "set journal dev %lx rdonly\n",
1195                        (long)jdev);
1196                 dev_set_rdonly(jdev);
1197         }
1198         CDEBUG(D_IOCTL | D_HA, "set dev %lx rdonly\n", (long)dev);
1199         dev_set_rdonly(dev);
1200 #else
1201         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
1202                osd_dt_dev(d)->od_svname, (long)dev, rc);
1203 #endif
1204         RETURN(rc);
1205 }
1206
1207 /*
1208  * Concurrency: serialization provided by callers.
1209  */
1210 static int osd_init_capa_ctxt(const struct lu_env *env, struct dt_device *d,
1211                               int mode, unsigned long timeout, __u32 alg,
1212                               struct lustre_capa_key *keys)
1213 {
1214         struct osd_device *dev = osd_dt_dev(d);
1215         ENTRY;
1216
1217         dev->od_fl_capa = mode;
1218         dev->od_capa_timeout = timeout;
1219         dev->od_capa_alg = alg;
1220         dev->od_capa_keys = keys;
1221         RETURN(0);
1222 }
1223
1224 /**
1225  * Note: we do not count into QUOTA here.
1226  * If we mount with --data_journal we may need more.
1227  */
1228 const int osd_dto_credits_noquota[DTO_NR] = {
1229         /**
1230          * Insert/Delete.
1231          * INDEX_EXTRA_TRANS_BLOCKS(8) +
1232          * SINGLEDATA_TRANS_BLOCKS(8)
1233          * XXX Note: maybe iam need more, since iam have more level than
1234          *           EXT3 htree.
1235          */
1236         [DTO_INDEX_INSERT]  = 16,
1237         [DTO_INDEX_DELETE]  = 16,
1238         /**
1239          * Used for OI scrub
1240          */
1241         [DTO_INDEX_UPDATE]  = 16,
1242         /**
1243          * Create a object. The same as create object in EXT3.
1244          * DATA_TRANS_BLOCKS(14) +
1245          * INDEX_EXTRA_BLOCKS(8) +
1246          * 3(inode bits, groups, GDT)
1247          */
1248         [DTO_OBJECT_CREATE] = 25,
1249         /**
1250          * XXX: real credits to be fixed
1251          */
1252         [DTO_OBJECT_DELETE] = 25,
1253         /**
1254          * Attr set credits (inode)
1255          */
1256         [DTO_ATTR_SET_BASE] = 1,
1257         /**
1258          * Xattr set. The same as xattr of EXT3.
1259          * DATA_TRANS_BLOCKS(14)
1260          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
1261          * are also counted in. Do not know why?
1262          */
1263         [DTO_XATTR_SET]     = 14,
1264         [DTO_LOG_REC]       = 14,
1265         /**
1266          * credits for inode change during write.
1267          */
1268         [DTO_WRITE_BASE]    = 3,
1269         /**
1270          * credits for single block write.
1271          */
1272         [DTO_WRITE_BLOCK]   = 14,
1273         /**
1274          * Attr set credits for chown.
1275          * This is extra credits for setattr, and it is null without quota
1276          */
1277         [DTO_ATTR_SET_CHOWN]= 0
1278 };
1279
1280 static const struct dt_device_operations osd_dt_ops = {
1281         .dt_root_get       = osd_root_get,
1282         .dt_statfs         = osd_statfs,
1283         .dt_trans_create   = osd_trans_create,
1284         .dt_trans_start    = osd_trans_start,
1285         .dt_trans_stop     = osd_trans_stop,
1286         .dt_trans_cb_add   = osd_trans_cb_add,
1287         .dt_conf_get       = osd_conf_get,
1288         .dt_sync           = osd_sync,
1289         .dt_ro             = osd_ro,
1290         .dt_commit_async   = osd_commit_async,
1291         .dt_init_capa_ctxt = osd_init_capa_ctxt,
1292 };
1293
1294 static void osd_object_read_lock(const struct lu_env *env,
1295                                  struct dt_object *dt, unsigned role)
1296 {
1297         struct osd_object *obj = osd_dt_obj(dt);
1298         struct osd_thread_info *oti = osd_oti_get(env);
1299
1300         LINVRNT(osd_invariant(obj));
1301
1302         LASSERT(obj->oo_owner != env);
1303         down_read_nested(&obj->oo_sem, role);
1304
1305         LASSERT(obj->oo_owner == NULL);
1306         oti->oti_r_locks++;
1307 }
1308
1309 static void osd_object_write_lock(const struct lu_env *env,
1310                                   struct dt_object *dt, unsigned role)
1311 {
1312         struct osd_object *obj = osd_dt_obj(dt);
1313         struct osd_thread_info *oti = osd_oti_get(env);
1314
1315         LINVRNT(osd_invariant(obj));
1316
1317         LASSERT(obj->oo_owner != env);
1318         down_write_nested(&obj->oo_sem, role);
1319
1320         LASSERT(obj->oo_owner == NULL);
1321         obj->oo_owner = env;
1322         oti->oti_w_locks++;
1323 }
1324
1325 static void osd_object_read_unlock(const struct lu_env *env,
1326                                    struct dt_object *dt)
1327 {
1328         struct osd_object *obj = osd_dt_obj(dt);
1329         struct osd_thread_info *oti = osd_oti_get(env);
1330
1331         LINVRNT(osd_invariant(obj));
1332
1333         LASSERT(oti->oti_r_locks > 0);
1334         oti->oti_r_locks--;
1335         up_read(&obj->oo_sem);
1336 }
1337
1338 static void osd_object_write_unlock(const struct lu_env *env,
1339                                     struct dt_object *dt)
1340 {
1341         struct osd_object *obj = osd_dt_obj(dt);
1342         struct osd_thread_info *oti = osd_oti_get(env);
1343
1344         LINVRNT(osd_invariant(obj));
1345
1346         LASSERT(obj->oo_owner == env);
1347         LASSERT(oti->oti_w_locks > 0);
1348         oti->oti_w_locks--;
1349         obj->oo_owner = NULL;
1350         up_write(&obj->oo_sem);
1351 }
1352
1353 static int osd_object_write_locked(const struct lu_env *env,
1354                                    struct dt_object *dt)
1355 {
1356         struct osd_object *obj = osd_dt_obj(dt);
1357
1358         LINVRNT(osd_invariant(obj));
1359
1360         return obj->oo_owner == env;
1361 }
1362
1363 static int capa_is_sane(const struct lu_env *env,
1364                         struct osd_device *dev,
1365                         struct lustre_capa *capa,
1366                         struct lustre_capa_key *keys)
1367 {
1368         struct osd_thread_info *oti = osd_oti_get(env);
1369         struct lustre_capa *tcapa = &oti->oti_capa;
1370         struct obd_capa *oc;
1371         int i, rc = 0;
1372         ENTRY;
1373
1374         oc = capa_lookup(dev->od_capa_hash, capa, 0);
1375         if (oc) {
1376                 if (capa_is_expired(oc)) {
1377                         DEBUG_CAPA(D_ERROR, capa, "expired");
1378                         rc = -ESTALE;
1379                 }
1380                 capa_put(oc);
1381                 RETURN(rc);
1382         }
1383
1384         if (capa_is_expired_sec(capa)) {
1385                 DEBUG_CAPA(D_ERROR, capa, "expired");
1386                 RETURN(-ESTALE);
1387         }
1388
1389         spin_lock(&capa_lock);
1390         for (i = 0; i < 2; i++) {
1391                 if (keys[i].lk_keyid == capa->lc_keyid) {
1392                         oti->oti_capa_key = keys[i];
1393                         break;
1394                 }
1395         }
1396         spin_unlock(&capa_lock);
1397
1398         if (i == 2) {
1399                 DEBUG_CAPA(D_ERROR, capa, "no matched capa key");
1400                 RETURN(-ESTALE);
1401         }
1402
1403         rc = capa_hmac(tcapa->lc_hmac, capa, oti->oti_capa_key.lk_key);
1404         if (rc)
1405                 RETURN(rc);
1406
1407         if (memcmp(tcapa->lc_hmac, capa->lc_hmac, sizeof(capa->lc_hmac))) {
1408                 DEBUG_CAPA(D_ERROR, capa, "HMAC mismatch");
1409                 RETURN(-EACCES);
1410         }
1411
1412         oc = capa_add(dev->od_capa_hash, capa);
1413         capa_put(oc);
1414
1415         RETURN(0);
1416 }
1417
1418 int osd_object_auth(const struct lu_env *env, struct dt_object *dt,
1419                     struct lustre_capa *capa, __u64 opc)
1420 {
1421         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
1422         struct osd_device *dev = osd_dev(dt->do_lu.lo_dev);
1423         struct md_capainfo *ci;
1424         int rc;
1425
1426         if (!dev->od_fl_capa)
1427                 return 0;
1428
1429         if (capa == BYPASS_CAPA)
1430                 return 0;
1431
1432         ci = md_capainfo(env);
1433         if (unlikely(!ci))
1434                 return 0;
1435
1436         if (ci->mc_auth == LC_ID_NONE)
1437                 return 0;
1438
1439         if (!capa) {
1440                 CERROR("no capability is provided for fid "DFID"\n", PFID(fid));
1441                 return -EACCES;
1442         }
1443
1444         if (!lu_fid_eq(fid, &capa->lc_fid)) {
1445                 DEBUG_CAPA(D_ERROR, capa, "fid "DFID" mismatch with",
1446                            PFID(fid));
1447                 return -EACCES;
1448         }
1449
1450         if (!capa_opc_supported(capa, opc)) {
1451                 DEBUG_CAPA(D_ERROR, capa, "opc "LPX64" not supported by", opc);
1452                 return -EACCES;
1453         }
1454
1455         if ((rc = capa_is_sane(env, dev, capa, dev->od_capa_keys))) {
1456                 DEBUG_CAPA(D_ERROR, capa, "insane (rc %d)", rc);
1457                 return -EACCES;
1458         }
1459
1460         return 0;
1461 }
1462
1463 static struct timespec *osd_inode_time(const struct lu_env *env,
1464                                        struct inode *inode, __u64 seconds)
1465 {
1466         struct osd_thread_info  *oti = osd_oti_get(env);
1467         struct timespec         *t   = &oti->oti_time;
1468
1469         t->tv_sec = seconds;
1470         t->tv_nsec = 0;
1471         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
1472         return t;
1473 }
1474
1475
1476 static void osd_inode_getattr(const struct lu_env *env,
1477                               struct inode *inode, struct lu_attr *attr)
1478 {
1479         attr->la_valid      |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
1480                                LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
1481                                LA_FLAGS | LA_NLINK | LA_RDEV | LA_BLKSIZE |
1482                                LA_TYPE;
1483
1484         attr->la_atime      = LTIME_S(inode->i_atime);
1485         attr->la_mtime      = LTIME_S(inode->i_mtime);
1486         attr->la_ctime      = LTIME_S(inode->i_ctime);
1487         attr->la_mode       = inode->i_mode;
1488         attr->la_size       = i_size_read(inode);
1489         attr->la_blocks     = inode->i_blocks;
1490         attr->la_uid        = inode->i_uid;
1491         attr->la_gid        = inode->i_gid;
1492         attr->la_flags      = LDISKFS_I(inode)->i_flags;
1493         attr->la_nlink      = inode->i_nlink;
1494         attr->la_rdev       = inode->i_rdev;
1495         attr->la_blksize    = 1 << inode->i_blkbits;
1496         attr->la_blkbits    = inode->i_blkbits;
1497 }
1498
1499 static int osd_attr_get(const struct lu_env *env,
1500                         struct dt_object *dt,
1501                         struct lu_attr *attr,
1502                         struct lustre_capa *capa)
1503 {
1504         struct osd_object *obj = osd_dt_obj(dt);
1505
1506         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1507         LINVRNT(osd_invariant(obj));
1508
1509         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
1510                 return -EACCES;
1511
1512         spin_lock(&obj->oo_guard);
1513         osd_inode_getattr(env, obj->oo_inode, attr);
1514         spin_unlock(&obj->oo_guard);
1515         return 0;
1516 }
1517
1518 static int osd_declare_attr_set(const struct lu_env *env,
1519                                 struct dt_object *dt,
1520                                 const struct lu_attr *attr,
1521                                 struct thandle *handle)
1522 {
1523         struct osd_thandle     *oh;
1524         struct osd_object      *obj;
1525         struct osd_thread_info *info = osd_oti_get(env);
1526         struct lquota_id_info  *qi = &info->oti_qi;
1527         long long               bspace;
1528         int                     rc = 0;
1529         bool                    allocated;
1530         ENTRY;
1531
1532         LASSERT(dt != NULL);
1533         LASSERT(handle != NULL);
1534
1535         obj = osd_dt_obj(dt);
1536         LASSERT(osd_invariant(obj));
1537
1538         oh = container_of0(handle, struct osd_thandle, ot_super);
1539         LASSERT(oh->ot_handle == NULL);
1540
1541         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
1542                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
1543
1544         if (attr == NULL || obj->oo_inode == NULL)
1545                 RETURN(rc);
1546
1547         bspace   = obj->oo_inode->i_blocks;
1548         bspace <<= obj->oo_inode->i_sb->s_blocksize_bits;
1549         bspace   = toqb(bspace);
1550
1551         /* Changing ownership is always preformed by super user, it should not
1552          * fail with EDQUOT.
1553          *
1554          * We still need to call the osd_declare_qid() to calculate the journal
1555          * credits for updating quota accounting files and to trigger quota
1556          * space adjustment once the operation is completed.*/
1557         if ((attr->la_valid & LA_UID) != 0 &&
1558              attr->la_uid != obj->oo_inode->i_uid) {
1559                 qi->lqi_type = USRQUOTA;
1560
1561                 /* inode accounting */
1562                 qi->lqi_is_blk = false;
1563
1564                 /* one more inode for the new owner ... */
1565                 qi->lqi_id.qid_uid = attr->la_uid;
1566                 qi->lqi_space      = 1;
1567                 allocated = (attr->la_uid == 0) ? true : false;
1568                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1569                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1570                         rc = 0;
1571                 if (rc)
1572                         RETURN(rc);
1573
1574                 /* and one less inode for the current uid */
1575                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1576                 qi->lqi_space      = -1;
1577                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1578                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1579                         rc = 0;
1580                 if (rc)
1581                         RETURN(rc);
1582
1583                 /* block accounting */
1584                 qi->lqi_is_blk = true;
1585
1586                 /* more blocks for the new owner ... */
1587                 qi->lqi_id.qid_uid = attr->la_uid;
1588                 qi->lqi_space      = bspace;
1589                 allocated = (attr->la_uid == 0) ? true : false;
1590                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1591                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1592                         rc = 0;
1593                 if (rc)
1594                         RETURN(rc);
1595
1596                 /* and finally less blocks for the current owner */
1597                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1598                 qi->lqi_space      = -bspace;
1599                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1600                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1601                         rc = 0;
1602                 if (rc)
1603                         RETURN(rc);
1604         }
1605
1606         if (attr->la_valid & LA_GID &&
1607             attr->la_gid != obj->oo_inode->i_gid) {
1608                 qi->lqi_type = GRPQUOTA;
1609
1610                 /* inode accounting */
1611                 qi->lqi_is_blk = false;
1612
1613                 /* one more inode for the new group owner ... */
1614                 qi->lqi_id.qid_gid = attr->la_gid;
1615                 qi->lqi_space      = 1;
1616                 allocated = (attr->la_gid == 0) ? true : false;
1617                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1618                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1619                         rc = 0;
1620                 if (rc)
1621                         RETURN(rc);
1622
1623                 /* and one less inode for the current gid */
1624                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1625                 qi->lqi_space      = -1;
1626                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1627                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1628                         rc = 0;
1629                 if (rc)
1630                         RETURN(rc);
1631
1632                 /* block accounting */
1633                 qi->lqi_is_blk = true;
1634
1635                 /* more blocks for the new owner ... */
1636                 qi->lqi_id.qid_gid = attr->la_gid;
1637                 qi->lqi_space      = bspace;
1638                 allocated = (attr->la_gid == 0) ? true : false;
1639                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1640                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1641                         rc = 0;
1642                 if (rc)
1643                         RETURN(rc);
1644
1645                 /* and finally less blocks for the current owner */
1646                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1647                 qi->lqi_space      = -bspace;
1648                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1649                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1650                         rc = 0;
1651                 if (rc)
1652                         RETURN(rc);
1653         }
1654
1655         RETURN(rc);
1656 }
1657
1658 static int osd_inode_setattr(const struct lu_env *env,
1659                              struct inode *inode, const struct lu_attr *attr)
1660 {
1661         __u64 bits;
1662
1663         bits = attr->la_valid;
1664
1665         if (bits & LA_ATIME)
1666                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
1667         if (bits & LA_CTIME)
1668                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
1669         if (bits & LA_MTIME)
1670                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
1671         if (bits & LA_SIZE) {
1672                 LDISKFS_I(inode)->i_disksize = attr->la_size;
1673                 i_size_write(inode, attr->la_size);
1674         }
1675
1676 #if 0
1677         /* OSD should not change "i_blocks" which is used by quota.
1678          * "i_blocks" should be changed by ldiskfs only. */
1679         if (bits & LA_BLOCKS)
1680                 inode->i_blocks = attr->la_blocks;
1681 #endif
1682         if (bits & LA_MODE)
1683                 inode->i_mode   = (inode->i_mode & S_IFMT) |
1684                         (attr->la_mode & ~S_IFMT);
1685         if (bits & LA_UID)
1686                 inode->i_uid    = attr->la_uid;
1687         if (bits & LA_GID)
1688                 inode->i_gid    = attr->la_gid;
1689         if (bits & LA_NLINK)
1690                 set_nlink(inode, attr->la_nlink);
1691         if (bits & LA_RDEV)
1692                 inode->i_rdev   = attr->la_rdev;
1693
1694         if (bits & LA_FLAGS) {
1695                 /* always keep S_NOCMTIME */
1696                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
1697                                  S_NOCMTIME;
1698         }
1699         return 0;
1700 }
1701
1702 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
1703 {
1704         if ((attr->la_valid & LA_UID && attr->la_uid != inode->i_uid) ||
1705             (attr->la_valid & LA_GID && attr->la_gid != inode->i_gid)) {
1706                 struct iattr    iattr;
1707                 int             rc;
1708
1709                 iattr.ia_valid = 0;
1710                 if (attr->la_valid & LA_UID)
1711                         iattr.ia_valid |= ATTR_UID;
1712                 if (attr->la_valid & LA_GID)
1713                         iattr.ia_valid |= ATTR_GID;
1714                 iattr.ia_uid = attr->la_uid;
1715                 iattr.ia_gid = attr->la_gid;
1716
1717                 rc = ll_vfs_dq_transfer(inode, &iattr);
1718                 if (rc) {
1719                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
1720                                "enforcement enabled on the ldiskfs filesystem?",
1721                                inode->i_sb->s_id, rc);
1722                         return rc;
1723                 }
1724         }
1725         return 0;
1726 }
1727
1728 static int osd_attr_set(const struct lu_env *env,
1729                         struct dt_object *dt,
1730                         const struct lu_attr *attr,
1731                         struct thandle *handle,
1732                         struct lustre_capa *capa)
1733 {
1734         struct osd_object *obj = osd_dt_obj(dt);
1735         struct inode      *inode;
1736         int rc;
1737
1738         LASSERT(handle != NULL);
1739         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1740         LASSERT(osd_invariant(obj));
1741
1742         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
1743                 return -EACCES;
1744
1745         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
1746
1747         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING)) {
1748                 struct osd_thread_info  *oti  = osd_oti_get(env);
1749                 const struct lu_fid     *fid0 = lu_object_fid(&dt->do_lu);
1750                 struct lu_fid           *fid1 = &oti->oti_fid;
1751                 struct osd_inode_id     *id   = &oti->oti_id;
1752                 struct iam_path_descr   *ipd;
1753                 struct iam_container    *bag;
1754                 struct osd_thandle      *oh;
1755                 int                      rc;
1756
1757                 fid_cpu_to_be(fid1, fid0);
1758                 memset(id, 1, sizeof(*id));
1759                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
1760                                   fid0)->oi_dir.od_container;
1761                 ipd = osd_idx_ipd_get(env, bag);
1762                 if (unlikely(ipd == NULL))
1763                         RETURN(-ENOMEM);
1764
1765                 oh = container_of0(handle, struct osd_thandle, ot_super);
1766                 rc = iam_update(oh->ot_handle, bag, (const struct iam_key *)fid1,
1767                                 (const struct iam_rec *)id, ipd);
1768                 osd_ipd_put(env, bag, ipd);
1769                 return(rc > 0 ? 0 : rc);
1770         }
1771
1772         inode = obj->oo_inode;
1773         ll_vfs_dq_init(inode);
1774
1775         rc = osd_quota_transfer(inode, attr);
1776         if (rc)
1777                 return rc;
1778
1779         spin_lock(&obj->oo_guard);
1780         rc = osd_inode_setattr(env, inode, attr);
1781         spin_unlock(&obj->oo_guard);
1782
1783         if (!rc)
1784                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
1785         return rc;
1786 }
1787
1788 struct dentry *osd_child_dentry_get(const struct lu_env *env,
1789                                     struct osd_object *obj,
1790                                     const char *name, const int namelen)
1791 {
1792         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
1793 }
1794
1795 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
1796                       cfs_umode_t mode,
1797                       struct dt_allocation_hint *hint,
1798                       struct thandle *th)
1799 {
1800         int result;
1801         struct osd_device  *osd = osd_obj2dev(obj);
1802         struct osd_thandle *oth;
1803         struct dt_object   *parent = NULL;
1804         struct inode       *inode;
1805
1806         LINVRNT(osd_invariant(obj));
1807         LASSERT(obj->oo_inode == NULL);
1808         LASSERT(obj->oo_hl_head == NULL);
1809
1810         if (S_ISDIR(mode) && ldiskfs_pdo) {
1811                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1812                 if (obj->oo_hl_head == NULL)
1813                         return -ENOMEM;
1814         }
1815
1816         oth = container_of(th, struct osd_thandle, ot_super);
1817         LASSERT(oth->ot_handle->h_transaction != NULL);
1818
1819         if (hint && hint->dah_parent)
1820                 parent = hint->dah_parent;
1821
1822         inode = ldiskfs_create_inode(oth->ot_handle,
1823                                      parent ? osd_dt_obj(parent)->oo_inode :
1824                                               osd_sb(osd)->s_root->d_inode,
1825                                      mode);
1826         if (!IS_ERR(inode)) {
1827                 /* Do not update file c/mtime in ldiskfs.
1828                  * NB: don't need any lock because no contention at this
1829                  * early stage */
1830                 inode->i_flags |= S_NOCMTIME;
1831
1832                 /* For new created object, it must be consistent,
1833                  * and it is unnecessary to scrub against it. */
1834                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
1835                 obj->oo_inode = inode;
1836                 result = 0;
1837         } else {
1838                 if (obj->oo_hl_head != NULL) {
1839                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1840                         obj->oo_hl_head = NULL;
1841                 }
1842                 result = PTR_ERR(inode);
1843         }
1844         LINVRNT(osd_invariant(obj));
1845         return result;
1846 }
1847
1848 enum {
1849         OSD_NAME_LEN = 255
1850 };
1851
1852 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
1853                      struct lu_attr *attr,
1854                      struct dt_allocation_hint *hint,
1855                      struct dt_object_format *dof,
1856                      struct thandle *th)
1857 {
1858         int result;
1859         struct osd_thandle *oth;
1860         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX));
1861
1862         LASSERT(S_ISDIR(attr->la_mode));
1863
1864         oth = container_of(th, struct osd_thandle, ot_super);
1865         LASSERT(oth->ot_handle->h_transaction != NULL);
1866         result = osd_mkfile(info, obj, mode, hint, th);
1867
1868         return result;
1869 }
1870
1871 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
1872                         struct lu_attr *attr,
1873                         struct dt_allocation_hint *hint,
1874                         struct dt_object_format *dof,
1875                         struct thandle *th)
1876 {
1877         int result;
1878         struct osd_thandle *oth;
1879         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
1880
1881         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
1882
1883         LASSERT(S_ISREG(attr->la_mode));
1884
1885         oth = container_of(th, struct osd_thandle, ot_super);
1886         LASSERT(oth->ot_handle->h_transaction != NULL);
1887
1888         result = osd_mkfile(info, obj, mode, hint, th);
1889         if (result == 0) {
1890                 LASSERT(obj->oo_inode != NULL);
1891                 if (feat->dif_flags & DT_IND_VARKEY)
1892                         result = iam_lvar_create(obj->oo_inode,
1893                                                  feat->dif_keysize_max,
1894                                                  feat->dif_ptrsize,
1895                                                  feat->dif_recsize_max,
1896                                                  oth->ot_handle);
1897                 else
1898                         result = iam_lfix_create(obj->oo_inode,
1899                                                  feat->dif_keysize_max,
1900                                                  feat->dif_ptrsize,
1901                                                  feat->dif_recsize_max,
1902                                                  oth->ot_handle);
1903
1904         }
1905         return result;
1906 }
1907
1908 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
1909                      struct lu_attr *attr,
1910                      struct dt_allocation_hint *hint,
1911                      struct dt_object_format *dof,
1912                      struct thandle *th)
1913 {
1914         LASSERT(S_ISREG(attr->la_mode));
1915         return osd_mkfile(info, obj, (attr->la_mode &
1916                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
1917 }
1918
1919 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
1920                      struct lu_attr *attr,
1921                      struct dt_allocation_hint *hint,
1922                      struct dt_object_format *dof,
1923                      struct thandle *th)
1924 {
1925         LASSERT(S_ISLNK(attr->la_mode));
1926         return osd_mkfile(info, obj, (attr->la_mode &
1927                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
1928 }
1929
1930 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
1931                      struct lu_attr *attr,
1932                      struct dt_allocation_hint *hint,
1933                      struct dt_object_format *dof,
1934                      struct thandle *th)
1935 {
1936         cfs_umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
1937         int result;
1938
1939         LINVRNT(osd_invariant(obj));
1940         LASSERT(obj->oo_inode == NULL);
1941         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
1942                 S_ISFIFO(mode) || S_ISSOCK(mode));
1943
1944         result = osd_mkfile(info, obj, mode, hint, th);
1945         if (result == 0) {
1946                 LASSERT(obj->oo_inode != NULL);
1947                 /*
1948                  * This inode should be marked dirty for i_rdev.  Currently
1949                  * that is done in the osd_attr_init().
1950                  */
1951                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
1952                                    attr->la_rdev);
1953         }
1954         LINVRNT(osd_invariant(obj));
1955         return result;
1956 }
1957
1958 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
1959                               struct lu_attr *,
1960                               struct dt_allocation_hint *hint,
1961                               struct dt_object_format *dof,
1962                               struct thandle *);
1963
1964 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
1965 {
1966         osd_obj_type_f result;
1967
1968         switch (type) {
1969         case DFT_DIR:
1970                 result = osd_mkdir;
1971                 break;
1972         case DFT_REGULAR:
1973                 result = osd_mkreg;
1974                 break;
1975         case DFT_SYM:
1976                 result = osd_mksym;
1977                 break;
1978         case DFT_NODE:
1979                 result = osd_mknod;
1980                 break;
1981         case DFT_INDEX:
1982                 result = osd_mk_index;
1983                 break;
1984
1985         default:
1986                 LBUG();
1987                 break;
1988         }
1989         return result;
1990 }
1991
1992
1993 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
1994                         struct dt_object *parent, struct dt_object *child,
1995                         cfs_umode_t child_mode)
1996 {
1997         LASSERT(ah);
1998
1999         memset(ah, 0, sizeof(*ah));
2000         ah->dah_parent = parent;
2001         ah->dah_mode = child_mode;
2002 }
2003
2004 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
2005                           struct lu_attr *attr, struct dt_object_format *dof)
2006 {
2007         struct inode   *inode = obj->oo_inode;
2008         __u64           valid = attr->la_valid;
2009         int             result;
2010
2011         attr->la_valid &= ~(LA_TYPE | LA_MODE);
2012
2013         if (dof->dof_type != DFT_NODE)
2014                 attr->la_valid &= ~LA_RDEV;
2015         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
2016                 attr->la_valid &= ~LA_ATIME;
2017         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
2018                 attr->la_valid &= ~LA_CTIME;
2019         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
2020                 attr->la_valid &= ~LA_MTIME;
2021
2022         result = osd_quota_transfer(inode, attr);
2023         if (result)
2024                 return;
2025
2026         if (attr->la_valid != 0) {
2027                 result = osd_inode_setattr(info->oti_env, inode, attr);
2028                 /*
2029                  * The osd_inode_setattr() should always succeed here.  The
2030                  * only error that could be returned is EDQUOT when we are
2031                  * trying to change the UID or GID of the inode. However, this
2032                  * should not happen since quota enforcement is no longer
2033                  * enabled on ldiskfs (lquota takes care of it).
2034                  */
2035                 LASSERTF(result == 0, "%d", result);
2036                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2037         }
2038
2039         attr->la_valid = valid;
2040 }
2041
2042 /**
2043  * Helper function for osd_object_create()
2044  *
2045  * \retval 0, on success
2046  */
2047 static int __osd_object_create(struct osd_thread_info *info,
2048                                struct osd_object *obj, struct lu_attr *attr,
2049                                struct dt_allocation_hint *hint,
2050                                struct dt_object_format *dof,
2051                                struct thandle *th)
2052 {
2053         int     result;
2054         __u32   umask;
2055
2056         /* we drop umask so that permissions we pass are not affected */
2057         umask = current->fs->umask;
2058         current->fs->umask = 0;
2059
2060         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
2061                                                   th);
2062         if (result == 0) {
2063                 osd_attr_init(info, obj, attr, dof);
2064                 osd_object_init0(obj);
2065                 /* bz 24037 */
2066                 if (obj->oo_inode && (obj->oo_inode->i_state & I_NEW))
2067                         unlock_new_inode(obj->oo_inode);
2068         }
2069
2070         /* restore previous umask value */
2071         current->fs->umask = umask;
2072
2073         return result;
2074 }
2075
2076 /**
2077  * Helper function for osd_object_create()
2078  *
2079  * \retval 0, on success
2080  */
2081 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
2082                            const struct lu_fid *fid, struct thandle *th)
2083 {
2084         struct osd_thread_info *info = osd_oti_get(env);
2085         struct osd_inode_id    *id   = &info->oti_id;
2086         struct osd_device      *osd  = osd_obj2dev(obj);
2087
2088         LASSERT(obj->oo_inode != NULL);
2089
2090         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
2091         return osd_oi_insert(info, osd, fid, id, th);
2092 }
2093
2094 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
2095                    const struct lu_fid *fid, struct lu_seq_range *range)
2096 {
2097         struct seq_server_site  *ss = osd_seq_site(osd);
2098         int                     rc;
2099
2100         if (fid_is_idif(fid)) {
2101                 fld_range_set_ost(range);
2102                 range->lsr_index = fid_idif_ost_idx(fid);
2103                 return 0;
2104         }
2105
2106         if (!fid_seq_in_fldb(fid_seq(fid))) {
2107                 fld_range_set_mdt(range);
2108                 if (ss != NULL)
2109                         /* FIXME: If ss is NULL, it suppose not get lsr_index
2110                          * at all */
2111                         range->lsr_index = ss->ss_node_id;
2112                 return 0;
2113         }
2114
2115         LASSERT(ss != NULL);
2116         fld_range_set_any(range);
2117         rc = fld_server_lookup(env, ss->ss_server_fld, fid_seq(fid), range);
2118         if (rc != 0) {
2119                 CERROR("%s: cannot find FLD range for "DFID": rc = %d\n",
2120                        osd_name(osd), PFID(fid), rc);
2121         }
2122         return rc;
2123 }
2124
2125 /*
2126  * Concurrency: no external locking is necessary.
2127  */
2128 static int osd_declare_object_create(const struct lu_env *env,
2129                                      struct dt_object *dt,
2130                                      struct lu_attr *attr,
2131                                      struct dt_allocation_hint *hint,
2132                                      struct dt_object_format *dof,
2133                                      struct thandle *handle)
2134 {
2135         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
2136         struct osd_thandle      *oh;
2137         int                      rc;
2138         ENTRY;
2139
2140         LASSERT(handle != NULL);
2141
2142         oh = container_of0(handle, struct osd_thandle, ot_super);
2143         LASSERT(oh->ot_handle == NULL);
2144
2145         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
2146                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
2147         if (!fid_is_on_ost(osd_oti_get(env), osd_dt_dev(handle->th_dev),
2148                            lu_object_fid(&dt->do_lu)))
2149                 /* Reuse idle OI block may cause additional one OI block
2150                  * to be changed. */
2151                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2152                                 osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
2153
2154         /* If this is directory, then we expect . and .. to be inserted as
2155          * well. The one directory block always needs to be created for the
2156          * directory, so we could use DTO_WRITE_BASE here (GDT, block bitmap,
2157          * block), there is no danger of needing a tree for the first block.
2158          */
2159         if (attr && S_ISDIR(attr->la_mode)) {
2160                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2161                                      osd_dto_credits_noquota[DTO_WRITE_BASE]);
2162                 osd_trans_declare_op(env, oh, OSD_OT_INSERT, 0);
2163         }
2164
2165         if (!attr)
2166                 RETURN(0);
2167
2168         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid, 1, oh,
2169                                    false, false, NULL, false);
2170         if (rc != 0)
2171                 RETURN(rc);
2172
2173         /* It does fld look up inside declare, and the result will be
2174          * added to fld cache, so the following fld lookup inside insert
2175          * does not need send RPC anymore, so avoid send rpc with holding
2176          * transaction */
2177         if (fid_is_norm(lu_object_fid(&dt->do_lu)) &&
2178                 !fid_is_last_id(lu_object_fid(&dt->do_lu)))
2179                 osd_fld_lookup(env, osd_dt_dev(handle->th_dev),
2180                                lu_object_fid(&dt->do_lu), range);
2181
2182
2183         RETURN(rc);
2184 }
2185
2186 static int osd_object_create(const struct lu_env *env, struct dt_object *dt,
2187                              struct lu_attr *attr,
2188                              struct dt_allocation_hint *hint,
2189                              struct dt_object_format *dof,
2190                              struct thandle *th)
2191 {
2192         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2193         struct osd_object      *obj    = osd_dt_obj(dt);
2194         struct osd_thread_info *info   = osd_oti_get(env);
2195         int result;
2196
2197         ENTRY;
2198
2199         LINVRNT(osd_invariant(obj));
2200         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2201         LASSERT(osd_write_locked(env, obj));
2202         LASSERT(th != NULL);
2203
2204         if (unlikely(fid_is_acct(fid)))
2205                 /* Quota files can't be created from the kernel any more,
2206                  * 'tune2fs -O quota' will take care of creating them */
2207                 RETURN(-EPERM);
2208
2209         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2210         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2211
2212         result = __osd_object_create(info, obj, attr, hint, dof, th);
2213         if (result == 0)
2214                 result = __osd_oi_insert(env, obj, fid, th);
2215
2216         LASSERT(ergo(result == 0,
2217                      dt_object_exists(dt) && !dt_object_remote(dt)));
2218
2219         LASSERT(osd_invariant(obj));
2220         RETURN(result);
2221 }
2222
2223 /**
2224  * Called to destroy on-disk representation of the object
2225  *
2226  * Concurrency: must be locked
2227  */
2228 static int osd_declare_object_destroy(const struct lu_env *env,
2229                                       struct dt_object *dt,
2230                                       struct thandle *th)
2231 {
2232         struct osd_object  *obj = osd_dt_obj(dt);
2233         struct inode       *inode = obj->oo_inode;
2234         struct osd_thandle *oh;
2235         int                 rc;
2236         ENTRY;
2237
2238         oh = container_of0(th, struct osd_thandle, ot_super);
2239         LASSERT(oh->ot_handle == NULL);
2240         LASSERT(inode);
2241
2242         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
2243                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
2244         /* Recycle idle OI leaf may cause additional three OI blocks
2245          * to be changed. */
2246         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
2247                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
2248         /* one less inode */
2249         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, -1, oh,
2250                                    false, true, NULL, false);
2251         if (rc)
2252                 RETURN(rc);
2253         /* data to be truncated */
2254         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
2255                                    true, true, NULL, false);
2256         RETURN(rc);
2257 }
2258
2259 static int osd_object_destroy(const struct lu_env *env,
2260                               struct dt_object *dt,
2261                               struct thandle *th)
2262 {
2263         const struct lu_fid    *fid = lu_object_fid(&dt->do_lu);
2264         struct osd_object      *obj = osd_dt_obj(dt);
2265         struct inode           *inode = obj->oo_inode;
2266         struct osd_device      *osd = osd_obj2dev(obj);
2267         struct osd_thandle     *oh;
2268         int                     result;
2269         ENTRY;
2270
2271         oh = container_of0(th, struct osd_thandle, ot_super);
2272         LASSERT(oh->ot_handle);
2273         LASSERT(inode);
2274         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
2275
2276         if (unlikely(fid_is_acct(fid)))
2277                 RETURN(-EPERM);
2278
2279         if (S_ISDIR(inode->i_mode)) {
2280                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1);
2281                 /* it will check/delete the inode from remote parent,
2282                  * how to optimize it? unlink performance impaction XXX */
2283                 result = osd_delete_from_remote_parent(env, osd, obj, oh);
2284                 if (result != 0 && result != -ENOENT) {
2285                         CERROR("%s: delete inode "DFID": rc = %d\n",
2286                                osd_name(osd), PFID(fid), result);
2287                 }
2288                 spin_lock(&obj->oo_guard);
2289                 clear_nlink(inode);
2290                 spin_unlock(&obj->oo_guard);
2291                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2292         }
2293
2294         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
2295
2296         result = osd_oi_delete(osd_oti_get(env), osd, fid, th);
2297
2298         /* XXX: add to ext3 orphan list */
2299         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
2300
2301         /* not needed in the cache anymore */
2302         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
2303
2304         RETURN(0);
2305 }
2306
2307 /**
2308  * Put the fid into lustre_mdt_attrs, and then place the structure
2309  * inode's ea. This fid should not be altered during the life time
2310  * of the inode.
2311  *
2312  * \retval +ve, on success
2313  * \retval -ve, on error
2314  *
2315  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
2316  */
2317 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
2318                    const struct lu_fid *fid, __u64 flags)
2319 {
2320         struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
2321         int                      rc;
2322
2323         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
2324                 return 0;
2325
2326         lustre_lma_init(lma, fid, flags);
2327         lustre_lma_swab(lma);
2328
2329         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma, sizeof(*lma),
2330                              XATTR_CREATE);
2331         /* Someone may created the EA by race. */
2332         if (unlikely(rc == -EEXIST))
2333                 rc = 0;
2334         return rc;
2335 }
2336
2337 /**
2338  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
2339  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
2340  * To have compatilibility with 1.8 ldiskfs driver we need to have
2341  * magic number at start of fid data.
2342  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
2343  * its inmemory API.
2344  */
2345 void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
2346                                   const struct dt_rec *fid)
2347 {
2348         if (!fid_is_namespace_visible((const struct lu_fid *)fid) ||
2349             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
2350                 param->edp_magic = 0;
2351                 return;
2352         }
2353
2354         param->edp_magic = LDISKFS_LUFID_MAGIC;
2355         param->edp_len =  sizeof(struct lu_fid) + 1;
2356         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
2357 }
2358
2359 /**
2360  * Try to read the fid from inode ea into dt_rec.
2361  *
2362  * \param fid object fid.
2363  *
2364  * \retval 0 on success
2365  */
2366 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
2367                           __u32 ino, struct lu_fid *fid,
2368                           struct osd_inode_id *id)
2369 {
2370         struct osd_thread_info *info  = osd_oti_get(env);
2371         struct inode           *inode;
2372         ENTRY;
2373
2374         osd_id_gen(id, ino, OSD_OII_NOGEN);
2375         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
2376         if (IS_ERR(inode))
2377                 RETURN(PTR_ERR(inode));
2378
2379         iput(inode);
2380         RETURN(0);
2381 }
2382
2383 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
2384                                         struct inode *dir,
2385                                         struct inode  *parent_dir,
2386                                         const struct dt_rec *dot_fid,
2387                                         const struct dt_rec *dot_dot_fid,
2388                                         struct osd_thandle *oth)
2389 {
2390         struct ldiskfs_dentry_param *dot_ldp;
2391         struct ldiskfs_dentry_param *dot_dot_ldp;
2392
2393         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
2394         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
2395
2396         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
2397         dot_ldp->edp_magic = 0;
2398         return ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
2399                                         dir, dot_ldp, dot_dot_ldp);
2400 }
2401
2402 /**
2403  * Create an local agent inode for remote entry
2404  */
2405 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
2406                                                   struct osd_device *osd,
2407                                                   struct osd_object *pobj,
2408                                                   const struct lu_fid *fid,
2409                                                   struct thandle *th)
2410 {
2411         struct osd_thread_info  *info = osd_oti_get(env);
2412         struct inode            *local;
2413         struct osd_thandle      *oh;
2414         int                     rc;
2415         ENTRY;
2416
2417         LASSERT(th);
2418         oh = container_of(th, struct osd_thandle, ot_super);
2419         LASSERT(oh->ot_handle->h_transaction != NULL);
2420
2421         /* FIXME: Insert index api needs to know the mode of
2422          * the remote object. Just use S_IFDIR for now */
2423         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, S_IFDIR);
2424         if (IS_ERR(local)) {
2425                 CERROR("%s: create local error %d\n", osd_name(osd),
2426                        (int)PTR_ERR(local));
2427                 RETURN(local);
2428         }
2429
2430         /* Set special LMA flag for local agent inode */
2431         rc = osd_ea_fid_set(info, local, fid, LMAI_AGENT);
2432         if (rc != 0) {
2433                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
2434                        osd_name(osd), PFID(fid), rc);
2435                 RETURN(ERR_PTR(rc));
2436         }
2437
2438         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
2439                 (const struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
2440                 (const struct dt_rec *)fid, oh);
2441         if (rc != 0) {
2442                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
2443                         osd_name(osd), PFID(fid), rc);
2444                 RETURN(ERR_PTR(rc));
2445         }
2446
2447         RETURN(local);
2448 }
2449
2450 /**
2451  * Delete local agent inode for remote entry
2452  */
2453 static int osd_delete_local_agent_inode(const struct lu_env *env,
2454                                         struct osd_device *osd,
2455                                         const struct lu_fid *fid,
2456                                         __u32 ino, struct osd_thandle *oh)
2457 {
2458         struct osd_thread_info  *oti = osd_oti_get(env);
2459         struct osd_inode_id     *id = &oti->oti_id;
2460         struct inode            *inode;
2461         ENTRY;
2462
2463         id->oii_ino = le32_to_cpu(ino);
2464         id->oii_gen = OSD_OII_NOGEN;
2465         inode = osd_iget(oti, osd, id);
2466         if (IS_ERR(inode)) {
2467                 CERROR("%s: iget error "DFID" id %u:%u\n", osd_name(osd),
2468                        PFID(fid), id->oii_ino, id->oii_gen);
2469                 RETURN(PTR_ERR(inode));
2470         }
2471
2472         clear_nlink(inode);
2473         mark_inode_dirty(inode);
2474         CDEBUG(D_INODE, "%s: delete remote inode "DFID" %lu\n",
2475                 osd_name(osd), PFID(fid), inode->i_ino);
2476         iput(inode);
2477         RETURN(0);
2478 }
2479
2480 /**
2481  * OSD layer object create function for interoperability mode (b11826).
2482  * This is mostly similar to osd_object_create(). Only difference being, fid is
2483  * inserted into inode ea here.
2484  *
2485  * \retval   0, on success
2486  * \retval -ve, on error
2487  */
2488 static int osd_object_ea_create(const struct lu_env *env, struct dt_object *dt,
2489                                 struct lu_attr *attr,
2490                                 struct dt_allocation_hint *hint,
2491                                 struct dt_object_format *dof,
2492                                 struct thandle *th)
2493 {
2494         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2495         struct osd_object      *obj    = osd_dt_obj(dt);
2496         struct osd_thread_info *info   = osd_oti_get(env);
2497         int                     result;
2498
2499         ENTRY;
2500
2501         LASSERT(osd_invariant(obj));
2502         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2503         LASSERT(osd_write_locked(env, obj));
2504         LASSERT(th != NULL);
2505
2506         if (unlikely(fid_is_acct(fid)))
2507                 /* Quota files can't be created from the kernel any more,
2508                  * 'tune2fs -O quota' will take care of creating them */
2509                 RETURN(-EPERM);
2510
2511         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2512         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2513
2514         result = __osd_object_create(info, obj, attr, hint, dof, th);
2515         if (result == 0)
2516                 result = osd_ea_fid_set(info, obj->oo_inode, fid, 0);
2517
2518         if (result == 0)
2519                 result = __osd_oi_insert(env, obj, fid, th);
2520
2521         LASSERT(ergo(result == 0,
2522                      dt_object_exists(dt) && !dt_object_remote(dt)));
2523         LINVRNT(osd_invariant(obj));
2524         RETURN(result);
2525 }
2526
2527 static int osd_declare_object_ref_add(const struct lu_env *env,
2528                                       struct dt_object *dt,
2529                                       struct thandle *handle)
2530 {
2531         struct osd_thandle       *oh;
2532
2533         /* it's possible that object doesn't exist yet */
2534         LASSERT(handle != NULL);
2535
2536         oh = container_of0(handle, struct osd_thandle, ot_super);
2537         LASSERT(oh->ot_handle == NULL);
2538
2539         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
2540                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2541
2542         return 0;
2543 }
2544
2545 /*
2546  * Concurrency: @dt is write locked.
2547  */
2548 static int osd_object_ref_add(const struct lu_env *env,
2549                               struct dt_object *dt, struct thandle *th)
2550 {
2551         struct osd_object *obj = osd_dt_obj(dt);
2552         struct inode      *inode = obj->oo_inode;
2553         bool               need_dirty = false;
2554         int                rc = 0;
2555
2556         LINVRNT(osd_invariant(obj));
2557         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2558         LASSERT(osd_write_locked(env, obj));
2559         LASSERT(th != NULL);
2560
2561         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
2562
2563         /* This based on ldiskfs_inc_count(), which is not exported.
2564          *
2565          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
2566          * (65000) subdirectories by storing "1" in i_nlink if the link count
2567          * would otherwise overflow. Directory tranversal tools understand
2568          * that (st_nlink == 1) indicates that the filesystem dose not track
2569          * hard links count on the directory, and will not abort subdirectory
2570          * scanning early once (st_nlink - 2) subdirs have been found.
2571          *
2572          * This also has to properly handle the case of inodes with nlink == 0
2573          * in case they are being linked into the PENDING directory
2574          */
2575         spin_lock(&obj->oo_guard);
2576         if (unlikely(!S_ISDIR(inode->i_mode) &&
2577                      inode->i_nlink >= LDISKFS_LINK_MAX)) {
2578                 /* MDD should have checked this, but good to be safe */
2579                 rc = -EMLINK;
2580         } else if (unlikely(inode->i_nlink == 0 ||
2581                             (S_ISDIR(inode->i_mode) &&
2582                              inode->i_nlink >= LDISKFS_LINK_MAX))) {
2583                 /* inc_nlink from 0 may cause WARN_ON */
2584                 set_nlink(inode, 1);
2585                 need_dirty = true;
2586         } else if (!S_ISDIR(inode->i_mode) ||
2587                    (S_ISDIR(inode->i_mode) && inode->i_nlink >= 2)) {
2588                 inc_nlink(inode);
2589                 need_dirty = true;
2590         } /* else (S_ISDIR(inode->i_mode) && inode->i_nlink == 1) { ; } */
2591
2592         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
2593         spin_unlock(&obj->oo_guard);
2594
2595         if (need_dirty)
2596                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2597
2598         LINVRNT(osd_invariant(obj));
2599
2600         return rc;
2601 }
2602
2603 static int osd_declare_object_ref_del(const struct lu_env *env,
2604                                       struct dt_object *dt,
2605                                       struct thandle *handle)
2606 {
2607         struct osd_thandle *oh;
2608
2609         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2610         LASSERT(handle != NULL);
2611
2612         oh = container_of0(handle, struct osd_thandle, ot_super);
2613         LASSERT(oh->ot_handle == NULL);
2614
2615         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
2616                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2617
2618         return 0;
2619 }
2620
2621 /*
2622  * Concurrency: @dt is write locked.
2623  */
2624 static int osd_object_ref_del(const struct lu_env *env, struct dt_object *dt,
2625                               struct thandle *th)
2626 {
2627         struct osd_object *obj = osd_dt_obj(dt);
2628         struct inode      *inode = obj->oo_inode;
2629
2630         LINVRNT(osd_invariant(obj));
2631         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2632         LASSERT(osd_write_locked(env, obj));
2633         LASSERT(th != NULL);
2634
2635         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
2636
2637         spin_lock(&obj->oo_guard);
2638         LASSERT(inode->i_nlink > 0);
2639
2640         /* This based on ldiskfs_dec_count(), which is not exported.
2641          *
2642          * If a directory already has nlink == 1, then do not drop the nlink
2643          * count to 0, even temporarily, to avoid race conditions with other
2644          * threads not holding oo_guard seeing i_nlink == 0 in rare cases.
2645          *
2646          * nlink == 1 means the directory has/had > EXT4_LINK_MAX subdirs.
2647          * */
2648         if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 1) {
2649                 drop_nlink(inode);
2650
2651                 spin_unlock(&obj->oo_guard);
2652                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2653                 LINVRNT(osd_invariant(obj));
2654         } else {
2655                 spin_unlock(&obj->oo_guard);
2656         }
2657
2658         return 0;
2659 }
2660
2661 /*
2662  * Get the 64-bit version for an inode.
2663  */
2664 static int osd_object_version_get(const struct lu_env *env,
2665                                   struct dt_object *dt, dt_obj_version_t *ver)
2666 {
2667         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2668
2669         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
2670                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2671         *ver = LDISKFS_I(inode)->i_fs_version;
2672         return 0;
2673 }
2674
2675 /*
2676  * Concurrency: @dt is read locked.
2677  */
2678 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
2679                          struct lu_buf *buf, const char *name,
2680                          struct lustre_capa *capa)
2681 {
2682         struct osd_object      *obj    = osd_dt_obj(dt);
2683         struct inode           *inode  = obj->oo_inode;
2684         struct osd_thread_info *info   = osd_oti_get(env);
2685         struct dentry          *dentry = &info->oti_obj_dentry;
2686
2687         /* version get is not real XATTR but uses xattr API */
2688         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2689                 /* for version we are just using xattr API but change inode
2690                  * field instead */
2691                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2692                 osd_object_version_get(env, dt, buf->lb_buf);
2693                 return sizeof(dt_obj_version_t);
2694         }
2695
2696         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2697         LASSERT(inode->i_op != NULL && inode->i_op->getxattr != NULL);
2698
2699         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2700                 return -EACCES;
2701
2702         return __osd_xattr_get(inode, dentry, name, buf->lb_buf, buf->lb_len);
2703 }
2704
2705
2706 static int osd_declare_xattr_set(const struct lu_env *env,
2707                                  struct dt_object *dt,
2708                                  const struct lu_buf *buf, const char *name,
2709                                  int fl, struct thandle *handle)
2710 {
2711         struct osd_thandle *oh;
2712
2713         LASSERT(handle != NULL);
2714
2715         oh = container_of0(handle, struct osd_thandle, ot_super);
2716         LASSERT(oh->ot_handle == NULL);
2717
2718         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2719                              strcmp(name, XATTR_NAME_VERSION) == 0 ?
2720                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] :
2721                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2722
2723         return 0;
2724 }
2725
2726 /*
2727  * Set the 64-bit version for object
2728  */
2729 static void osd_object_version_set(const struct lu_env *env,
2730                                    struct dt_object *dt,
2731                                    dt_obj_version_t *new_version)
2732 {
2733         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2734
2735         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
2736                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2737
2738         LDISKFS_I(inode)->i_fs_version = *new_version;
2739         /** Version is set after all inode operations are finished,
2740          *  so we should mark it dirty here */
2741         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2742 }
2743
2744 /*
2745  * Concurrency: @dt is write locked.
2746  */
2747 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
2748                          const struct lu_buf *buf, const char *name, int fl,
2749                          struct thandle *handle, struct lustre_capa *capa)
2750 {
2751         struct osd_object      *obj      = osd_dt_obj(dt);
2752         struct inode           *inode    = obj->oo_inode;
2753         struct osd_thread_info *info     = osd_oti_get(env);
2754         int                     fs_flags = 0;
2755         ENTRY;
2756
2757         LASSERT(handle != NULL);
2758
2759         /* version set is not real XATTR */
2760         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2761                 /* for version we are just using xattr API but change inode
2762                  * field instead */
2763                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2764                 osd_object_version_set(env, dt, buf->lb_buf);
2765                 return sizeof(dt_obj_version_t);
2766         }
2767
2768         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2769                 return -EACCES;
2770
2771         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2772         if (fl & LU_XATTR_REPLACE)
2773                 fs_flags |= XATTR_REPLACE;
2774
2775         if (fl & LU_XATTR_CREATE)
2776                 fs_flags |= XATTR_CREATE;
2777
2778         return __osd_xattr_set(info, inode, name, buf->lb_buf, buf->lb_len,
2779                                fs_flags);
2780 }
2781
2782 /*
2783  * Concurrency: @dt is read locked.
2784  */
2785 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
2786                           struct lu_buf *buf, struct lustre_capa *capa)
2787 {
2788         struct osd_object      *obj    = osd_dt_obj(dt);
2789         struct inode           *inode  = obj->oo_inode;
2790         struct osd_thread_info *info   = osd_oti_get(env);
2791         struct dentry          *dentry = &info->oti_obj_dentry;
2792
2793         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2794         LASSERT(inode->i_op != NULL && inode->i_op->listxattr != NULL);
2795         LASSERT(osd_read_locked(env, obj) || osd_write_locked(env, obj));
2796
2797         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2798                 return -EACCES;
2799
2800         dentry->d_inode = inode;
2801         dentry->d_sb = inode->i_sb;
2802         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
2803 }
2804
2805 static int osd_declare_xattr_del(const struct lu_env *env,
2806                                  struct dt_object *dt, const char *name,
2807                                  struct thandle *handle)
2808 {
2809         struct osd_thandle *oh;
2810
2811         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2812         LASSERT(handle != NULL);
2813
2814         oh = container_of0(handle, struct osd_thandle, ot_super);
2815         LASSERT(oh->ot_handle == NULL);
2816
2817         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2818                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2819
2820         return 0;
2821 }
2822
2823 /*
2824  * Concurrency: @dt is write locked.
2825  */
2826 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
2827                          const char *name, struct thandle *handle,
2828                          struct lustre_capa *capa)
2829 {
2830         struct osd_object      *obj    = osd_dt_obj(dt);
2831         struct inode           *inode  = obj->oo_inode;
2832         struct osd_thread_info *info   = osd_oti_get(env);
2833         struct dentry          *dentry = &info->oti_obj_dentry;
2834         int                     rc;
2835
2836         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2837         LASSERT(inode->i_op != NULL && inode->i_op->removexattr != NULL);
2838         LASSERT(handle != NULL);
2839
2840         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2841                 return -EACCES;
2842
2843         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2844
2845         ll_vfs_dq_init(inode);
2846         dentry->d_inode = inode;
2847         dentry->d_sb = inode->i_sb;
2848         rc = inode->i_op->removexattr(dentry, name);
2849         return rc;
2850 }
2851
2852 static struct obd_capa *osd_capa_get(const struct lu_env *env,
2853                                      struct dt_object *dt,
2854                                      struct lustre_capa *old,
2855                                      __u64 opc)
2856 {
2857         struct osd_thread_info *info = osd_oti_get(env);
2858         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
2859         struct osd_object *obj = osd_dt_obj(dt);
2860         struct osd_device *dev = osd_obj2dev(obj);
2861         struct lustre_capa_key *key = &info->oti_capa_key;
2862         struct lustre_capa *capa = &info->oti_capa;
2863         struct obd_capa *oc;
2864         struct md_capainfo *ci;
2865         int rc;
2866         ENTRY;
2867
2868         if (!dev->od_fl_capa)
2869                 RETURN(ERR_PTR(-ENOENT));
2870
2871         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2872         LINVRNT(osd_invariant(obj));
2873
2874         /* renewal sanity check */
2875         if (old && osd_object_auth(env, dt, old, opc))
2876                 RETURN(ERR_PTR(-EACCES));
2877
2878         ci = md_capainfo(env);
2879         if (unlikely(!ci))
2880                 RETURN(ERR_PTR(-ENOENT));
2881
2882         switch (ci->mc_auth) {
2883         case LC_ID_NONE:
2884                 RETURN(NULL);
2885         case LC_ID_PLAIN:
2886                 capa->lc_uid = obj->oo_inode->i_uid;
2887                 capa->lc_gid = obj->oo_inode->i_gid;
2888                 capa->lc_flags = LC_ID_PLAIN;
2889                 break;
2890         case LC_ID_CONVERT: {
2891                 __u32 d[4], s[4];
2892
2893                 s[0] = obj->oo_inode->i_uid;
2894                 cfs_get_random_bytes(&(s[1]), sizeof(__u32));
2895                 s[2] = obj->oo_inode->i_gid;
2896                 cfs_get_random_bytes(&(s[3]), sizeof(__u32));
2897                 rc = capa_encrypt_id(d, s, key->lk_key, CAPA_HMAC_KEY_MAX_LEN);
2898                 if (unlikely(rc))
2899                         RETURN(ERR_PTR(rc));
2900
2901                 capa->lc_uid   = ((__u64)d[1] << 32) | d[0];
2902                 capa->lc_gid   = ((__u64)d[3] << 32) | d[2];
2903                 capa->lc_flags = LC_ID_CONVERT;
2904                 break;
2905         }
2906         default:
2907                 RETURN(ERR_PTR(-EINVAL));
2908         }
2909
2910         capa->lc_fid = *fid;
2911         capa->lc_opc = opc;
2912         capa->lc_flags |= dev->od_capa_alg << 24;
2913         capa->lc_timeout = dev->od_capa_timeout;
2914         capa->lc_expiry = 0;
2915
2916         oc = capa_lookup(dev->od_capa_hash, capa, 1);
2917         if (oc) {
2918                 LASSERT(!capa_is_expired(oc));
2919                 RETURN(oc);
2920         }
2921
2922         spin_lock(&capa_lock);
2923         *key = dev->od_capa_keys[1];
2924         spin_unlock(&capa_lock);
2925
2926         capa->lc_keyid = key->lk_keyid;
2927         capa->lc_expiry = cfs_time_current_sec() + dev->od_capa_timeout;
2928
2929         rc = capa_hmac(capa->lc_hmac, capa, key->lk_key);
2930         if (rc) {
2931                 DEBUG_CAPA(D_ERROR, capa, "HMAC failed: %d for", rc);
2932                 RETURN(ERR_PTR(rc));
2933         }
2934
2935         oc = capa_add(dev->od_capa_hash, capa);
2936         RETURN(oc);
2937 }
2938
2939 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt)
2940 {
2941         struct osd_object       *obj    = osd_dt_obj(dt);
2942         struct inode            *inode  = obj->oo_inode;
2943         struct osd_thread_info  *info   = osd_oti_get(env);
2944         struct dentry           *dentry = &info->oti_obj_dentry;
2945         struct file             *file   = &info->oti_file;
2946         int                     rc;
2947
2948         ENTRY;
2949
2950         dentry->d_inode = inode;
2951         dentry->d_sb = inode->i_sb;
2952         file->f_dentry = dentry;
2953         file->f_mapping = inode->i_mapping;
2954         file->f_op = inode->i_fop;
2955 #ifndef HAVE_FILE_FSYNC_4ARGS
2956         mutex_lock(&inode->i_mutex);
2957 #endif
2958         rc = do_fsync(file, 0);
2959 #ifndef HAVE_FILE_FSYNC_4ARGS
2960         mutex_unlock(&inode->i_mutex);
2961 #endif
2962         RETURN(rc);
2963 }
2964
2965 static int osd_data_get(const struct lu_env *env, struct dt_object *dt,
2966                         void **data)
2967 {
2968         struct osd_object *obj = osd_dt_obj(dt);
2969         ENTRY;
2970
2971         *data = (void *)obj->oo_inode;
2972         RETURN(0);
2973 }
2974
2975 /*
2976  * Index operations.
2977  */
2978
2979 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
2980                            const struct dt_index_features *feat)
2981 {
2982         struct iam_descr *descr;
2983
2984         if (osd_object_is_root(o))
2985                 return feat == &dt_directory_features;
2986
2987         LASSERT(o->oo_dir != NULL);
2988
2989         descr = o->oo_dir->od_container.ic_descr;
2990         if (feat == &dt_directory_features) {
2991                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
2992                         return 1;
2993                 else
2994                         return 0;
2995         } else {
2996                 return
2997                         feat->dif_keysize_min <= descr->id_key_size &&
2998                         descr->id_key_size <= feat->dif_keysize_max &&
2999                         feat->dif_recsize_min <= descr->id_rec_size &&
3000                         descr->id_rec_size <= feat->dif_recsize_max &&
3001                         !(feat->dif_flags & (DT_IND_VARKEY |
3002                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
3003                         ergo(feat->dif_flags & DT_IND_UPDATE,
3004                              1 /* XXX check that object (and file system) is
3005                                 * writable */);
3006         }
3007 }
3008
3009 static int osd_iam_container_init(const struct lu_env *env,
3010                                   struct osd_object *obj,
3011                                   struct osd_directory *dir)
3012 {
3013         struct iam_container *bag = &dir->od_container;
3014         int result;
3015
3016         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
3017         if (result != 0)
3018                 return result;
3019
3020         result = iam_container_setup(bag);
3021         if (result == 0)
3022                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
3023         else
3024                 iam_container_fini(bag);
3025
3026         return result;
3027 }
3028
3029
3030 /*
3031  * Concurrency: no external locking is necessary.
3032  */
3033 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
3034                          const struct dt_index_features *feat)
3035 {
3036         int                      result;
3037         int                      skip_iam = 0;
3038         struct osd_object       *obj = osd_dt_obj(dt);
3039
3040         LINVRNT(osd_invariant(obj));
3041
3042         if (osd_object_is_root(obj)) {
3043                 dt->do_index_ops = &osd_index_ea_ops;
3044                 result = 0;
3045         } else if (feat == &dt_directory_features) {
3046                 dt->do_index_ops = &osd_index_ea_ops;
3047                 if (obj->oo_inode != NULL && S_ISDIR(obj->oo_inode->i_mode))
3048                         result = 0;
3049                 else
3050                         result = -ENOTDIR;
3051                 skip_iam = 1;
3052         } else if (unlikely(feat == &dt_otable_features)) {
3053                 dt->do_index_ops = &osd_otable_ops;
3054                 return 0;
3055         } else if (unlikely(feat == &dt_acct_features)) {
3056                 dt->do_index_ops = &osd_acct_index_ops;
3057                 result = 0;
3058                 skip_iam = 1;
3059         } else if (!osd_has_index(obj)) {
3060                 struct osd_directory *dir;
3061
3062                 OBD_ALLOC_PTR(dir);
3063                 if (dir != NULL) {
3064
3065                         spin_lock(&obj->oo_guard);
3066                         if (obj->oo_dir == NULL)
3067                                 obj->oo_dir = dir;
3068                         else
3069                                 /*
3070                                  * Concurrent thread allocated container data.
3071                                  */
3072                                 OBD_FREE_PTR(dir);
3073                         spin_unlock(&obj->oo_guard);
3074                         /*
3075                          * Now, that we have container data, serialize its
3076                          * initialization.
3077                          */
3078                         down_write(&obj->oo_ext_idx_sem);
3079                         /*
3080                          * recheck under lock.
3081                          */
3082                         if (!osd_has_index(obj))
3083                                 result = osd_iam_container_init(env, obj, dir);
3084                         else
3085                                 result = 0;
3086                         up_write(&obj->oo_ext_idx_sem);
3087                 } else {
3088                         result = -ENOMEM;
3089                 }
3090         } else {
3091                 result = 0;
3092         }
3093
3094         if (result == 0 && skip_iam == 0) {
3095                 if (!osd_iam_index_probe(env, obj, feat))
3096                         result = -ENOTDIR;
3097         }
3098         LINVRNT(osd_invariant(obj));
3099
3100         if (result == 0 && is_quota_glb_feat(feat) &&
3101             fid_seq(lu_object_fid(&dt->do_lu)) == FID_SEQ_QUOTA_GLB)
3102                 result = osd_quota_migration(env, dt, feat);
3103
3104         return result;
3105 }
3106
3107 static int osd_otable_it_attr_get(const struct lu_env *env,
3108                                  struct dt_object *dt,
3109                                  struct lu_attr *attr,
3110                                  struct lustre_capa *capa)
3111 {
3112         attr->la_valid = 0;
3113         return 0;
3114 }
3115
3116 static const struct dt_object_operations osd_obj_ops = {
3117         .do_read_lock         = osd_object_read_lock,
3118         .do_write_lock        = osd_object_write_lock,
3119         .do_read_unlock       = osd_object_read_unlock,
3120         .do_write_unlock      = osd_object_write_unlock,
3121         .do_write_locked      = osd_object_write_locked,
3122         .do_attr_get          = osd_attr_get,
3123         .do_declare_attr_set  = osd_declare_attr_set,
3124         .do_attr_set          = osd_attr_set,
3125         .do_ah_init           = osd_ah_init,
3126         .do_declare_create    = osd_declare_object_create,
3127         .do_create            = osd_object_create,
3128         .do_declare_destroy   = osd_declare_object_destroy,
3129         .do_destroy           = osd_object_destroy,
3130         .do_index_try         = osd_index_try,
3131         .do_declare_ref_add   = osd_declare_object_ref_add,
3132         .do_ref_add           = osd_object_ref_add,
3133         .do_declare_ref_del   = osd_declare_object_ref_del,
3134         .do_ref_del           = osd_object_ref_del,
3135         .do_xattr_get         = osd_xattr_get,
3136         .do_declare_xattr_set = osd_declare_xattr_set,
3137         .do_xattr_set         = osd_xattr_set,
3138         .do_declare_xattr_del = osd_declare_xattr_del,
3139         .do_xattr_del         = osd_xattr_del,
3140         .do_xattr_list        = osd_xattr_list,
3141         .do_capa_get          = osd_capa_get,
3142         .do_object_sync       = osd_object_sync,
3143         .do_data_get          = osd_data_get,
3144 };
3145
3146 /**
3147  * dt_object_operations for interoperability mode
3148  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
3149  */
3150 static const struct dt_object_operations osd_obj_ea_ops = {
3151         .do_read_lock         = osd_object_read_lock,
3152         .do_write_lock        = osd_object_write_lock,
3153         .do_read_unlock       = osd_object_read_unlock,
3154         .do_write_unlock      = osd_object_write_unlock,
3155         .do_write_locked      = osd_object_write_locked,
3156         .do_attr_get          = osd_attr_get,
3157         .do_declare_attr_set  = osd_declare_attr_set,
3158         .do_attr_set          = osd_attr_set,
3159         .do_ah_init           = osd_ah_init,
3160         .do_declare_create    = osd_declare_object_create,
3161         .do_create            = osd_object_ea_create,
3162         .do_declare_destroy   = osd_declare_object_destroy,
3163         .do_destroy           = osd_object_destroy,
3164         .do_index_try         = osd_index_try,
3165         .do_declare_ref_add   = osd_declare_object_ref_add,
3166         .do_ref_add           = osd_object_ref_add,
3167         .do_declare_ref_del   = osd_declare_object_ref_del,
3168         .do_ref_del           = osd_object_ref_del,
3169         .do_xattr_get         = osd_xattr_get,
3170         .do_declare_xattr_set = osd_declare_xattr_set,
3171         .do_xattr_set         = osd_xattr_set,
3172         .do_declare_xattr_del = osd_declare_xattr_del,
3173         .do_xattr_del         = osd_xattr_del,
3174         .do_xattr_list        = osd_xattr_list,
3175         .do_capa_get          = osd_capa_get,
3176         .do_object_sync       = osd_object_sync,
3177         .do_data_get          = osd_data_get,
3178 };
3179
3180 static const struct dt_object_operations osd_obj_otable_it_ops = {
3181         .do_attr_get    = osd_otable_it_attr_get,
3182         .do_index_try   = osd_index_try,
3183 };
3184
3185 static int osd_index_declare_iam_delete(const struct lu_env *env,
3186                                         struct dt_object *dt,
3187                                         const struct dt_key *key,
3188                                         struct thandle *handle)
3189 {
3190         struct osd_thandle    *oh;
3191
3192         oh = container_of0(handle, struct osd_thandle, ot_super);
3193         LASSERT(oh->ot_handle == NULL);
3194
3195         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3196                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3197
3198         return 0;
3199 }
3200
3201 /**
3202  *      delete a (key, value) pair from index \a dt specified by \a key
3203  *
3204  *      \param  dt      osd index object
3205  *      \param  key     key for index
3206  *      \param  rec     record reference
3207  *      \param  handle  transaction handler
3208  *
3209  *      \retval  0  success
3210  *      \retval -ve   failure
3211  */
3212
3213 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
3214                                 const struct dt_key *key,
3215                                 struct thandle *handle,
3216                                 struct lustre_capa *capa)
3217 {
3218         struct osd_thread_info *oti = osd_oti_get(env);
3219         struct osd_object      *obj = osd_dt_obj(dt);
3220         struct osd_thandle     *oh;
3221         struct iam_path_descr  *ipd;
3222         struct iam_container   *bag = &obj->oo_dir->od_container;
3223         int                     rc;
3224
3225         ENTRY;
3226
3227         LINVRNT(osd_invariant(obj));
3228         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3229         LASSERT(bag->ic_object == obj->oo_inode);
3230         LASSERT(handle != NULL);
3231
3232         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3233                 RETURN(-EACCES);
3234
3235         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3236
3237         ipd = osd_idx_ipd_get(env, bag);
3238         if (unlikely(ipd == NULL))
3239                 RETURN(-ENOMEM);
3240
3241         oh = container_of0(handle, struct osd_thandle, ot_super);
3242         LASSERT(oh->ot_handle != NULL);
3243         LASSERT(oh->ot_handle->h_transaction != NULL);
3244
3245         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3246                 /* swab quota uid/gid provided by caller */
3247                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3248                 key = (const struct dt_key *)&oti->oti_quota_id;
3249         }
3250
3251         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
3252         osd_ipd_put(env, bag, ipd);
3253         LINVRNT(osd_invariant(obj));
3254         RETURN(rc);
3255 }
3256
3257 static int osd_index_declare_ea_delete(const struct lu_env *env,
3258                                        struct dt_object *dt,
3259                                        const struct dt_key *key,
3260                                        struct thandle *handle)
3261 {
3262         struct osd_thandle *oh;
3263         struct inode       *inode;
3264         int                 rc;
3265         ENTRY;
3266
3267         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3268         LASSERT(handle != NULL);
3269
3270         oh = container_of0(handle, struct osd_thandle, ot_super);
3271         LASSERT(oh->ot_handle == NULL);
3272
3273         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3274                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3275
3276         inode = osd_dt_obj(dt)->oo_inode;
3277         LASSERT(inode);
3278
3279         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
3280                                    true, true, NULL, false);
3281         RETURN(rc);
3282 }
3283
3284 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3285                                           struct dt_rec *fid)
3286 {
3287         struct osd_fid_pack *rec;
3288         int                  rc = -ENODATA;
3289
3290         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3291                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3292                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3293         }
3294         return rc;
3295 }
3296
3297 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
3298                           struct lu_fid *fid)
3299 {
3300         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
3301         struct seq_server_site  *ss = osd_seq_site(osd);
3302         int                     rc;
3303         ENTRY;
3304
3305         /* Those FID seqs, which are not in FLDB, must be local seq */
3306         if (unlikely(!fid_seq_in_fldb(fid_seq(fid)) || ss == NULL))
3307                 RETURN(0);
3308
3309         rc = osd_fld_lookup(env, osd, fid, range);
3310         if (rc != 0) {
3311                 CERROR("%s: Can not lookup fld for "DFID"\n",
3312                        osd_name(osd), PFID(fid));
3313                 RETURN(rc);
3314         }
3315
3316         RETURN(ss->ss_node_id != range->lsr_index);
3317 }
3318
3319 /**
3320  * Index delete function for interoperability mode (b11826).
3321  * It will remove the directory entry added by osd_index_ea_insert().
3322  * This entry is needed to maintain name->fid mapping.
3323  *
3324  * \param key,  key i.e. file entry to be deleted
3325  *
3326  * \retval   0, on success
3327  * \retval -ve, on error
3328  */
3329 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3330                                const struct dt_key *key,
3331                                struct thandle *handle,
3332                                struct lustre_capa *capa)
3333 {
3334         struct osd_object          *obj    = osd_dt_obj(dt);
3335         struct inode               *dir    = obj->oo_inode;
3336         struct dentry              *dentry;
3337         struct osd_thandle         *oh;
3338         struct ldiskfs_dir_entry_2 *de = NULL;
3339         struct buffer_head         *bh;
3340         struct htree_lock          *hlock = NULL;
3341         struct lu_fid              *fid = &osd_oti_get(env)->oti_fid;
3342         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
3343         int                        rc;
3344         ENTRY;
3345
3346         LINVRNT(osd_invariant(obj));
3347         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3348         LASSERT(handle != NULL);
3349
3350         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3351
3352         oh = container_of(handle, struct osd_thandle, ot_super);
3353         LASSERT(oh->ot_handle != NULL);
3354         LASSERT(oh->ot_handle->h_transaction != NULL);
3355
3356         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3357                 RETURN(-EACCES);
3358
3359         ll_vfs_dq_init(dir);
3360         dentry = osd_child_dentry_get(env, obj,
3361                                       (char *)key, strlen((char *)key));
3362
3363         if (obj->oo_hl_head != NULL) {
3364                 hlock = osd_oti_get(env)->oti_hlock;
3365                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3366                                    dir, LDISKFS_HLOCK_DEL);
3367         } else {
3368                 down_write(&obj->oo_ext_idx_sem);
3369         }
3370
3371         bh = ldiskfs_find_entry(dir, &dentry->d_name, &de, hlock);
3372         if (bh) {
3373                 __u32 ino = 0;
3374
3375                 /* If this is not the ".." entry, it might be a remote DNE
3376                  * entry and  we need to check if the FID is for a remote
3377                  * MDT.  If the FID is  not in the directory entry (e.g.
3378                  * upgraded 1.8 filesystem without dirdata enabled) then
3379                  * we need to get the FID from the LMA. For a remote directory
3380                  * there HAS to be an LMA, it cannot be an IGIF inode in this
3381                  * case.
3382                  *
3383                  * Delete the entry before the agent inode in order to
3384                  * simplify error handling.  At worst an error after deleting
3385                  * the entry first might leak the agent inode afterward. The
3386                  * reverse would need filesystem abort in case of error deleting
3387                  * the entry after the agent had been removed, or leave a
3388                  * dangling entry pointing at a random inode. */
3389                 if (strcmp((char *)key, dotdot) != 0) {
3390                         LASSERT(de != NULL);
3391                         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
3392                         /* If Fid is not in dentry, try to get it from LMA */
3393                         if (rc == -ENODATA) {
3394                                 struct osd_inode_id *id;
3395                                 struct inode *inode;
3396
3397                                 /* Before trying to get fid from the inode,
3398                                  * check whether the inode is valid.
3399                                  *
3400                                  * If the inode has been deleted, do not go
3401                                  * ahead to do osd_ea_fid_get, which will set
3402                                  * the inode to bad inode, which might cause
3403                                  * the inode to be deleted uncorrectly */
3404                                 inode = ldiskfs_iget(osd_sb(osd),
3405                                                      le32_to_cpu(de->inode));
3406                                 if (IS_ERR(inode)) {
3407                                         CDEBUG(D_INODE, "%s: "DFID"get inode"
3408                                                "error.\n", osd_name(osd),
3409                                                PFID(fid));
3410                                         rc = PTR_ERR(inode);
3411                                 } else {
3412                                         if (likely(inode->i_nlink != 0)) {
3413                                                 id = &osd_oti_get(env)->oti_id;
3414                                                 rc = osd_ea_fid_get(env, obj,
3415                                                         le32_to_cpu(de->inode),
3416                                                                     fid, id);
3417                                         } else {
3418                                                 CDEBUG(D_INFO, "%s: %u "DFID
3419                                                        "deleted.\n",
3420                                                        osd_name(osd),
3421                                                        le32_to_cpu(de->inode),
3422                                                        PFID(fid));
3423                                                 rc = -ESTALE;
3424                                         }
3425                                         iput(inode);
3426                                 }
3427                         }
3428                         if (rc == 0 &&
3429                             unlikely(osd_remote_fid(env, osd, fid)))
3430                                 /* Need to delete agent inode */
3431                                 ino = le32_to_cpu(de->inode);
3432                 }
3433                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
3434                 brelse(bh);
3435                 if (rc == 0 && unlikely(ino != 0)) {
3436                         rc = osd_delete_local_agent_inode(env, osd, fid, ino,
3437                                                           oh);
3438                         if (rc != 0)
3439                                 CERROR("%s: del local inode "DFID": rc = %d\n",
3440                                        osd_name(osd), PFID(fid), rc);
3441                 }
3442         } else {
3443                 rc = -ENOENT;
3444         }
3445         if (hlock != NULL)
3446                 ldiskfs_htree_unlock(hlock);
3447         else
3448                 up_write(&obj->oo_ext_idx_sem);
3449
3450         if (rc != 0)
3451                 GOTO(out, rc);
3452
3453         /* For inode on the remote MDT, .. will point to
3454          * /Agent directory, Check whether it needs to delete
3455          * from agent directory */
3456         if (unlikely(strcmp((char *)key, dotdot) == 0)) {
3457                 rc = osd_delete_from_remote_parent(env, osd_obj2dev(obj), obj,
3458                                                    oh);
3459                 if (rc != 0 && rc != -ENOENT) {
3460                         CERROR("%s: delete agent inode "DFID": rc = %d\n",
3461                                osd_name(osd), PFID(fid), rc);
3462                 }
3463
3464                 if (rc == -ENOENT)
3465                         rc = 0;
3466
3467                 GOTO(out, rc);
3468         }
3469 out:
3470
3471         LASSERT(osd_invariant(obj));
3472         RETURN(rc);
3473 }
3474
3475 /**
3476  *      Lookup index for \a key and copy record to \a rec.
3477  *
3478  *      \param  dt      osd index object
3479  *      \param  key     key for index
3480  *      \param  rec     record reference
3481  *
3482  *      \retval  +ve  success : exact mach
3483  *      \retval  0    return record with key not greater than \a key
3484  *      \retval -ve   failure
3485  */
3486 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
3487                                 struct dt_rec *rec, const struct dt_key *key,
3488                                 struct lustre_capa *capa)
3489 {
3490         struct osd_object      *obj = osd_dt_obj(dt);
3491         struct iam_path_descr  *ipd;
3492         struct iam_container   *bag = &obj->oo_dir->od_container;
3493         struct osd_thread_info *oti = osd_oti_get(env);
3494         struct iam_iterator    *it = &oti->oti_idx_it;
3495         struct iam_rec         *iam_rec;
3496         int                     rc;
3497
3498         ENTRY;
3499
3500         LASSERT(osd_invariant(obj));
3501         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3502         LASSERT(bag->ic_object == obj->oo_inode);
3503
3504         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
3505                 RETURN(-EACCES);
3506
3507         ipd = osd_idx_ipd_get(env, bag);
3508         if (IS_ERR(ipd))
3509                 RETURN(-ENOMEM);
3510
3511         /* got ipd now we can start iterator. */
3512         iam_it_init(it, bag, 0, ipd);
3513
3514         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3515                 /* swab quota uid/gid provided by caller */
3516                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3517                 key = (const struct dt_key *)&oti->oti_quota_id;
3518         }
3519
3520         rc = iam_it_get(it, (struct iam_key *)key);
3521         if (rc >= 0) {
3522                 if (S_ISDIR(obj->oo_inode->i_mode))
3523                         iam_rec = (struct iam_rec *)oti->oti_ldp;
3524                 else
3525                         iam_rec = (struct iam_rec *) rec;
3526
3527                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
3528
3529                 if (S_ISDIR(obj->oo_inode->i_mode))
3530                         osd_fid_unpack((struct lu_fid *) rec,
3531                                        (struct osd_fid_pack *)iam_rec);
3532                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
3533                         osd_quota_unpack(obj, rec);
3534         }
3535
3536         iam_it_put(it);
3537         iam_it_fini(it);
3538         osd_ipd_put(env, bag, ipd);
3539
3540         LINVRNT(osd_invariant(obj));
3541
3542         RETURN(rc);
3543 }
3544
3545 static int osd_index_declare_iam_insert(const struct lu_env *env,
3546                                         struct dt_object *dt,
3547                                         const struct dt_rec *rec,
3548                                         const struct dt_key *key,
3549                                         struct thandle *handle)
3550 {
3551         struct osd_thandle *oh;
3552
3553         LASSERT(handle != NULL);
3554
3555         oh = container_of0(handle, struct osd_thandle, ot_super);
3556         LASSERT(oh->ot_handle == NULL);
3557
3558         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3559                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
3560
3561         return 0;
3562 }
3563
3564 /**
3565  *      Inserts (key, value) pair in \a dt index object.
3566  *
3567  *      \param  dt      osd index object
3568  *      \param  key     key for index
3569  *      \param  rec     record reference
3570  *      \param  th      transaction handler
3571  *
3572  *      \retval  0  success
3573  *      \retval -ve failure
3574  */
3575 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
3576                                 const struct dt_rec *rec,
3577                                 const struct dt_key *key, struct thandle *th,
3578                                 struct lustre_capa *capa, int ignore_quota)
3579 {
3580         struct osd_object     *obj = osd_dt_obj(dt);
3581         struct iam_path_descr *ipd;
3582         struct osd_thandle    *oh;
3583         struct iam_container  *bag = &obj->oo_dir->od_container;
3584         struct osd_thread_info *oti = osd_oti_get(env);
3585         struct iam_rec         *iam_rec;
3586         int                     rc;
3587
3588         ENTRY;
3589
3590         LINVRNT(osd_invariant(obj));
3591         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3592         LASSERT(bag->ic_object == obj->oo_inode);
3593         LASSERT(th != NULL);
3594
3595         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3596                 RETURN(-EACCES);
3597
3598         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3599
3600         ipd = osd_idx_ipd_get(env, bag);
3601         if (unlikely(ipd == NULL))
3602                 RETURN(-ENOMEM);
3603
3604         oh = container_of0(th, struct osd_thandle, ot_super);
3605         LASSERT(oh->ot_handle != NULL);
3606         LASSERT(oh->ot_handle->h_transaction != NULL);
3607         if (S_ISDIR(obj->oo_inode->i_mode)) {
3608                 iam_rec = (struct iam_rec *)oti->oti_ldp;
3609                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
3610         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3611                 /* pack quota uid/gid */
3612                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3613                 key = (const struct dt_key *)&oti->oti_quota_id;
3614                 /* pack quota record */
3615                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
3616                 iam_rec = (struct iam_rec *)rec;
3617         } else {
3618                 iam_rec = (struct iam_rec *)rec;
3619         }
3620
3621         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
3622                         iam_rec, ipd);
3623         osd_ipd_put(env, bag, ipd);
3624         LINVRNT(osd_invariant(obj));
3625         RETURN(rc);
3626 }
3627
3628 /**
3629  * Calls ldiskfs_add_entry() to add directory entry
3630  * into the directory. This is required for
3631  * interoperability mode (b11826)
3632  *
3633  * \retval   0, on success
3634  * \retval -ve, on error
3635  */
3636 static int __osd_ea_add_rec(struct osd_thread_info *info,
3637                             struct osd_object *pobj, struct inode  *cinode,
3638                             const char *name, const struct dt_rec *fid,
3639                             struct htree_lock *hlock, struct thandle *th)
3640 {
3641         struct ldiskfs_dentry_param *ldp;
3642         struct dentry               *child;
3643         struct osd_thandle          *oth;
3644         int                          rc;
3645
3646         oth = container_of(th, struct osd_thandle, ot_super);
3647         LASSERT(oth->ot_handle != NULL);
3648         LASSERT(oth->ot_handle->h_transaction != NULL);
3649         LASSERT(pobj->oo_inode);
3650
3651         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3652         if (unlikely(pobj->oo_inode ==
3653                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
3654                 ldp->edp_magic = 0;
3655         else
3656                 osd_get_ldiskfs_dirent_param(ldp, fid);
3657         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
3658         child->d_fsdata = (void *)ldp;
3659         ll_vfs_dq_init(pobj->oo_inode);
3660         rc = osd_ldiskfs_add_entry(oth->ot_handle, child, cinode, hlock);
3661
3662         RETURN(rc);
3663 }
3664
3665 /**
3666  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
3667  * into the directory.Also sets flags into osd object to
3668  * indicate dot and dotdot are created. This is required for
3669  * interoperability mode (b11826)
3670  *
3671  * \param dir   directory for dot and dotdot fixup.
3672  * \param obj   child object for linking
3673  *
3674  * \retval   0, on success
3675  * \retval -ve, on error
3676  */
3677 static int osd_add_dot_dotdot(struct osd_thread_info *info,
3678                               struct osd_object *dir,
3679                               struct inode  *parent_dir, const char *name,
3680                               const struct dt_rec *dot_fid,
3681                               const struct dt_rec *dot_dot_fid,
3682                               struct thandle *th)
3683 {
3684         struct inode                *inode = dir->oo_inode;
3685         struct osd_thandle          *oth;
3686         int result = 0;
3687
3688         oth = container_of(th, struct osd_thandle, ot_super);
3689         LASSERT(oth->ot_handle->h_transaction != NULL);
3690         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
3691
3692         if (strcmp(name, dot) == 0) {
3693                 if (dir->oo_compat_dot_created) {
3694                         result = -EEXIST;
3695                 } else {
3696                         LASSERT(inode == parent_dir);
3697                         dir->oo_compat_dot_created = 1;
3698                         result = 0;
3699                 }
3700         } else if (strcmp(name, dotdot) == 0) {
3701                 if (!dir->oo_compat_dot_created)
3702                         return -EINVAL;
3703                 /* in case of rename, dotdot is already created */
3704                 if (dir->oo_compat_dotdot_created) {
3705                         return __osd_ea_add_rec(info, dir, parent_dir, name,
3706                                                 dot_dot_fid, NULL, th);
3707                 }
3708
3709                 result = osd_add_dot_dotdot_internal(info, dir->oo_inode,
3710                                                 parent_dir, dot_fid,
3711                                                 dot_dot_fid, oth);
3712                 if (result == 0)
3713                         dir->oo_compat_dotdot_created = 1;
3714         }
3715
3716         return result;
3717 }
3718
3719
3720 /**
3721  * It will call the appropriate osd_add* function and return the
3722  * value, return by respective functions.
3723  */
3724 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
3725                           struct inode *cinode, const char *name,
3726                           const struct dt_rec *fid, struct thandle *th)
3727 {
3728         struct osd_thread_info *info   = osd_oti_get(env);
3729         struct htree_lock      *hlock;
3730         int                     rc;
3731
3732         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
3733
3734         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
3735                                                    name[2] =='\0'))) {
3736                 if (hlock != NULL) {
3737                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3738                                            pobj->oo_inode, 0);
3739                 } else {
3740                         down_write(&pobj->oo_ext_idx_sem);
3741                 }
3742                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
3743                      (struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
3744                                         fid, th);
3745         } else {
3746                 if (hlock != NULL) {
3747                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3748                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
3749                 } else {
3750                         down_write(&pobj->oo_ext_idx_sem);
3751                 }
3752
3753                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
3754                         struct lu_fid *tfid = &info->oti_fid;
3755
3756                         *tfid = *(const struct lu_fid *)fid;
3757                         tfid->f_ver = ~0;
3758                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
3759                                               (const struct dt_rec *)tfid,
3760                                               hlock, th);
3761                 } else {
3762                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
3763                                               hlock, th);
3764                 }
3765         }
3766         if (hlock != NULL)
3767                 ldiskfs_htree_unlock(hlock);
3768         else
3769                 up_write(&pobj->oo_ext_idx_sem);
3770
3771         return rc;
3772 }
3773
3774 static void
3775 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
3776                       struct osd_idmap_cache *oic)
3777 {
3778         struct osd_scrub    *scrub = &dev->od_scrub;
3779         struct lu_fid       *fid   = &oic->oic_fid;
3780         struct osd_inode_id *id    = &oti->oti_id;
3781         int                  once  = 0;
3782         int                  rc;
3783         ENTRY;
3784
3785         if (!fid_is_norm(fid) && !fid_is_igif(fid))
3786                 RETURN_EXIT;
3787
3788 again:
3789         rc = osd_oi_lookup(oti, dev, fid, id, true);
3790         if (rc != 0 && rc != -ENOENT)
3791                 RETURN_EXIT;
3792
3793         if (rc == 0 && osd_id_eq(id, &oic->oic_lid))
3794                 RETURN_EXIT;
3795
3796         if (thread_is_running(&scrub->os_thread)) {
3797                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
3798                 /* There is race condition between osd_oi_lookup and OI scrub.
3799                  * The OI scrub finished just after osd_oi_lookup() failure.
3800                  * Under such case, it is unnecessary to trigger OI scrub again,
3801                  * but try to call osd_oi_lookup() again. */
3802                 if (unlikely(rc == -EAGAIN))
3803                         goto again;
3804
3805                 RETURN_EXIT;
3806         }
3807
3808         if (!dev->od_noscrub && ++once == 1) {
3809                 CDEBUG(D_LFSCK, "Trigger OI scrub by RPC for "DFID"\n",
3810                        PFID(fid));
3811                 rc = osd_scrub_start(dev);
3812                 LCONSOLE_ERROR("%.16s: trigger OI scrub by RPC for "DFID
3813                                ", rc = %d [2]\n",
3814                                LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
3815                                PFID(fid), rc);
3816                 if (rc == 0)
3817                         goto again;
3818         }
3819
3820         EXIT;
3821 }
3822
3823 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
3824                                struct osd_device *dev,
3825                                struct osd_idmap_cache *oic,
3826                                struct lu_fid *fid, __u32 ino)
3827 {
3828         struct lustre_mdt_attrs *lma   = &oti->oti_mdt_attrs;
3829         struct inode            *inode;
3830         int                      rc;
3831
3832         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
3833         inode = osd_iget(oti, dev, &oic->oic_lid);
3834         if (IS_ERR(inode)) {
3835                 fid_zero(&oic->oic_fid);
3836                 return PTR_ERR(inode);
3837         }
3838
3839         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, lma);
3840         iput(inode);
3841         if (rc != 0)
3842                 fid_zero(&oic->oic_fid);
3843         else
3844                 *fid = oic->oic_fid = lma->lma_self_fid;
3845         return rc;
3846 }
3847
3848 int osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
3849                      struct osd_inode_id *id, const struct lu_fid *fid)
3850 {
3851         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
3852                id->oii_ino, id->oii_gen, info);
3853         info->oti_cache.oic_lid = *id;
3854         info->oti_cache.oic_fid = *fid;
3855
3856         return 0;
3857 }
3858
3859 /**
3860  * Calls ->lookup() to find dentry. From dentry get inode and
3861  * read inode's ea to get fid. This is required for  interoperability
3862  * mode (b11826)
3863  *
3864  * \retval   0, on success
3865  * \retval -ve, on error
3866  */
3867 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
3868                              struct dt_rec *rec, const struct dt_key *key)
3869 {
3870         struct inode               *dir    = obj->oo_inode;
3871         struct dentry              *dentry;
3872         struct ldiskfs_dir_entry_2 *de;
3873         struct buffer_head         *bh;
3874         struct lu_fid              *fid = (struct lu_fid *) rec;
3875         struct htree_lock          *hlock = NULL;
3876         int                         ino;
3877         int                         rc;
3878         ENTRY;
3879
3880         LASSERT(dir->i_op != NULL && dir->i_op->lookup != NULL);
3881
3882         dentry = osd_child_dentry_get(env, obj,
3883                                       (char *)key, strlen((char *)key));
3884
3885         if (obj->oo_hl_head != NULL) {
3886                 hlock = osd_oti_get(env)->oti_hlock;
3887                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3888                                    dir, LDISKFS_HLOCK_LOOKUP);
3889         } else {
3890                 down_read(&obj->oo_ext_idx_sem);
3891         }
3892
3893         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
3894         if (bh) {
3895                 struct osd_thread_info *oti = osd_oti_get(env);
3896                 struct osd_inode_id *id = &oti->oti_id;
3897                 struct osd_idmap_cache *oic = &oti->oti_cache;
3898                 struct osd_device *dev = osd_obj2dev(obj);
3899                 struct osd_scrub *scrub = &dev->od_scrub;
3900                 struct scrub_file *sf = &scrub->os_file;
3901
3902                 ino = le32_to_cpu(de->inode);
3903                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
3904                         brelse(bh);
3905                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
3906                         GOTO(out, rc);
3907                 }
3908
3909                 rc = osd_get_fid_from_dentry(de, rec);
3910
3911                 /* done with de, release bh */
3912                 brelse(bh);
3913                 if (rc != 0)
3914                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
3915                 else
3916                         osd_id_gen(id, ino, OSD_OII_NOGEN);
3917                 if (rc != 0 || osd_remote_fid(env, dev, fid)) {
3918                         fid_zero(&oic->oic_fid);
3919                         GOTO(out, rc);
3920                 }
3921
3922                 rc = osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id,
3923                                       fid);
3924                 if (rc != 0)
3925                         GOTO(out, rc);
3926                 if ((scrub->os_pos_current <= ino) &&
3927                     ((sf->sf_flags & SF_INCONSISTENT) ||
3928                      (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
3929                      ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
3930                                       sf->sf_oi_bitmap)))
3931                         osd_consistency_check(oti, dev, oic);
3932         } else {
3933                 rc = -ENOENT;
3934         }
3935
3936         GOTO(out, rc);
3937
3938 out:
3939         if (hlock != NULL)
3940                 ldiskfs_htree_unlock(hlock);
3941         else
3942                 up_read(&obj->oo_ext_idx_sem);
3943         return rc;
3944 }
3945
3946 /**
3947  * Find the osd object for given fid.
3948  *
3949  * \param fid need to find the osd object having this fid
3950  *
3951  * \retval osd_object on success
3952  * \retval        -ve on error
3953  */
3954 struct osd_object *osd_object_find(const struct lu_env *env,
3955                                    struct dt_object *dt,
3956                                    const struct lu_fid *fid)
3957 {
3958         struct lu_device  *ludev = dt->do_lu.lo_dev;
3959         struct osd_object *child = NULL;
3960         struct lu_object  *luch;
3961         struct lu_object  *lo;
3962
3963         /*
3964          * at this point topdev might not exist yet
3965          * (i.e. MGS is preparing profiles). so we can
3966          * not rely on topdev and instead lookup with
3967          * our device passed as topdev. this can't work
3968          * if the object isn't cached yet (as osd doesn't
3969          * allocate lu_header). IOW, the object must be
3970          * in the cache, otherwise lu_object_alloc() crashes
3971          * -bzzz
3972          */
3973         luch = lu_object_find_at(env, ludev, fid, NULL);
3974         if (!IS_ERR(luch)) {
3975                 if (lu_object_exists(luch)) {
3976                         lo = lu_object_locate(luch->lo_header, ludev->ld_type);
3977                         if (lo != NULL)
3978                                 child = osd_obj(lo);
3979                         else
3980                                 LU_OBJECT_DEBUG(D_ERROR, env, luch,
3981                                                 "lu_object can't be located"
3982                                                 DFID"\n", PFID(fid));
3983
3984                         if (child == NULL) {
3985                                 lu_object_put(env, luch);
3986                                 CERROR("Unable to get osd_object\n");
3987                                 child = ERR_PTR(-ENOENT);
3988                         }
3989                 } else {
3990                         LU_OBJECT_DEBUG(D_ERROR, env, luch,
3991                                         "lu_object does not exists "DFID"\n",
3992                                         PFID(fid));
3993                         lu_object_put(env, luch);
3994                         child = ERR_PTR(-ENOENT);
3995                 }
3996         } else
3997                 child = (void *)luch;
3998
3999         return child;
4000 }
4001
4002 /**
4003  * Put the osd object once done with it.
4004  *
4005  * \param obj osd object that needs to be put
4006  */
4007 static inline void osd_object_put(const struct lu_env *env,
4008                                   struct osd_object *obj)
4009 {
4010         lu_object_put(env, &obj->oo_dt.do_lu);
4011 }
4012
4013 static int osd_index_declare_ea_insert(const struct lu_env *env,
4014                                        struct dt_object *dt,
4015                                        const struct dt_rec *rec,
4016                                        const struct dt_key *key,
4017                                        struct thandle *handle)
4018 {
4019         struct osd_thandle      *oh;
4020         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
4021         struct lu_fid           *fid = (struct lu_fid *)rec;
4022         int                     rc;
4023         ENTRY;
4024
4025         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4026         LASSERT(handle != NULL);
4027
4028         oh = container_of0(handle, struct osd_thandle, ot_super);
4029         LASSERT(oh->ot_handle == NULL);
4030
4031         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4032                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4033
4034         if (osd_dt_obj(dt)->oo_inode == NULL) {
4035                 const char *name  = (const char *)key;
4036                 /* Object is not being created yet. Only happens when
4037                  *     1. declare directory create
4038                  *     2. declare insert .
4039                  *     3. declare insert ..
4040                  */
4041                 LASSERT(strcmp(name, dotdot) == 0 || strcmp(name, dot) == 0);
4042         } else {
4043                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
4044
4045                 /* We ignore block quota on meta pool (MDTs), so needn't
4046                  * calculate how many blocks will be consumed by this index
4047                  * insert */
4048                 rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0,
4049                                            oh, true, true, NULL, false);
4050         }
4051
4052         if (fid == NULL)
4053                 RETURN(0);
4054
4055         rc = osd_remote_fid(env, osd, fid);
4056         if (rc <= 0)
4057                 RETURN(rc);
4058
4059         rc = 0;
4060
4061         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
4062                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
4063         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4064                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4065         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4066                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4067
4068         RETURN(rc);
4069 }
4070
4071 /**
4072  * Index add function for interoperability mode (b11826).
4073  * It will add the directory entry.This entry is needed to
4074  * maintain name->fid mapping.
4075  *
4076  * \param key it is key i.e. file entry to be inserted
4077  * \param rec it is value of given key i.e. fid
4078  *
4079  * \retval   0, on success
4080  * \retval -ve, on error
4081  */
4082 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
4083                                const struct dt_rec *rec,
4084                                const struct dt_key *key, struct thandle *th,
4085                                struct lustre_capa *capa, int ignore_quota)
4086 {
4087         struct osd_object       *obj = osd_dt_obj(dt);
4088         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
4089         struct lu_fid           *fid = (struct lu_fid *) rec;
4090         const char              *name = (const char *)key;
4091         struct osd_thread_info  *oti   = osd_oti_get(env);
4092         struct osd_inode_id     *id    = &oti->oti_id;
4093         struct inode            *child_inode = NULL;
4094         struct osd_object       *child = NULL;
4095         int                     rc;
4096         ENTRY;
4097
4098         LASSERT(osd_invariant(obj));
4099         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4100         LASSERT(th != NULL);
4101
4102         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4103
4104         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
4105                 RETURN(-EACCES);
4106
4107         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!", PFID(fid));
4108
4109         rc = osd_remote_fid(env, osd, fid);
4110         if (rc < 0) {
4111                 CERROR("%s: Can not find object "DFID" rc %d\n",
4112                        osd_name(osd), PFID(fid), rc);
4113                 RETURN(rc);
4114         }
4115
4116         if (rc == 1) {
4117                 /* Insert remote entry */
4118                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
4119                         struct osd_mdobj_map    *omm = osd->od_mdt_map;
4120                         struct osd_thandle      *oh;
4121
4122                         /* If parent on remote MDT, we need put this object
4123                          * under AGENT */
4124                         oh = container_of(th, typeof(*oh), ot_super);
4125                         rc = osd_add_to_remote_parent(env, osd, obj, oh);
4126                         if (rc != 0) {
4127                                 CERROR("%s: add "DFID" error: rc = %d\n",
4128                                        osd_name(osd),
4129                                        PFID(lu_object_fid(&dt->do_lu)), rc);
4130                                 RETURN(rc);
4131                         }
4132
4133                         child_inode = igrab(omm->omm_remote_parent->d_inode);
4134                 } else {
4135                         child_inode = osd_create_local_agent_inode(env, osd,
4136                                                                    obj, fid,
4137                                                                    th);
4138                         if (IS_ERR(child_inode))
4139                                 RETURN(PTR_ERR(child_inode));
4140                 }
4141         } else {
4142                 /* Insert local entry */
4143                 child = osd_object_find(env, dt, fid);
4144                 if (IS_ERR(child)) {
4145                         CERROR("%s: Can not find object "DFID"%u:%u: rc = %d\n",
4146                                osd_name(osd), PFID(fid),
4147                                id->oii_ino, id->oii_gen,
4148                                (int)PTR_ERR(child_inode));
4149                         RETURN(PTR_ERR(child_inode));
4150                 }
4151                 child_inode = igrab(child->oo_inode);
4152         }
4153
4154         rc = osd_ea_add_rec(env, obj, child_inode, name, rec, th);
4155
4156         iput(child_inode);
4157         if (child != NULL)
4158                 osd_object_put(env, child);
4159         LASSERT(osd_invariant(obj));
4160         RETURN(rc);
4161 }
4162
4163 /**
4164  *  Initialize osd Iterator for given osd index object.
4165  *
4166  *  \param  dt      osd index object
4167  */
4168
4169 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
4170                                      struct dt_object *dt,
4171                                      __u32 unused,
4172                                      struct lustre_capa *capa)
4173 {
4174         struct osd_it_iam      *it;
4175         struct osd_thread_info *oti = osd_oti_get(env);
4176         struct osd_object      *obj = osd_dt_obj(dt);
4177         struct lu_object       *lo  = &dt->do_lu;
4178         struct iam_path_descr  *ipd;
4179         struct iam_container   *bag = &obj->oo_dir->od_container;
4180
4181         LASSERT(lu_object_exists(lo));
4182
4183         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
4184                 return ERR_PTR(-EACCES);
4185
4186         it = &oti->oti_it;
4187         ipd = osd_it_ipd_get(env, bag);
4188         if (likely(ipd != NULL)) {
4189                 it->oi_obj = obj;
4190                 it->oi_ipd = ipd;
4191                 lu_object_get(lo);
4192                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
4193                 return (struct dt_it *)it;
4194         }
4195         return ERR_PTR(-ENOMEM);
4196 }
4197
4198 /**
4199  * free given Iterator.
4200  */
4201
4202 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
4203 {
4204         struct osd_it_iam *it = (struct osd_it_iam *)di;
4205         struct osd_object *obj = it->oi_obj;
4206
4207         iam_it_fini(&it->oi_it);
4208         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
4209         lu_object_put(env, &obj->oo_dt.do_lu);
4210 }
4211
4212 /**
4213  *  Move Iterator to record specified by \a key
4214  *
4215  *  \param  di      osd iterator
4216  *  \param  key     key for index
4217  *
4218  *  \retval +ve  di points to record with least key not larger than key
4219  *  \retval  0   di points to exact matched key
4220  *  \retval -ve  failure
4221  */
4222
4223 static int osd_it_iam_get(const struct lu_env *env,
4224                           struct dt_it *di, const struct dt_key *key)
4225 {
4226         struct osd_thread_info  *oti = osd_oti_get(env);
4227         struct osd_it_iam       *it = (struct osd_it_iam *)di;
4228
4229         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4230                 /* swab quota uid/gid */
4231                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4232                 key = (struct dt_key *)&oti->oti_quota_id;
4233         }
4234
4235         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
4236 }
4237
4238 /**
4239  *  Release Iterator
4240  *
4241  *  \param  di      osd iterator
4242  */
4243 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
4244 {
4245         struct osd_it_iam *it = (struct osd_it_iam *)di;
4246
4247         iam_it_put(&it->oi_it);
4248 }
4249
4250 /**
4251  *  Move iterator by one record
4252  *
4253  *  \param  di      osd iterator
4254  *
4255  *  \retval +1   end of container reached
4256  *  \retval  0   success
4257  *  \retval -ve  failure
4258  */
4259
4260 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
4261 {
4262         struct osd_it_iam *it = (struct osd_it_iam *)di;
4263
4264         return iam_it_next(&it->oi_it);
4265 }
4266
4267 /**
4268  * Return pointer to the key under iterator.
4269  */
4270
4271 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
4272                                  const struct dt_it *di)
4273 {
4274         struct osd_thread_info *oti = osd_oti_get(env);
4275         struct osd_it_iam      *it = (struct osd_it_iam *)di;
4276         struct osd_object      *obj = it->oi_obj;
4277         struct dt_key          *key;
4278
4279         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
4280
4281         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
4282                 /* swab quota uid/gid */
4283                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
4284                 key = (struct dt_key *)&oti->oti_quota_id;
4285         }
4286
4287         return key;
4288 }
4289
4290 /**
4291  * Return size of key under iterator (in bytes)
4292  */
4293
4294 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
4295 {
4296         struct osd_it_iam *it = (struct osd_it_iam *)di;
4297
4298         return iam_it_key_size(&it->oi_it);
4299 }
4300
4301 static inline void
4302 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
4303 {
4304         /* check if file type is required */
4305         if (ent->lde_attrs & LUDA_TYPE) {
4306                 struct luda_type *lt;
4307                 int align = sizeof(*lt) - 1;
4308
4309                 len = (len + align) & ~align;
4310                 lt = (struct luda_type *)(ent->lde_name + len);
4311                 lt->lt_type = cpu_to_le16(DTTOIF(type));
4312         }
4313
4314         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
4315 }
4316
4317 /**
4318  * build lu direct from backend fs dirent.
4319  */
4320
4321 static inline void
4322 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
4323                    char *name, __u16 namelen, __u16 type, __u32 attr)
4324 {
4325         ent->lde_attrs = attr | LUDA_FID;
4326         fid_cpu_to_le(&ent->lde_fid, fid);
4327
4328         ent->lde_hash = cpu_to_le64(offset);
4329         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
4330
4331         strncpy(ent->lde_name, name, namelen);
4332         ent->lde_name[namelen] = '\0';
4333         ent->lde_namelen = cpu_to_le16(namelen);
4334
4335         /* append lustre attributes */
4336         osd_it_append_attrs(ent, namelen, type);
4337 }
4338
4339 /**
4340  * Return pointer to the record under iterator.
4341  */
4342 static int osd_it_iam_rec(const struct lu_env *env,
4343                           const struct dt_it *di,
4344                           struct dt_rec *dtrec, __u32 attr)
4345 {
4346         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
4347         struct osd_thread_info *info = osd_oti_get(env);
4348         ENTRY;
4349
4350         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
4351                 const struct osd_fid_pack *rec;
4352                 struct lu_fid             *fid = &info->oti_fid;
4353                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
4354                 char                      *name;
4355                 int                        namelen;
4356                 __u64                      hash;
4357                 int                        rc;
4358
4359                 name = (char *)iam_it_key_get(&it->oi_it);
4360                 if (IS_ERR(name))
4361                         RETURN(PTR_ERR(name));
4362
4363                 namelen = iam_it_key_size(&it->oi_it);
4364
4365                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
4366                 if (IS_ERR(rec))
4367                         RETURN(PTR_ERR(rec));
4368
4369                 rc = osd_fid_unpack(fid, rec);
4370                 if (rc)
4371                         RETURN(rc);
4372
4373                 hash = iam_it_store(&it->oi_it);
4374
4375                 /* IAM does not store object type in IAM index (dir) */
4376                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
4377                                    0, LUDA_FID);
4378         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4379                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4380                            (struct iam_rec *)dtrec);
4381                 osd_quota_unpack(it->oi_obj, dtrec);
4382         } else {
4383                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4384                            (struct iam_rec *)dtrec);
4385         }
4386
4387         RETURN(0);
4388 }
4389
4390 /**
4391  * Returns cookie for current Iterator position.
4392  */
4393 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
4394 {
4395         struct osd_it_iam *it = (struct osd_it_iam *)di;
4396
4397         return iam_it_store(&it->oi_it);
4398 }
4399
4400 /**
4401  * Restore iterator from cookie.
4402  *
4403  * \param  di      osd iterator
4404  * \param  hash    Iterator location cookie
4405  *
4406  * \retval +ve  di points to record with least key not larger than key.
4407  * \retval  0   di points to exact matched key
4408  * \retval -ve  failure
4409  */
4410
4411 static int osd_it_iam_load(const struct lu_env *env,
4412                            const struct dt_it *di, __u64 hash)
4413 {
4414         struct osd_it_iam *it = (struct osd_it_iam *)di;
4415
4416         return iam_it_load(&it->oi_it, hash);
4417 }
4418
4419 static const struct dt_index_operations osd_index_iam_ops = {
4420         .dio_lookup         = osd_index_iam_lookup,
4421         .dio_declare_insert = osd_index_declare_iam_insert,
4422         .dio_insert         = osd_index_iam_insert,
4423         .dio_declare_delete = osd_index_declare_iam_delete,
4424         .dio_delete         = osd_index_iam_delete,
4425         .dio_it     = {
4426                 .init     = osd_it_iam_init,
4427                 .fini     = osd_it_iam_fini,
4428                 .get      = osd_it_iam_get,
4429                 .put      = osd_it_iam_put,
4430                 .next     = osd_it_iam_next,
4431                 .key      = osd_it_iam_key,
4432                 .key_size = osd_it_iam_key_size,
4433                 .rec      = osd_it_iam_rec,
4434                 .store    = osd_it_iam_store,
4435                 .load     = osd_it_iam_load
4436         }
4437 };
4438
4439
4440 /**
4441  * Creates or initializes iterator context.
4442  *
4443  * \retval struct osd_it_ea, iterator structure on success
4444  *
4445  */
4446 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
4447                                     struct dt_object *dt,
4448                                     __u32 attr,
4449                                     struct lustre_capa *capa)
4450 {
4451         struct osd_object       *obj  = osd_dt_obj(dt);
4452         struct osd_thread_info  *info = osd_oti_get(env);
4453         struct osd_it_ea        *it   = &info->oti_it_ea;
4454         struct file             *file = &it->oie_file;
4455         struct lu_object        *lo   = &dt->do_lu;
4456         struct dentry           *obj_dentry = &info->oti_it_dentry;
4457         ENTRY;
4458         LASSERT(lu_object_exists(lo));
4459
4460         obj_dentry->d_inode = obj->oo_inode;
4461         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
4462         obj_dentry->d_name.hash = 0;
4463
4464         it->oie_rd_dirent       = 0;
4465         it->oie_it_dirent       = 0;
4466         it->oie_dirent          = NULL;
4467         it->oie_buf             = info->oti_it_ea_buf;
4468         it->oie_obj             = obj;
4469
4470         /* Reset the "file" totally to avoid to reuse any old value from
4471          * former readdir handling, the "file->f_pos" should be zero. */
4472         memset(file, 0, sizeof(*file));
4473         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
4474         if (attr & LUDA_64BITHASH)
4475                 file->f_mode    = FMODE_64BITHASH;
4476         else
4477                 file->f_mode    = FMODE_32BITHASH;
4478         file->f_dentry          = obj_dentry;
4479         file->f_mapping         = obj->oo_inode->i_mapping;
4480         file->f_op              = obj->oo_inode->i_fop;
4481         lu_object_get(lo);
4482         RETURN((struct dt_it *) it);
4483 }
4484
4485 /**
4486  * Destroy or finishes iterator context.
4487  *
4488  * \param di iterator structure to be destroyed
4489  */
4490 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
4491 {
4492         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4493         struct osd_object    *obj  = it->oie_obj;
4494         struct inode       *inode  = obj->oo_inode;
4495
4496         ENTRY;
4497         it->oie_file.f_op->release(inode, &it->oie_file);
4498         lu_object_put(env, &obj->oo_dt.do_lu);
4499         EXIT;
4500 }
4501
4502 /**
4503  * It position the iterator at given key, so that next lookup continues from
4504  * that key Or it is similar to dio_it->load() but based on a key,
4505  * rather than file position.
4506  *
4507  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
4508  * to the beginning.
4509  *
4510  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
4511  */
4512 static int osd_it_ea_get(const struct lu_env *env,
4513                          struct dt_it *di, const struct dt_key *key)
4514 {
4515         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4516
4517         ENTRY;
4518         LASSERT(((const char *)key)[0] == '\0');
4519         it->oie_file.f_pos      = 0;
4520         it->oie_rd_dirent       = 0;
4521         it->oie_it_dirent       = 0;
4522         it->oie_dirent          = NULL;
4523
4524         RETURN(+1);
4525 }
4526
4527 /**
4528  * Does nothing
4529  */
4530 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
4531 {
4532 }
4533
4534 /**
4535  * It is called internally by ->readdir(). It fills the
4536  * iterator's in-memory data structure with required
4537  * information i.e. name, namelen, rec_size etc.
4538  *
4539  * \param buf in which information to be filled in.
4540  * \param name name of the file in given dir
4541  *
4542  * \retval 0 on success
4543  * \retval 1 on buffer full
4544  */
4545 static int osd_ldiskfs_filldir(char *buf, const char *name, int namelen,
4546                                loff_t offset, __u64 ino,
4547                                unsigned d_type)
4548 {
4549         struct osd_it_ea        *it   = (struct osd_it_ea *)buf;
4550         struct osd_object       *obj  = it->oie_obj;
4551         struct osd_it_ea_dirent *ent  = it->oie_dirent;
4552         struct lu_fid           *fid  = &ent->oied_fid;
4553         struct osd_fid_pack     *rec;
4554         ENTRY;
4555
4556         /* this should never happen */
4557         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
4558                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
4559                 RETURN(-EIO);
4560         }
4561
4562         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
4563             OSD_IT_EA_BUFSIZE)
4564                 RETURN(1);
4565
4566         /* "." is just the object itself. */
4567         if (namelen == 1 && name[0] == '.') {
4568                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4569         } else if (d_type & LDISKFS_DIRENT_LUFID) {
4570                 rec = (struct osd_fid_pack*) (name + namelen + 1);
4571                 if (osd_fid_unpack(fid, rec) != 0)
4572                         fid_zero(fid);
4573         } else {
4574                 fid_zero(fid);
4575         }
4576         d_type &= ~LDISKFS_DIRENT_LUFID;
4577
4578         /* NOT export local root. */
4579         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
4580                 ino = obj->oo_inode->i_ino;
4581                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4582         }
4583
4584         ent->oied_ino     = ino;
4585         ent->oied_off     = offset;
4586         ent->oied_namelen = namelen;
4587         ent->oied_type    = d_type;
4588
4589         memcpy(ent->oied_name, name, namelen);
4590
4591         it->oie_rd_dirent++;
4592         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
4593         RETURN(0);
4594 }
4595
4596 /**
4597  * Calls ->readdir() to load a directory entry at a time
4598  * and stored it in iterator's in-memory data structure.
4599  *
4600  * \param di iterator's in memory structure
4601  *
4602  * \retval   0 on success
4603  * \retval -ve on error
4604  */
4605 static int osd_ldiskfs_it_fill(const struct lu_env *env,
4606                                const struct dt_it *di)
4607 {
4608         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
4609         struct osd_object  *obj   = it->oie_obj;
4610         struct inode       *inode = obj->oo_inode;
4611         struct htree_lock  *hlock = NULL;
4612         int                 result = 0;
4613
4614         ENTRY;
4615         it->oie_dirent = it->oie_buf;
4616         it->oie_rd_dirent = 0;
4617
4618         if (obj->oo_hl_head != NULL) {
4619                 hlock = osd_oti_get(env)->oti_hlock;
4620                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4621                                    inode, LDISKFS_HLOCK_READDIR);
4622         } else {
4623                 down_read(&obj->oo_ext_idx_sem);
4624         }
4625
4626         result = inode->i_fop->readdir(&it->oie_file, it,
4627                                        (filldir_t) osd_ldiskfs_filldir);
4628
4629         if (hlock != NULL)
4630                 ldiskfs_htree_unlock(hlock);
4631         else
4632                 up_read(&obj->oo_ext_idx_sem);
4633
4634         if (it->oie_rd_dirent == 0) {
4635                 result = -EIO;
4636         } else {
4637                 it->oie_dirent = it->oie_buf;
4638                 it->oie_it_dirent = 1;
4639         }
4640
4641         RETURN(result);
4642 }
4643
4644 /**
4645  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4646  * to load a directory entry at a time and stored it in
4647  * iterator's in-memory data structure.
4648  *
4649  * \param di iterator's in memory structure
4650  *
4651  * \retval +ve iterator reached to end
4652  * \retval   0 iterator not reached to end
4653  * \retval -ve on error
4654  */
4655 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
4656 {
4657         struct osd_it_ea *it = (struct osd_it_ea *)di;
4658         int rc;
4659
4660         ENTRY;
4661
4662         if (it->oie_it_dirent < it->oie_rd_dirent) {
4663                 it->oie_dirent =
4664                         (void *) it->oie_dirent +
4665                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
4666                                        it->oie_dirent->oied_namelen);
4667                 it->oie_it_dirent++;
4668                 RETURN(0);
4669         } else {
4670                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
4671                         rc = +1;
4672                 else
4673                         rc = osd_ldiskfs_it_fill(env, di);
4674         }
4675
4676         RETURN(rc);
4677 }
4678
4679 /**
4680  * Returns the key at current position from iterator's in memory structure.
4681  *
4682  * \param di iterator's in memory structure
4683  *
4684  * \retval key i.e. struct dt_key on success
4685  */
4686 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
4687                                     const struct dt_it *di)
4688 {
4689         struct osd_it_ea *it = (struct osd_it_ea *)di;
4690
4691         return (struct dt_key *)it->oie_dirent->oied_name;
4692 }
4693
4694 /**
4695  * Returns the key's size at current position from iterator's in memory structure.
4696  *
4697  * \param di iterator's in memory structure
4698  *
4699  * \retval key_size i.e. struct dt_key on success
4700  */
4701 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
4702 {
4703         struct osd_it_ea *it = (struct osd_it_ea *)di;
4704
4705         return it->oie_dirent->oied_namelen;
4706 }
4707
4708 static int
4709 osd_dirent_update(handle_t *jh, struct super_block *sb,
4710                   struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4711                   struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de)
4712 {
4713         struct osd_fid_pack *rec;
4714         int                  rc;
4715         ENTRY;
4716
4717         LASSERT(de->file_type & LDISKFS_DIRENT_LUFID);
4718         LASSERT(de->rec_len >= de->name_len + sizeof(struct osd_fid_pack));
4719
4720         rc = ldiskfs_journal_get_write_access(jh, bh);
4721         if (rc != 0) {
4722                 CERROR("%.16s: fail to write access for update dirent: "
4723                        "name = %.*s, rc = %d\n",
4724                        LDISKFS_SB(sb)->s_es->s_volume_name,
4725                        ent->oied_namelen, ent->oied_name, rc);
4726                 RETURN(rc);
4727         }
4728
4729         rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4730         fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4731         rc = ldiskfs_journal_dirty_metadata(jh, bh);
4732         if (rc != 0)
4733                 CERROR("%.16s: fail to dirty metadata for update dirent: "
4734                        "name = %.*s, rc = %d\n",
4735                        LDISKFS_SB(sb)->s_es->s_volume_name,
4736                        ent->oied_namelen, ent->oied_name, rc);
4737
4738         RETURN(rc);
4739 }
4740
4741 static inline int
4742 osd_dirent_has_space(__u16 reclen, __u16 namelen, unsigned blocksize)
4743 {
4744         if (ldiskfs_rec_len_from_disk(reclen, blocksize) >=
4745             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
4746                 return 1;
4747         else
4748                 return 0;
4749 }
4750
4751 static inline int
4752 osd_dot_dotdot_has_space(struct ldiskfs_dir_entry_2 *de, int dot_dotdot)
4753 {
4754         LASSERTF(dot_dotdot == 1 || dot_dotdot == 2,
4755                  "dot_dotdot = %d\n", dot_dotdot);
4756
4757         if (LDISKFS_DIR_REC_LEN(de) >=
4758             __LDISKFS_DIR_REC_LEN(dot_dotdot + 1 + sizeof(struct osd_fid_pack)))
4759                 return 1;
4760         else
4761                 return 0;
4762 }
4763
4764 static int
4765 osd_dirent_reinsert(const struct lu_env *env, handle_t *jh,
4766                     struct inode *dir, struct inode *inode,
4767                     struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4768                     struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de,
4769                     struct htree_lock *hlock)
4770 {
4771         struct dentry               *dentry;
4772         struct osd_fid_pack         *rec;
4773         struct ldiskfs_dentry_param *ldp;
4774         int                          rc;
4775         ENTRY;
4776
4777         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
4778                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
4779                 RETURN(0);
4780
4781         /* There is enough space to hold the FID-in-dirent. */
4782         if (osd_dirent_has_space(de->rec_len, ent->oied_namelen,
4783                                  dir->i_sb->s_blocksize)) {
4784                 rc = ldiskfs_journal_get_write_access(jh, bh);
4785                 if (rc != 0) {
4786                         CERROR("%.16s: fail to write access for reinsert "
4787                                "dirent: name = %.*s, rc = %d\n",
4788                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4789                                ent->oied_namelen, ent->oied_name, rc);
4790                         RETURN(rc);
4791                 }
4792
4793                 de->name[de->name_len] = 0;
4794                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4795                 rec->fp_len = sizeof(struct lu_fid) + 1;
4796                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4797                 de->file_type |= LDISKFS_DIRENT_LUFID;
4798
4799                 rc = ldiskfs_journal_dirty_metadata(jh, bh);
4800                 if (rc != 0)
4801                         CERROR("%.16s: fail to dirty metadata for reinsert "
4802                                "dirent: name = %.*s, rc = %d\n",
4803                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4804                                ent->oied_namelen, ent->oied_name, rc);
4805
4806                 RETURN(rc);
4807         }
4808
4809         rc = ldiskfs_delete_entry(jh, dir, de, bh);
4810         if (rc != 0) {
4811                 CERROR("%.16s: fail to delete entry for reinsert dirent: "
4812                        "name = %.*s, rc = %d\n",
4813                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4814                        ent->oied_namelen, ent->oied_name, rc);
4815                 RETURN(rc);
4816         }
4817
4818         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
4819                                            ent->oied_namelen);
4820         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
4821         osd_get_ldiskfs_dirent_param(ldp, (const struct dt_rec *)fid);
4822         dentry->d_fsdata = (void *)ldp;
4823         ll_vfs_dq_init(dir);
4824         rc = osd_ldiskfs_add_entry(jh, dentry, inode, hlock);
4825         /* It is too bad, we cannot reinsert the name entry back.
4826          * That means we lose it! */
4827         if (rc != 0)
4828                 CERROR("%.16s: fail to insert entry for reinsert dirent: "
4829                        "name = %.*s, rc = %d\n",
4830                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4831                        ent->oied_namelen, ent->oied_name, rc);
4832
4833         RETURN(rc);
4834 }
4835
4836 static int
4837 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
4838                         struct osd_it_ea *it, struct lu_fid *fid,
4839                         struct osd_inode_id *id, __u32 *attr)
4840 {
4841         struct osd_thread_info     *info        = osd_oti_get(env);
4842         struct lustre_mdt_attrs    *lma         = &info->oti_mdt_attrs;
4843         struct osd_device          *dev         = osd_obj2dev(obj);
4844         struct super_block         *sb          = osd_sb(dev);
4845         const char                 *devname     =
4846                                         LDISKFS_SB(sb)->s_es->s_volume_name;
4847         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
4848         struct inode               *dir         = obj->oo_inode;
4849         struct htree_lock          *hlock       = NULL;
4850         struct buffer_head         *bh          = NULL;
4851         handle_t                   *jh          = NULL;
4852         struct ldiskfs_dir_entry_2 *de;
4853         struct dentry              *dentry;
4854         struct inode               *inode;
4855         int                         credits;
4856         int                         rc;
4857         int                         dot_dotdot  = 0;
4858         bool                        dirty       = false;
4859         ENTRY;
4860
4861         if (ent->oied_name[0] == '.') {
4862                 if (ent->oied_namelen == 1)
4863                         dot_dotdot = 1;
4864                 else if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
4865                         dot_dotdot = 2;
4866         }
4867
4868         dentry = osd_child_dentry_get(env, obj, ent->oied_name,
4869                                       ent->oied_namelen);
4870
4871         /* We need to ensure that the name entry is still valid.
4872          * Because it may be removed or renamed by other already.
4873          *
4874          * The unlink or rename operation will start journal before PDO lock,
4875          * so to avoid deadlock, here we need to start journal handle before
4876          * related PDO lock also. But because we do not know whether there
4877          * will be something to be repaired before PDO lock, we just start
4878          * journal without conditions.
4879          *
4880          * We may need to remove the name entry firstly, then insert back.
4881          * One credit is for user quota file update.
4882          * One credit is for group quota file update.
4883          * Two credits are for dirty inode. */
4884         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
4885                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
4886
4887 again:
4888         if (dev->od_dirent_journal) {
4889                 jh = ldiskfs_journal_start_sb(sb, credits);
4890                 if (IS_ERR(jh)) {
4891                         rc = PTR_ERR(jh);
4892                         CERROR("%.16s: fail to start trans for dirent "
4893                                "check_repair: credits %d, name %.*s, rc %d\n",
4894                                devname, credits, ent->oied_namelen,
4895                                ent->oied_name, rc);
4896                         RETURN(rc);
4897                 }
4898
4899                 if (obj->oo_hl_head != NULL) {
4900                         hlock = osd_oti_get(env)->oti_hlock;
4901                         /* "0" means exclusive lock for the whole directory.
4902                          * We need to prevent others access such name entry
4903                          * during the delete + insert. Neither HLOCK_ADD nor
4904                          * HLOCK_DEL cannot guarantee the atomicity. */
4905                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
4906                 } else {
4907                         down_write(&obj->oo_ext_idx_sem);
4908                 }
4909         } else {
4910                 if (obj->oo_hl_head != NULL) {
4911                         hlock = osd_oti_get(env)->oti_hlock;
4912                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
4913                                            LDISKFS_HLOCK_LOOKUP);
4914                 } else {
4915                         down_read(&obj->oo_ext_idx_sem);
4916                 }
4917         }
4918
4919         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
4920         /* For dot/dotdot entry, if there is not enough space to hold the
4921          * FID-in-dirent, just keep them there. It only happens when the
4922          * device upgraded from 1.8 or restored from MDT file-level backup.
4923          * For the whole directory, only dot/dotdot entry have no FID-in-dirent
4924          * and needs to get FID from LMA when readdir, it will not affect the
4925          * performance much. */
4926         if ((bh == NULL) || (le32_to_cpu(de->inode) != ent->oied_ino) ||
4927             (dot_dotdot != 0 && !osd_dot_dotdot_has_space(de, dot_dotdot))) {
4928                 *attr |= LUDA_IGNORE;
4929                 GOTO(out_journal, rc = 0);
4930         }
4931
4932         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
4933         inode = osd_iget(info, dev, id);
4934         if (IS_ERR(inode)) {
4935                 rc = PTR_ERR(inode);
4936                 if (rc == -ENOENT || rc == -ESTALE) {
4937                         *attr |= LUDA_IGNORE;
4938                         rc = 0;
4939                 }
4940
4941                 GOTO(out_journal, rc);
4942         }
4943
4944         /* skip the REMOTE_PARENT_DIR. */
4945         if (inode == dev->od_mdt_map->omm_remote_parent->d_inode)
4946                 GOTO(out_inode, rc = 0);
4947
4948         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
4949         if (rc == 0) {
4950                 if (fid_is_sane(fid)) {
4951                         /* FID-in-dirent is valid. */
4952                         if (lu_fid_eq(fid, &lma->lma_self_fid))
4953                                 GOTO(out_inode, rc = 0);
4954
4955                         /* Do not repair under dryrun mode. */
4956                         if (*attr & LUDA_VERIFY_DRYRUN) {
4957                                 *attr |= LUDA_REPAIR;
4958                                 GOTO(out_inode, rc = 0);
4959                         }
4960
4961                         if (!dev->od_dirent_journal) {
4962                                 iput(inode);
4963                                 brelse(bh);
4964                                 if (hlock != NULL)
4965                                         ldiskfs_htree_unlock(hlock);
4966                                 else
4967                                         up_read(&obj->oo_ext_idx_sem);
4968                                 dev->od_dirent_journal = 1;
4969                                 goto again;
4970                         }
4971
4972                         *fid = lma->lma_self_fid;
4973                         dirty = true;
4974                         /* Update the FID-in-dirent. */
4975                         rc = osd_dirent_update(jh, sb, ent, fid, bh, de);
4976                         if (rc == 0)
4977                                 *attr |= LUDA_REPAIR;
4978                 } else {
4979                         /* Do not repair under dryrun mode. */
4980                         if (*attr & LUDA_VERIFY_DRYRUN) {
4981                                 *fid = lma->lma_self_fid;
4982                                 *attr |= LUDA_REPAIR;
4983                                 GOTO(out_inode, rc = 0);
4984                         }
4985
4986                         if (!dev->od_dirent_journal) {
4987                                 iput(inode);
4988                                 brelse(bh);
4989                                 if (hlock != NULL)
4990                                         ldiskfs_htree_unlock(hlock);
4991                                 else
4992                                         up_read(&obj->oo_ext_idx_sem);
4993                                 dev->od_dirent_journal = 1;
4994                                 goto again;
4995                         }
4996
4997                         *fid = lma->lma_self_fid;
4998                         dirty = true;
4999                         /* Append the FID-in-dirent. */
5000                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5001                                                  fid, bh, de, hlock);
5002                         if (rc == 0)
5003                                 *attr |= LUDA_REPAIR;
5004                 }
5005         } else if (rc == -ENODATA) {
5006                 /* Do not repair under dryrun mode. */
5007                 if (*attr & LUDA_VERIFY_DRYRUN) {
5008                         if (fid_is_sane(fid)) {
5009                                 *attr |= LUDA_REPAIR;
5010                         } else {
5011                                 lu_igif_build(fid, inode->i_ino,
5012                                               inode->i_generation);
5013                                 *attr |= LUDA_UPGRADE;
5014                         }
5015                         GOTO(out_inode, rc = 0);
5016                 }
5017
5018                 if (!dev->od_dirent_journal) {
5019                         iput(inode);
5020                         brelse(bh);
5021                         if (hlock != NULL)
5022                                 ldiskfs_htree_unlock(hlock);
5023                         else
5024                                 up_read(&obj->oo_ext_idx_sem);
5025                         dev->od_dirent_journal = 1;
5026                         goto again;
5027                 }
5028
5029                 dirty = true;
5030                 if (unlikely(fid_is_sane(fid))) {
5031                         /* FID-in-dirent exists, but FID-in-LMA is lost.
5032                          * Trust the FID-in-dirent, and add FID-in-LMA. */
5033                         rc = osd_ea_fid_set(info, inode, fid, 0);
5034                         if (rc == 0)
5035                                 *attr |= LUDA_REPAIR;
5036                 } else {
5037                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
5038                         /* It is probably IGIF object. Only aappend the
5039                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
5040                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5041                                                  fid, bh, de, hlock);
5042                         if (rc == 0)
5043                                 *attr |= LUDA_UPGRADE;
5044                 }
5045         }
5046
5047         GOTO(out_inode, rc);
5048
5049 out_inode:
5050         iput(inode);
5051
5052 out_journal:
5053         brelse(bh);
5054         if (hlock != NULL) {
5055                 ldiskfs_htree_unlock(hlock);
5056         } else {
5057                 if (dev->od_dirent_journal)
5058                         up_write(&obj->oo_ext_idx_sem);
5059                 else
5060                         up_read(&obj->oo_ext_idx_sem);
5061         }
5062         if (jh != NULL)
5063                 ldiskfs_journal_stop(jh);
5064         if (rc >= 0 && !dirty)
5065                 dev->od_dirent_journal = 0;
5066         return rc;
5067 }
5068
5069 /**
5070  * Returns the value at current position from iterator's in memory structure.
5071  *
5072  * \param di struct osd_it_ea, iterator's in memory structure
5073  * \param attr attr requested for dirent.
5074  * \param lde lustre dirent
5075  *
5076  * \retval   0 no error and \param lde has correct lustre dirent.
5077  * \retval -ve on error
5078  */
5079 static inline int osd_it_ea_rec(const struct lu_env *env,
5080                                 const struct dt_it *di,
5081                                 struct dt_rec *dtrec, __u32 attr)
5082 {
5083         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
5084         struct osd_object      *obj   = it->oie_obj;
5085         struct osd_device      *dev   = osd_obj2dev(obj);
5086         struct osd_scrub       *scrub = &dev->od_scrub;
5087         struct scrub_file      *sf    = &scrub->os_file;
5088         struct osd_thread_info *oti   = osd_oti_get(env);
5089         struct osd_inode_id    *id    = &oti->oti_id;
5090         struct osd_idmap_cache *oic   = &oti->oti_cache;
5091         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
5092         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
5093         __u32                   ino   = it->oie_dirent->oied_ino;
5094         int                     rc    = 0;
5095         ENTRY;
5096
5097         if (attr & LUDA_VERIFY) {
5098                 attr |= LUDA_TYPE;
5099                 if (unlikely(ino == osd_sb(dev)->s_root->d_inode->i_ino)) {
5100                         attr |= LUDA_IGNORE;
5101                         rc = 0;
5102                 } else {
5103                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
5104                                                      &attr);
5105                 }
5106         } else {
5107                 attr &= ~LU_DIRENT_ATTRS_MASK;
5108                 if (!fid_is_sane(fid)) {
5109                         if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
5110                                 RETURN(-ENOENT);
5111
5112                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
5113                 } else {
5114                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5115                 }
5116         }
5117
5118         /* Pack the entry anyway, at least the offset is right. */
5119         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
5120                            it->oie_dirent->oied_name,
5121                            it->oie_dirent->oied_namelen,
5122                            it->oie_dirent->oied_type, attr);
5123
5124         if (rc < 0)
5125                 RETURN(rc);
5126
5127         if (osd_remote_fid(env, dev, fid))
5128                 RETURN(0);
5129
5130         if (likely(!(attr & LUDA_IGNORE)))
5131                 rc = osd_add_oi_cache(oti, dev, id, fid);
5132
5133         if (!(attr & LUDA_VERIFY) &&
5134             (scrub->os_pos_current <= ino) &&
5135             ((sf->sf_flags & SF_INCONSISTENT) ||
5136              (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
5137              ldiskfs_test_bit(osd_oi_fid2idx(dev, fid), sf->sf_oi_bitmap)))
5138                 osd_consistency_check(oti, dev, oic);
5139
5140         RETURN(rc);
5141 }
5142
5143 /**
5144  * Returns a cookie for current position of the iterator head, so that
5145  * user can use this cookie to load/start the iterator next time.
5146  *
5147  * \param di iterator's in memory structure
5148  *
5149  * \retval cookie for current position, on success
5150  */
5151 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
5152 {
5153         struct osd_it_ea *it = (struct osd_it_ea *)di;
5154
5155         return it->oie_dirent->oied_off;
5156 }
5157
5158 /**
5159  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5160  * to load a directory entry at a time and stored it i inn,
5161  * in iterator's in-memory data structure.
5162  *
5163  * \param di struct osd_it_ea, iterator's in memory structure
5164  *
5165  * \retval +ve on success
5166  * \retval -ve on error
5167  */
5168 static int osd_it_ea_load(const struct lu_env *env,
5169                           const struct dt_it *di, __u64 hash)
5170 {
5171         struct osd_it_ea *it = (struct osd_it_ea *)di;
5172         int rc;
5173
5174         ENTRY;
5175         it->oie_file.f_pos = hash;
5176
5177         rc =  osd_ldiskfs_it_fill(env, di);
5178         if (rc == 0)
5179                 rc = +1;
5180
5181         RETURN(rc);
5182 }
5183
5184 /**
5185  * Index lookup function for interoperability mode (b11826).
5186  *
5187  * \param key,  key i.e. file name to be searched
5188  *
5189  * \retval +ve, on success
5190  * \retval -ve, on error
5191  */
5192 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
5193                                struct dt_rec *rec, const struct dt_key *key,
5194                                struct lustre_capa *capa)
5195 {
5196         struct osd_object *obj = osd_dt_obj(dt);
5197         int rc = 0;
5198
5199         ENTRY;
5200
5201         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
5202         LINVRNT(osd_invariant(obj));
5203
5204         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
5205                 return -EACCES;
5206
5207         rc = osd_ea_lookup_rec(env, obj, rec, key);
5208         if (rc == 0)
5209                 rc = +1;
5210         RETURN(rc);
5211 }
5212
5213 /**
5214  * Index and Iterator operations for interoperability
5215  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
5216  */
5217 static const struct dt_index_operations osd_index_ea_ops = {
5218         .dio_lookup         = osd_index_ea_lookup,
5219         .dio_declare_insert = osd_index_declare_ea_insert,
5220         .dio_insert         = osd_index_ea_insert,
5221         .dio_declare_delete = osd_index_declare_ea_delete,
5222         .dio_delete         = osd_index_ea_delete,
5223         .dio_it     = {
5224                 .init     = osd_it_ea_init,
5225                 .fini     = osd_it_ea_fini,
5226                 .get      = osd_it_ea_get,
5227                 .put      = osd_it_ea_put,
5228                 .next     = osd_it_ea_next,
5229                 .key      = osd_it_ea_key,
5230                 .key_size = osd_it_ea_key_size,
5231                 .rec      = osd_it_ea_rec,
5232                 .store    = osd_it_ea_store,
5233                 .load     = osd_it_ea_load
5234         }
5235 };
5236
5237 static void *osd_key_init(const struct lu_context *ctx,
5238                           struct lu_context_key *key)
5239 {
5240         struct osd_thread_info *info;
5241
5242         OBD_ALLOC_PTR(info);
5243         if (info == NULL)
5244                 return ERR_PTR(-ENOMEM);
5245
5246         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5247         if (info->oti_it_ea_buf == NULL)
5248                 goto out_free_info;
5249
5250         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
5251
5252         info->oti_hlock = ldiskfs_htree_lock_alloc();
5253         if (info->oti_hlock == NULL)
5254                 goto out_free_ea;
5255
5256         return info;
5257
5258  out_free_ea:
5259         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5260  out_free_info:
5261         OBD_FREE_PTR(info);
5262         return ERR_PTR(-ENOMEM);
5263 }
5264
5265 static void osd_key_fini(const struct lu_context *ctx,
5266                          struct lu_context_key *key, void* data)
5267 {
5268         struct osd_thread_info *info = data;
5269
5270         if (info->oti_hlock != NULL)
5271                 ldiskfs_htree_lock_free(info->oti_hlock);
5272         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5273         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
5274         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
5275         OBD_FREE_PTR(info);
5276 }
5277
5278 static void osd_key_exit(const struct lu_context *ctx,
5279                          struct lu_context_key *key, void *data)
5280 {
5281         struct osd_thread_info *info = data;
5282
5283         LASSERT(info->oti_r_locks == 0);
5284         LASSERT(info->oti_w_locks == 0);
5285         LASSERT(info->oti_txns    == 0);
5286 }
5287
5288 /* type constructor/destructor: osd_type_init, osd_type_fini */
5289 LU_TYPE_INIT_FINI(osd, &osd_key);
5290
5291 struct lu_context_key osd_key = {
5292         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
5293         .lct_init = osd_key_init,
5294         .lct_fini = osd_key_fini,
5295         .lct_exit = osd_key_exit
5296 };
5297
5298
5299 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
5300                            const char *name, struct lu_device *next)
5301 {
5302         struct osd_device *osd = osd_dev(d);
5303
5304         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
5305             >= sizeof(osd->od_svname))
5306                 return -E2BIG;
5307         return osd_procfs_init(osd, name);
5308 }
5309
5310 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
5311 {
5312         ENTRY;
5313
5314         /* shutdown quota slave instance associated with the device */
5315         if (o->od_quota_slave != NULL) {
5316                 qsd_fini(env, o->od_quota_slave);
5317                 o->od_quota_slave = NULL;
5318         }
5319
5320         RETURN(0);
5321 }
5322
5323 static void osd_umount(const struct lu_env *env, struct osd_device *o)
5324 {
5325         ENTRY;
5326
5327         if (o->od_fsops) {
5328                 fsfilt_put_ops(o->od_fsops);
5329                 o->od_fsops = NULL;
5330         }
5331
5332         if (o->od_mnt != NULL) {
5333                 shrink_dcache_sb(osd_sb(o));
5334                 osd_sync(env, &o->od_dt_dev);
5335
5336                 mntput(o->od_mnt);
5337                 o->od_mnt = NULL;
5338         }
5339
5340         EXIT;
5341 }
5342
5343 static int osd_mount(const struct lu_env *env,
5344                      struct osd_device *o, struct lustre_cfg *cfg)
5345 {
5346         const char              *name  = lustre_cfg_string(cfg, 0);
5347         const char              *dev  = lustre_cfg_string(cfg, 1);
5348         const char              *opts;
5349         unsigned long            page, s_flags, lmd_flags = 0;
5350         struct page             *__page;
5351         struct file_system_type *type;
5352         char                    *options = NULL;
5353         char                    *str;
5354         int                       rc = 0;
5355         ENTRY;
5356
5357         if (o->od_mnt != NULL)
5358                 RETURN(0);
5359
5360         if (strlen(dev) >= sizeof(o->od_mntdev))
5361                 RETURN(-E2BIG);
5362         strcpy(o->od_mntdev, dev);
5363
5364         o->od_fsops = fsfilt_get_ops(mt_str(LDD_MT_LDISKFS));
5365         if (IS_ERR(o->od_fsops)) {
5366                 CERROR("%s: Can't find fsfilt_ldiskfs\n", name);
5367                 o->od_fsops = NULL;
5368                 RETURN(-ENOTSUPP);
5369         }
5370
5371         OBD_PAGE_ALLOC(__page, GFP_IOFS);
5372         if (__page == NULL)
5373                 GOTO(out, rc = -ENOMEM);
5374
5375         str = lustre_cfg_string(cfg, 2);
5376         s_flags = simple_strtoul(str, NULL, 0);
5377         str = strstr(str, ":");
5378         if (str)
5379                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
5380         opts = lustre_cfg_string(cfg, 3);
5381         page = (unsigned long)page_address(__page);
5382         options = (char *)page;
5383         *options = '\0';
5384         if (opts == NULL)
5385                 strcat(options, "user_xattr,acl");
5386         else
5387                 strcat(options, opts);
5388
5389         /* Glom up mount options */
5390         if (*options != '\0')
5391                 strcat(options, ",");
5392         strlcat(options, "no_mbcache", PAGE_CACHE_SIZE);
5393
5394         type = get_fs_type("ldiskfs");
5395         if (!type) {
5396                 CERROR("%s: cannot find ldiskfs module\n", name);
5397                 GOTO(out, rc = -ENODEV);
5398         }
5399
5400         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
5401         cfs_module_put(type->owner);
5402
5403         if (IS_ERR(o->od_mnt)) {
5404                 rc = PTR_ERR(o->od_mnt);
5405                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
5406                 o->od_mnt = NULL;
5407                 GOTO(out, rc);
5408         }
5409
5410 #ifdef HAVE_DEV_SET_RDONLY
5411         if (dev_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
5412                 CERROR("%s: underlying device %s is marked as read-only. "
5413                        "Setup failed\n", name, dev);
5414                 mntput(o->od_mnt);
5415                 o->od_mnt = NULL;
5416                 GOTO(out, rc = -EROFS);
5417         }
5418 #endif
5419
5420         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
5421             LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
5422                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
5423                 mntput(o->od_mnt);
5424                 o->od_mnt = NULL;
5425                 GOTO(out, rc = -EINVAL);
5426         }
5427
5428         ldiskfs_set_inode_state(osd_sb(o)->s_root->d_inode,
5429                                 LDISKFS_STATE_LUSTRE_NO_OI);
5430         if (lmd_flags & LMD_FLG_NOSCRUB)
5431                 o->od_noscrub = 1;
5432
5433 out:
5434         if (__page)
5435                 OBD_PAGE_FREE(__page);
5436         if (rc)
5437                 fsfilt_put_ops(o->od_fsops);
5438
5439         RETURN(rc);
5440 }
5441
5442 static struct lu_device *osd_device_fini(const struct lu_env *env,
5443                                          struct lu_device *d)
5444 {
5445         struct osd_device *o = osd_dev(d);
5446         ENTRY;
5447
5448         osd_procfs_fini(o);
5449         osd_shutdown(env, o);
5450         osd_scrub_cleanup(env, o);
5451         osd_obj_map_fini(o);
5452         osd_umount(env, o);
5453
5454         RETURN(NULL);
5455 }
5456
5457 static int osd_device_init0(const struct lu_env *env,
5458                             struct osd_device *o,
5459                             struct lustre_cfg *cfg)
5460 {
5461         struct lu_device        *l = osd2lu_dev(o);
5462         struct osd_thread_info *info;
5463         int                     rc;
5464         int                     cplen = 0;
5465
5466         /* if the module was re-loaded, env can loose its keys */
5467         rc = lu_env_refill((struct lu_env *) env);
5468         if (rc)
5469                 GOTO(out, rc);
5470         info = osd_oti_get(env);
5471         LASSERT(info);
5472
5473         l->ld_ops = &osd_lu_ops;
5474         o->od_dt_dev.dd_ops = &osd_dt_ops;
5475
5476         spin_lock_init(&o->od_osfs_lock);
5477         mutex_init(&o->od_otable_mutex);
5478         o->od_osfs_age = cfs_time_shift_64(-1000);
5479
5480         o->od_capa_hash = init_capa_hash();
5481         if (o->od_capa_hash == NULL)
5482                 GOTO(out, rc = -ENOMEM);
5483
5484         o->od_read_cache = 1;
5485         o->od_writethrough_cache = 1;
5486         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
5487
5488         rc = osd_mount(env, o, cfg);
5489         if (rc)
5490                 GOTO(out_capa, rc);
5491
5492         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
5493                         sizeof(o->od_svname));
5494         if (cplen >= sizeof(o->od_svname)) {
5495                 rc = -E2BIG;
5496                 GOTO(out_mnt, rc);
5497         }
5498
5499         rc = osd_obj_map_init(env, o);
5500         if (rc != 0)
5501                 GOTO(out_mnt, rc);
5502
5503         rc = lu_site_init(&o->od_site, l);
5504         if (rc != 0)
5505                 GOTO(out_compat, rc);
5506         o->od_site.ls_bottom_dev = l;
5507
5508         rc = lu_site_init_finish(&o->od_site);
5509         if (rc != 0)
5510                 GOTO(out_site, rc);
5511
5512         CFS_INIT_LIST_HEAD(&o->od_ios_list);
5513         /* setup scrub, including OI files initialization */
5514         rc = osd_scrub_setup(env, o);
5515         if (rc < 0)
5516                 GOTO(out_site, rc);
5517
5518         rc = osd_procfs_init(o, o->od_svname);
5519         if (rc != 0) {
5520                 CERROR("%s: can't initialize procfs: rc = %d\n",
5521                        o->od_svname, rc);
5522                 GOTO(out_scrub, rc);
5523         }
5524
5525         LASSERT(l->ld_site->ls_linkage.next && l->ld_site->ls_linkage.prev);
5526
5527         /* initialize quota slave instance */
5528         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
5529                                      o->od_proc_entry);
5530         if (IS_ERR(o->od_quota_slave)) {
5531                 rc = PTR_ERR(o->od_quota_slave);
5532                 o->od_quota_slave = NULL;
5533                 GOTO(out_procfs, rc);
5534         }
5535
5536         RETURN(0);
5537
5538 out_procfs:
5539         osd_procfs_fini(o);
5540 out_scrub:
5541         osd_scrub_cleanup(env, o);
5542 out_site:
5543         lu_site_fini(&o->od_site);
5544 out_compat:
5545         osd_obj_map_fini(o);
5546 out_mnt:
5547         osd_umount(env, o);
5548 out_capa:
5549         cleanup_capa_hash(o->od_capa_hash);
5550 out:
5551         return rc;
5552 }
5553
5554 static struct lu_device *osd_device_alloc(const struct lu_env *env,
5555                                           struct lu_device_type *t,
5556                                           struct lustre_cfg *cfg)
5557 {
5558         struct osd_device *o;
5559         int                rc;
5560
5561         OBD_ALLOC_PTR(o);
5562         if (o == NULL)
5563                 return ERR_PTR(-ENOMEM);
5564
5565         rc = dt_device_init(&o->od_dt_dev, t);
5566         if (rc == 0) {
5567                 /* Because the ctx might be revived in dt_device_init,
5568                  * refill the env here */
5569                 lu_env_refill((struct lu_env *)env);
5570                 rc = osd_device_init0(env, o, cfg);
5571                 if (rc)
5572                         dt_device_fini(&o->od_dt_dev);
5573         }
5574
5575         if (unlikely(rc != 0))
5576                 OBD_FREE_PTR(o);
5577
5578         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
5579 }
5580
5581 static struct lu_device *osd_device_free(const struct lu_env *env,
5582                                          struct lu_device *d)
5583 {
5584         struct osd_device *o = osd_dev(d);
5585         ENTRY;
5586
5587         cleanup_capa_hash(o->od_capa_hash);
5588         /* XXX: make osd top device in order to release reference */
5589         d->ld_site->ls_top_dev = d;
5590         lu_site_purge(env, d->ld_site, -1);
5591         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
5592                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
5593                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
5594         }
5595         lu_site_fini(&o->od_site);
5596         dt_device_fini(&o->od_dt_dev);
5597         OBD_FREE_PTR(o);
5598         RETURN(NULL);
5599 }
5600
5601 static int osd_process_config(const struct lu_env *env,
5602                               struct lu_device *d, struct lustre_cfg *cfg)
5603 {
5604         struct osd_device *o = osd_dev(d);
5605         int err;
5606         ENTRY;
5607
5608         switch(cfg->lcfg_command) {
5609         case LCFG_SETUP:
5610                 err = osd_mount(env, o, cfg);
5611                 break;
5612         case LCFG_CLEANUP:
5613                 lu_dev_del_linkage(d->ld_site, d);
5614                 err = osd_shutdown(env, o);
5615                 break;
5616         default:
5617                 err = -ENOSYS;
5618         }
5619
5620         RETURN(err);
5621 }
5622
5623 static int osd_recovery_complete(const struct lu_env *env,
5624                                  struct lu_device *d)
5625 {
5626         struct osd_device       *osd = osd_dev(d);
5627         int                      rc = 0;
5628         ENTRY;
5629
5630         if (osd->od_quota_slave == NULL)
5631                 RETURN(0);
5632
5633         /* start qsd instance on recovery completion, this notifies the quota
5634          * slave code that we are about to process new requests now */
5635         rc = qsd_start(env, osd->od_quota_slave);
5636         RETURN(rc);
5637 }
5638
5639 /*
5640  * we use exports to track all osd users
5641  */
5642 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
5643                            struct obd_device *obd, struct obd_uuid *cluuid,
5644                            struct obd_connect_data *data, void *localdata)
5645 {
5646         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
5647         struct lustre_handle  conn;
5648         int                   rc;
5649         ENTRY;
5650
5651         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
5652
5653         rc = class_connect(&conn, obd, cluuid);
5654         if (rc)
5655                 RETURN(rc);
5656
5657         *exp = class_conn2export(&conn);
5658
5659         spin_lock(&osd->od_osfs_lock);
5660         osd->od_connects++;
5661         spin_unlock(&osd->od_osfs_lock);
5662
5663         RETURN(0);
5664 }
5665
5666 /*
5667  * once last export (we don't count self-export) disappeared
5668  * osd can be released
5669  */
5670 static int osd_obd_disconnect(struct obd_export *exp)
5671 {
5672         struct obd_device *obd = exp->exp_obd;
5673         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
5674         int                rc, release = 0;
5675         ENTRY;
5676
5677         /* Only disconnect the underlying layers on the final disconnect. */
5678         spin_lock(&osd->od_osfs_lock);
5679         osd->od_connects--;
5680         if (osd->od_connects == 0)
5681                 release = 1;
5682         spin_unlock(&osd->od_osfs_lock);
5683
5684         rc = class_disconnect(exp); /* bz 9811 */
5685
5686         if (rc == 0 && release)
5687                 class_manual_cleanup(obd);
5688         RETURN(rc);
5689 }
5690
5691 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
5692                        struct lu_device *dev)
5693 {
5694         struct osd_device *osd = osd_dev(dev);
5695         int                result = 0;
5696         ENTRY;
5697
5698         if (osd->od_quota_slave != NULL)
5699                 /* set up quota slave objects */
5700                 result = qsd_prepare(env, osd->od_quota_slave);
5701
5702         RETURN(result);
5703 }
5704
5705 static const struct lu_object_operations osd_lu_obj_ops = {
5706         .loo_object_init      = osd_object_init,
5707         .loo_object_delete    = osd_object_delete,
5708         .loo_object_release   = osd_object_release,
5709         .loo_object_free      = osd_object_free,
5710         .loo_object_print     = osd_object_print,
5711         .loo_object_invariant = osd_object_invariant
5712 };
5713
5714 const struct lu_device_operations osd_lu_ops = {
5715         .ldo_object_alloc      = osd_object_alloc,
5716         .ldo_process_config    = osd_process_config,
5717         .ldo_recovery_complete = osd_recovery_complete,
5718         .ldo_prepare           = osd_prepare,
5719 };
5720
5721 static const struct lu_device_type_operations osd_device_type_ops = {
5722         .ldto_init = osd_type_init,
5723         .ldto_fini = osd_type_fini,
5724
5725         .ldto_start = osd_type_start,
5726         .ldto_stop  = osd_type_stop,
5727
5728         .ldto_device_alloc = osd_device_alloc,
5729         .ldto_device_free  = osd_device_free,
5730
5731         .ldto_device_init    = osd_device_init,
5732         .ldto_device_fini    = osd_device_fini
5733 };
5734
5735 struct lu_device_type osd_device_type = {
5736         .ldt_tags     = LU_DEVICE_DT,
5737         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
5738         .ldt_ops      = &osd_device_type_ops,
5739         .ldt_ctx_tags = LCT_LOCAL,
5740 };
5741
5742 /*
5743  * lprocfs legacy support.
5744  */
5745 static struct obd_ops osd_obd_device_ops = {
5746         .o_owner = THIS_MODULE,
5747         .o_connect      = osd_obd_connect,
5748         .o_disconnect   = osd_obd_disconnect
5749 };
5750
5751 static int __init osd_mod_init(void)
5752 {
5753         struct lprocfs_static_vars lvars;
5754
5755         osd_oi_mod_init();
5756         lprocfs_osd_init_vars(&lvars);
5757         return class_register_type(&osd_obd_device_ops, NULL, lvars.module_vars,
5758                                    LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
5759 }
5760
5761 static void __exit osd_mod_exit(void)
5762 {
5763         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
5764 }
5765
5766 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
5767 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
5768 MODULE_LICENSE("GPL");
5769
5770 cfs_module(osd, "0.1.0", osd_mod_init, osd_mod_exit);