Whamcloud - gitweb
aca8fc71f807f89f03b7fe1036b51c8062190de6
[fs/lustre-release.git] / lustre / lod / lod_qos.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright  2009 Sun Microsystems, Inc. All rights reserved
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/lod/lod_qos.c
33  *
34  * Implementation of different allocation algorithm used
35  * to distribute objects and data among OSTs.
36  */
37
38 #define DEBUG_SUBSYSTEM S_LOV
39
40 #include <asm/div64.h>
41 #include <libcfs/libcfs.h>
42 #include <uapi/linux/lustre/lustre_idl.h>
43 #include <lustre_swab.h>
44 #include <obd_class.h>
45
46 #include "lod_internal.h"
47
48 /*
49  * force QoS policy (not RR) to be used for testing purposes
50  */
51 #define FORCE_QOS_
52
53 #define D_QOS   D_OTHER
54
55 #define QOS_DEBUG(fmt, ...)     CDEBUG(D_QOS, fmt, ## __VA_ARGS__)
56 #define QOS_CONSOLE(fmt, ...)   LCONSOLE(D_QOS, fmt, ## __VA_ARGS__)
57
58 #define TGT_BAVAIL(i) (OST_TGT(lod,i)->ltd_statfs.os_bavail * \
59                        OST_TGT(lod,i)->ltd_statfs.os_bsize)
60
61 /**
62  * Check whether the target is available for new OST objects.
63  *
64  * Request statfs data from the given target and verify it's active and not
65  * read-only. If so, then it can be used to place new OST objects. This
66  * function also maintains the number of active/inactive targets and sets
67  * dirty flags if those numbers change so others can run re-balance procedures.
68  * No external locking is required.
69  *
70  * \param[in] env       execution environment for this thread
71  * \param[in] d         LOD device
72  * \param[in] index     index of OST target to check
73  * \param[out] sfs      buffer for statfs data
74  *
75  * \retval 0            if the target is good
76  * \retval negative     negated errno on error
77
78  */
79 static int lod_statfs_and_check(const struct lu_env *env, struct lod_device *d,
80                                 int index, struct obd_statfs *sfs)
81 {
82         struct lod_tgt_desc *ost;
83         int                  rc;
84         ENTRY;
85
86         LASSERT(d);
87         ost = OST_TGT(d,index);
88         LASSERT(ost);
89
90         rc = dt_statfs(env, ost->ltd_ost, sfs);
91
92         if (rc == 0 && ((sfs->os_state & OS_STATE_ENOSPC) ||
93             (sfs->os_state & OS_STATE_ENOINO && sfs->os_fprecreated == 0)))
94                 RETURN(-ENOSPC);
95
96         if (rc && rc != -ENOTCONN)
97                 CERROR("%s: statfs: rc = %d\n", lod2obd(d)->obd_name, rc);
98
99         /* If the OST is readonly then we can't allocate objects there */
100         if (sfs->os_state & OS_STATE_READONLY)
101                 rc = -EROFS;
102
103         /* object precreation is skipped on the OST with max_create_count=0 */
104         if (sfs->os_state & OS_STATE_NOPRECREATE)
105                 rc = -ENOBUFS;
106
107         /* check whether device has changed state (active, inactive) */
108         if (rc != 0 && ost->ltd_active) {
109                 /* turned inactive? */
110                 spin_lock(&d->lod_lock);
111                 if (ost->ltd_active) {
112                         ost->ltd_active = 0;
113                         if (rc == -ENOTCONN)
114                                 ost->ltd_connecting = 1;
115
116                         LASSERT(d->lod_desc.ld_active_tgt_count > 0);
117                         d->lod_desc.ld_active_tgt_count--;
118                         d->lod_qos.lq_dirty = 1;
119                         d->lod_qos.lq_rr.lqr_dirty = 1;
120                         CDEBUG(D_CONFIG, "%s: turns inactive\n",
121                                ost->ltd_exp->exp_obd->obd_name);
122                 }
123                 spin_unlock(&d->lod_lock);
124         } else if (rc == 0 && ost->ltd_active == 0) {
125                 /* turned active? */
126                 LASSERTF(d->lod_desc.ld_active_tgt_count < d->lod_ostnr,
127                          "active tgt count %d, ost nr %d\n",
128                          d->lod_desc.ld_active_tgt_count, d->lod_ostnr);
129                 spin_lock(&d->lod_lock);
130                 if (ost->ltd_active == 0) {
131                         ost->ltd_active = 1;
132                         ost->ltd_connecting = 0;
133                         d->lod_desc.ld_active_tgt_count++;
134                         d->lod_qos.lq_dirty = 1;
135                         d->lod_qos.lq_rr.lqr_dirty = 1;
136                         CDEBUG(D_CONFIG, "%s: turns active\n",
137                                ost->ltd_exp->exp_obd->obd_name);
138                 }
139                 spin_unlock(&d->lod_lock);
140         }
141
142         RETURN(rc);
143 }
144
145 /**
146  * Maintain per-target statfs data.
147  *
148  * The function refreshes statfs data for all the targets every N seconds.
149  * The actual N is controlled via procfs and set to LOV_DESC_QOS_MAXAGE_DEFAULT
150  * initially.
151  *
152  * \param[in] env       execution environment for this thread
153  * \param[in] lod       LOD device
154  */
155 void lod_qos_statfs_update(const struct lu_env *env, struct lod_device *lod)
156 {
157         struct obd_device *obd = lod2obd(lod);
158         struct ost_pool *osts = &(lod->lod_pool_info);
159         time64_t max_age;
160         unsigned int i;
161         u64 avail;
162         int idx;
163         ENTRY;
164
165         max_age = ktime_get_seconds() - 2 * lod->lod_desc.ld_qos_maxage;
166
167         if (obd->obd_osfs_age > max_age)
168                 /* statfs data are quite recent, don't need to refresh it */
169                 RETURN_EXIT;
170
171         down_write(&lod->lod_qos.lq_rw_sem);
172
173         if (obd->obd_osfs_age > max_age)
174                 goto out;
175
176         for (i = 0; i < osts->op_count; i++) {
177                 idx = osts->op_array[i];
178                 avail = OST_TGT(lod,idx)->ltd_statfs.os_bavail;
179                 if (lod_statfs_and_check(env, lod, idx,
180                                          &OST_TGT(lod, idx)->ltd_statfs))
181                         continue;
182                 if (OST_TGT(lod,idx)->ltd_statfs.os_bavail != avail)
183                         /* recalculate weigths */
184                         lod->lod_qos.lq_dirty = 1;
185         }
186         obd->obd_osfs_age = ktime_get_seconds();
187
188 out:
189         up_write(&lod->lod_qos.lq_rw_sem);
190         EXIT;
191 }
192
193 /**
194  * Calculate per-OST and per-OSS penalties
195  *
196  * Re-calculate penalties when the configuration changes, active targets
197  * change and after statfs refresh (all these are reflected by lq_dirty flag).
198  * On every OST and OSS: decay the penalty by half for every 8x the update
199  * interval that the device has been idle. That gives lots of time for the
200  * statfs information to be updated (which the penalty is only a proxy for),
201  * and avoids penalizing OSS/OSTs under light load.
202  * See lod_qos_calc_weight() for how penalties are factored into the weight.
203  *
204  * \param[in] lod       LOD device
205  *
206  * \retval 0            on success
207  * \retval -EAGAIN      the number of OSTs isn't enough
208  */
209 static int lod_qos_calc_ppo(struct lod_device *lod)
210 {
211         struct lu_svr_qos *oss;
212         __u64 ba_max, ba_min, temp;
213         __u32 num_active;
214         unsigned int i;
215         int rc, prio_wide;
216         time64_t now, age;
217
218         ENTRY;
219
220         if (!lod->lod_qos.lq_dirty)
221                 GOTO(out, rc = 0);
222
223         num_active = lod->lod_desc.ld_active_tgt_count - 1;
224         if (num_active < 1)
225                 GOTO(out, rc = -EAGAIN);
226
227         /* find bavail on each OSS */
228         list_for_each_entry(oss, &lod->lod_qos.lq_svr_list, lsq_svr_list)
229                 oss->lsq_bavail = 0;
230         lod->lod_qos.lq_active_svr_count = 0;
231
232         /*
233          * How badly user wants to select OSTs "widely" (not recently chosen
234          * and not on recent OSS's).  As opposed to "freely" (free space
235          * avail.) 0-256
236          */
237         prio_wide = 256 - lod->lod_qos.lq_prio_free;
238
239         ba_min = (__u64)(-1);
240         ba_max = 0;
241         now = ktime_get_real_seconds();
242         /* Calculate OST penalty per object
243          * (lod ref taken in lod_qos_prep_create())
244          */
245         cfs_foreach_bit(lod->lod_ost_bitmap, i) {
246                 LASSERT(OST_TGT(lod,i));
247                 temp = TGT_BAVAIL(i);
248                 if (!temp)
249                         continue;
250                 ba_min = min(temp, ba_min);
251                 ba_max = max(temp, ba_max);
252
253                 /* Count the number of usable OSS's */
254                 if (OST_TGT(lod, i)->ltd_qos.ltq_svr->lsq_bavail == 0)
255                         lod->lod_qos.lq_active_svr_count++;
256                 OST_TGT(lod, i)->ltd_qos.ltq_svr->lsq_bavail += temp;
257
258                 /* per-OST penalty is prio * TGT_bavail / (num_ost - 1) / 2 */
259                 temp >>= 1;
260                 do_div(temp, num_active);
261                 OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj =
262                         (temp * prio_wide) >> 8;
263
264                 age = (now - OST_TGT(lod,i)->ltd_qos.ltq_used) >> 3;
265                 if (lod->lod_qos.lq_reset ||
266                     age > 32 * lod->lod_desc.ld_qos_maxage)
267                         OST_TGT(lod,i)->ltd_qos.ltq_penalty = 0;
268                 else if (age > lod->lod_desc.ld_qos_maxage)
269                         /* Decay OST penalty. */
270                         OST_TGT(lod,i)->ltd_qos.ltq_penalty >>=
271                                 (age / lod->lod_desc.ld_qos_maxage);
272         }
273
274         num_active = lod->lod_qos.lq_active_svr_count - 1;
275         if (num_active < 1) {
276                 /* If there's only 1 OSS, we can't penalize it, so instead
277                    we have to double the OST penalty */
278                 num_active = 1;
279                 cfs_foreach_bit(lod->lod_ost_bitmap, i)
280                         OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj <<= 1;
281         }
282
283         /* Per-OSS penalty is prio * oss_avail / oss_osts / (num_oss - 1) / 2 */
284         list_for_each_entry(oss, &lod->lod_qos.lq_svr_list, lsq_svr_list) {
285                 temp = oss->lsq_bavail >> 1;
286                 do_div(temp, oss->lsq_tgt_count * num_active);
287                 oss->lsq_penalty_per_obj = (temp * prio_wide) >> 8;
288
289                 age = (now - oss->lsq_used) >> 3;
290                 if (lod->lod_qos.lq_reset ||
291                     age > 32 * lod->lod_desc.ld_qos_maxage)
292                         oss->lsq_penalty = 0;
293                 else if (age > lod->lod_desc.ld_qos_maxage)
294                         /* Decay OSS penalty. */
295                         oss->lsq_penalty >>= age / lod->lod_desc.ld_qos_maxage;
296         }
297
298         lod->lod_qos.lq_dirty = 0;
299         lod->lod_qos.lq_reset = 0;
300
301         /* If each ost has almost same free space,
302          * do rr allocation for better creation performance */
303         lod->lod_qos.lq_same_space = 0;
304         if ((ba_max * (256 - lod->lod_qos.lq_threshold_rr)) >> 8 < ba_min) {
305                 lod->lod_qos.lq_same_space = 1;
306                 /* Reset weights for the next time we enter qos mode */
307                 lod->lod_qos.lq_reset = 1;
308         }
309         rc = 0;
310
311 out:
312 #ifndef FORCE_QOS
313         if (!rc && lod->lod_qos.lq_same_space)
314                 RETURN(-EAGAIN);
315 #endif
316         RETURN(rc);
317 }
318
319 /**
320  * Calculate weight for a given OST target.
321  *
322  * The final OST weight is the number of bytes available minus the OST and
323  * OSS penalties.  See lod_qos_calc_ppo() for how penalties are calculated.
324  *
325  * \param[in] lod       LOD device, where OST targets are listed
326  * \param[in] i         OST target index
327  *
328  * \retval              0
329  */
330 static int lod_qos_calc_weight(struct lod_device *lod, int i)
331 {
332         __u64 temp, temp2;
333
334         temp = TGT_BAVAIL(i);
335         temp2 = OST_TGT(lod, i)->ltd_qos.ltq_penalty +
336                 OST_TGT(lod, i)->ltd_qos.ltq_svr->lsq_penalty;
337         if (temp < temp2)
338                 OST_TGT(lod, i)->ltd_qos.ltq_weight = 0;
339         else
340                 OST_TGT(lod, i)->ltd_qos.ltq_weight = temp - temp2;
341         return 0;
342 }
343
344 /**
345  * Re-calculate weights.
346  *
347  * The function is called when some OST target was used for a new object. In
348  * this case we should re-calculate all the weights to keep new allocations
349  * balanced well.
350  *
351  * \param[in] lod       LOD device
352  * \param[in] osts      OST pool where a new object was placed
353  * \param[in] index     OST target where a new object was placed
354  * \param[out] total_wt new total weight for the pool
355  *
356  * \retval              0
357  */
358 static int lod_qos_used(struct lod_device *lod, struct ost_pool *osts,
359                         __u32 index, __u64 *total_wt)
360 {
361         struct lod_tgt_desc *ost;
362         struct lu_svr_qos  *oss;
363         unsigned int j;
364         ENTRY;
365
366         ost = OST_TGT(lod,index);
367         LASSERT(ost);
368
369         /* Don't allocate on this devuce anymore, until the next alloc_qos */
370         ost->ltd_qos.ltq_usable = 0;
371
372         oss = ost->ltd_qos.ltq_svr;
373
374         /* Decay old penalty by half (we're adding max penalty, and don't
375            want it to run away.) */
376         ost->ltd_qos.ltq_penalty >>= 1;
377         oss->lsq_penalty >>= 1;
378
379         /* mark the OSS and OST as recently used */
380         ost->ltd_qos.ltq_used = oss->lsq_used = ktime_get_real_seconds();
381
382         /* Set max penalties for this OST and OSS */
383         ost->ltd_qos.ltq_penalty +=
384                 ost->ltd_qos.ltq_penalty_per_obj * lod->lod_ostnr;
385         oss->lsq_penalty += oss->lsq_penalty_per_obj *
386                 lod->lod_qos.lq_active_svr_count;
387
388         /* Decrease all OSS penalties */
389         list_for_each_entry(oss, &lod->lod_qos.lq_svr_list, lsq_svr_list) {
390                 if (oss->lsq_penalty < oss->lsq_penalty_per_obj)
391                         oss->lsq_penalty = 0;
392                 else
393                         oss->lsq_penalty -= oss->lsq_penalty_per_obj;
394         }
395
396         *total_wt = 0;
397         /* Decrease all OST penalties */
398         for (j = 0; j < osts->op_count; j++) {
399                 int i;
400
401                 i = osts->op_array[j];
402                 if (!cfs_bitmap_check(lod->lod_ost_bitmap, i))
403                         continue;
404
405                 ost = OST_TGT(lod,i);
406                 LASSERT(ost);
407
408                 if (ost->ltd_qos.ltq_penalty <
409                                 ost->ltd_qos.ltq_penalty_per_obj)
410                         ost->ltd_qos.ltq_penalty = 0;
411                 else
412                         ost->ltd_qos.ltq_penalty -=
413                                 ost->ltd_qos.ltq_penalty_per_obj;
414
415                 lod_qos_calc_weight(lod, i);
416
417                 /* Recalc the total weight of usable osts */
418                 if (ost->ltd_qos.ltq_usable)
419                         *total_wt += ost->ltd_qos.ltq_weight;
420
421                 QOS_DEBUG("recalc tgt %d usable=%d avail=%llu"
422                           " ostppo=%llu ostp=%llu ossppo=%llu"
423                           " ossp=%llu wt=%llu\n",
424                           i, ost->ltd_qos.ltq_usable, TGT_BAVAIL(i) >> 10,
425                           ost->ltd_qos.ltq_penalty_per_obj >> 10,
426                           ost->ltd_qos.ltq_penalty >> 10,
427                           ost->ltd_qos.ltq_svr->lsq_penalty_per_obj >> 10,
428                           ost->ltd_qos.ltq_svr->lsq_penalty >> 10,
429                           ost->ltd_qos.ltq_weight >> 10);
430         }
431
432         RETURN(0);
433 }
434
435 void lod_qos_rr_init(struct lu_qos_rr *lqr)
436 {
437         spin_lock_init(&lqr->lqr_alloc);
438         lqr->lqr_dirty = 1;
439 }
440
441 #define LOV_QOS_EMPTY ((__u32)-1)
442
443 /**
444  * Calculate optimal round-robin order with regard to OSSes.
445  *
446  * Place all the OSTs from pool \a src_pool in a special array to be used for
447  * round-robin (RR) stripe allocation.  The placement algorithm interleaves
448  * OSTs from the different OSSs so that RR allocation can balance OSSs evenly.
449  * Resorts the targets when the number of active targets changes (because of
450  * a new target or activation/deactivation).
451  *
452  * \param[in] lod       LOD device
453  * \param[in] src_pool  OST pool
454  * \param[in] lqr       round-robin list
455  *
456  * \retval 0            on success
457  * \retval -ENOMEM      fails to allocate the array
458  */
459 static int lod_qos_calc_rr(struct lod_device *lod, struct ost_pool *src_pool,
460                            struct lu_qos_rr *lqr)
461 {
462         struct lu_svr_qos  *oss;
463         struct lod_tgt_desc *ost;
464         unsigned placed, real_count;
465         unsigned int i;
466         int rc;
467         ENTRY;
468
469         if (!lqr->lqr_dirty) {
470                 LASSERT(lqr->lqr_pool.op_size);
471                 RETURN(0);
472         }
473
474         /* Do actual allocation. */
475         down_write(&lod->lod_qos.lq_rw_sem);
476
477         /*
478          * Check again. While we were sleeping on @lq_rw_sem something could
479          * change.
480          */
481         if (!lqr->lqr_dirty) {
482                 LASSERT(lqr->lqr_pool.op_size);
483                 up_write(&lod->lod_qos.lq_rw_sem);
484                 RETURN(0);
485         }
486
487         real_count = src_pool->op_count;
488
489         /* Zero the pool array */
490         /* alloc_rr is holding a read lock on the pool, so nobody is adding/
491            deleting from the pool. The lq_rw_sem insures that nobody else
492            is reading. */
493         lqr->lqr_pool.op_count = real_count;
494         rc = lod_ost_pool_extend(&lqr->lqr_pool, real_count);
495         if (rc) {
496                 up_write(&lod->lod_qos.lq_rw_sem);
497                 RETURN(rc);
498         }
499         for (i = 0; i < lqr->lqr_pool.op_count; i++)
500                 lqr->lqr_pool.op_array[i] = LOV_QOS_EMPTY;
501
502         /* Place all the OSTs from 1 OSS at the same time. */
503         placed = 0;
504         list_for_each_entry(oss, &lod->lod_qos.lq_svr_list, lsq_svr_list) {
505                 int j = 0;
506
507                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
508                         int next;
509
510                         if (!cfs_bitmap_check(lod->lod_ost_bitmap,
511                                                 src_pool->op_array[i]))
512                                 continue;
513
514                         ost = OST_TGT(lod,src_pool->op_array[i]);
515                         LASSERT(ost && ost->ltd_ost);
516                         if (ost->ltd_qos.ltq_svr != oss)
517                                 continue;
518
519                         /* Evenly space these OSTs across arrayspace */
520                         next = j * lqr->lqr_pool.op_count / oss->lsq_tgt_count;
521                         while (lqr->lqr_pool.op_array[next] != LOV_QOS_EMPTY)
522                                 next = (next + 1) % lqr->lqr_pool.op_count;
523
524                         lqr->lqr_pool.op_array[next] = src_pool->op_array[i];
525                         j++;
526                         placed++;
527                 }
528         }
529
530         lqr->lqr_dirty = 0;
531         up_write(&lod->lod_qos.lq_rw_sem);
532
533         if (placed != real_count) {
534                 /* This should never happen */
535                 LCONSOLE_ERROR_MSG(0x14e, "Failed to place all OSTs in the "
536                                    "round-robin list (%d of %d).\n",
537                                    placed, real_count);
538                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
539                         LCONSOLE(D_WARNING, "rr #%d ost idx=%d\n", i,
540                                  lqr->lqr_pool.op_array[i]);
541                 }
542                 lqr->lqr_dirty = 1;
543                 RETURN(-EAGAIN);
544         }
545
546 #if 0
547         for (i = 0; i < lqr->lqr_pool.op_count; i++)
548                 QOS_CONSOLE("rr #%d ost idx=%d\n", i, lqr->lqr_pool.op_array[i]);
549 #endif
550
551         RETURN(0);
552 }
553
554 /**
555  * Instantiate and declare creation of a new object.
556  *
557  * The function instantiates LU representation for a new object on the
558  * specified device. Also it declares an intention to create that
559  * object on the storage target.
560  *
561  * Note lu_object_anon() is used which is a trick with regard to LU/OSD
562  * infrastructure - in the existing precreation framework we can't assign FID
563  * at this moment, we do this later once a transaction is started. So the
564  * special method instantiates FID-less object in the cache and later it
565  * will get a FID and proper placement in LU cache.
566  *
567  * \param[in] env       execution environment for this thread
568  * \param[in] d         LOD device
569  * \param[in] ost_idx   OST target index where the object is being created
570  * \param[in] th        transaction handle
571  *
572  * \retval              object ptr on success, ERR_PTR() otherwise
573  */
574 static struct dt_object *lod_qos_declare_object_on(const struct lu_env *env,
575                                                    struct lod_device *d,
576                                                    __u32 ost_idx,
577                                                    struct thandle *th)
578 {
579         struct lod_tgt_desc *ost;
580         struct lu_object *o, *n;
581         struct lu_device *nd;
582         struct dt_object *dt;
583         int               rc;
584         ENTRY;
585
586         LASSERT(d);
587         LASSERT(ost_idx < d->lod_osts_size);
588         ost = OST_TGT(d,ost_idx);
589         LASSERT(ost);
590         LASSERT(ost->ltd_ost);
591
592         nd = &ost->ltd_ost->dd_lu_dev;
593
594         /*
595          * allocate anonymous object with zero fid, real fid
596          * will be assigned by OSP within transaction
597          * XXX: to be fixed with fully-functional OST fids
598          */
599         o = lu_object_anon(env, nd, NULL);
600         if (IS_ERR(o))
601                 GOTO(out, dt = ERR_PTR(PTR_ERR(o)));
602
603         n = lu_object_locate(o->lo_header, nd->ld_type);
604         if (unlikely(n == NULL)) {
605                 CERROR("can't find slice\n");
606                 lu_object_put(env, o);
607                 GOTO(out, dt = ERR_PTR(-EINVAL));
608         }
609
610         dt = container_of(n, struct dt_object, do_lu);
611
612         rc = lod_sub_declare_create(env, dt, NULL, NULL, NULL, th);
613         if (rc < 0) {
614                 CDEBUG(D_OTHER, "can't declare creation on #%u: %d\n",
615                        ost_idx, rc);
616                 lu_object_put(env, o);
617                 dt = ERR_PTR(rc);
618         }
619
620 out:
621         RETURN(dt);
622 }
623
624 /**
625  * Calculate a minimum acceptable stripe count.
626  *
627  * Return an acceptable stripe count depending on flag LOV_USES_DEFAULT_STRIPE:
628  * all stripes or 3/4 of stripes.
629  *
630  * \param[in] stripe_count      number of stripes requested
631  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
632  *
633  * \retval                      acceptable stripecount
634  */
635 static int min_stripe_count(__u32 stripe_count, int flags)
636 {
637         return (flags & LOV_USES_DEFAULT_STRIPE ?
638                 stripe_count - (stripe_count / 4) : stripe_count);
639 }
640
641 #define LOV_CREATE_RESEED_MULT 30
642 #define LOV_CREATE_RESEED_MIN  2000
643
644 /**
645  * Initialize temporary OST-in-use array.
646  *
647  * Allocate or extend the array used to mark targets already assigned to a new
648  * striping so they are not used more than once.
649  *
650  * \param[in] env       execution environment for this thread
651  * \param[in] stripes   number of items needed in the array
652  *
653  * \retval 0            on success
654  * \retval -ENOMEM      on error
655  */
656 static inline int lod_qos_ost_in_use_clear(const struct lu_env *env,
657                                            __u32 stripes)
658 {
659         struct lod_thread_info *info = lod_env_info(env);
660
661         if (info->lti_ea_store_size < sizeof(int) * stripes)
662                 lod_ea_store_resize(info, stripes * sizeof(int));
663         if (info->lti_ea_store_size < sizeof(int) * stripes) {
664                 CERROR("can't allocate memory for ost-in-use array\n");
665                 return -ENOMEM;
666         }
667         memset(info->lti_ea_store, -1, sizeof(int) * stripes);
668         return 0;
669 }
670
671 /**
672  * Remember a target in the array of used targets.
673  *
674  * Mark the given target as used for a new striping being created. The status
675  * of an OST in a striping can be checked with lod_qos_is_ost_used().
676  *
677  * \param[in] env       execution environment for this thread
678  * \param[in] idx       index in the array
679  * \param[in] ost       OST target index to mark as used
680  */
681 static inline void lod_qos_ost_in_use(const struct lu_env *env,
682                                       int idx, int ost)
683 {
684         struct lod_thread_info *info = lod_env_info(env);
685         int *osts = info->lti_ea_store;
686
687         LASSERT(info->lti_ea_store_size >= idx * sizeof(int));
688         osts[idx] = ost;
689 }
690
691 /**
692  * Check is OST used in a striping.
693  *
694  * Checks whether OST with the given index is marked as used in the temporary
695  * array (see lod_qos_ost_in_use()).
696  *
697  * \param[in] env       execution environment for this thread
698  * \param[in] ost       OST target index to check
699  * \param[in] stripes   the number of items used in the array already
700  *
701  * \retval 0            not used
702  * \retval 1            used
703  */
704 static int lod_qos_is_ost_used(const struct lu_env *env, int ost, __u32 stripes)
705 {
706         struct lod_thread_info *info = lod_env_info(env);
707         int *osts = info->lti_ea_store;
708         __u32 j;
709
710         for (j = 0; j < stripes; j++) {
711                 if (osts[j] == ost)
712                         return 1;
713         }
714         return 0;
715 }
716
717 static inline bool
718 lod_obj_is_ost_use_skip_cb(const struct lu_env *env, struct lod_object *lo,
719                            int comp_idx, struct lod_obj_stripe_cb_data *data)
720 {
721         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
722
723         return comp->llc_ost_indices == NULL;
724 }
725
726 static inline int
727 lod_obj_is_ost_use_cb(const struct lu_env *env, struct lod_object *lo,
728                       int comp_idx, struct lod_obj_stripe_cb_data *data)
729 {
730         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
731         int i;
732
733         for (i = 0; i < comp->llc_stripe_count; i++) {
734                 if (comp->llc_ost_indices[i] == data->locd_ost_index) {
735                         data->locd_ost_index = -1;
736                         return -EEXIST;
737                 }
738         }
739
740         return 0;
741 }
742
743 /**
744  * Check is OST used in a composite layout
745  *
746  * \param[in] lo        lod object
747  * \param[in] ost       OST target index to check
748  *
749  * \retval false        not used
750  * \retval true         used
751  */
752 static inline bool lod_comp_is_ost_used(const struct lu_env *env,
753                                        struct lod_object *lo, int ost)
754 {
755         struct lod_obj_stripe_cb_data data = { { 0 } };
756
757         data.locd_ost_index = ost;
758         data.locd_comp_skip_cb = lod_obj_is_ost_use_skip_cb;
759         data.locd_comp_cb = lod_obj_is_ost_use_cb;
760
761         (void)lod_obj_for_each_stripe(env, lo, NULL, &data);
762
763         return data.locd_ost_index == -1;
764 }
765
766 static inline void lod_avoid_update(struct lod_object *lo,
767                                     struct lod_avoid_guide *lag)
768 {
769         if (!lod_is_flr(lo))
770                 return;
771
772         lag->lag_ost_avail--;
773 }
774
775 static inline bool lod_should_avoid_ost(struct lod_object *lo,
776                                         struct lod_avoid_guide *lag,
777                                         __u32 index)
778 {
779         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
780         struct lod_tgt_desc *ost = OST_TGT(lod, index);
781         struct lu_svr_qos *lsq = ost->ltd_qos.ltq_svr;
782         bool used = false;
783         int i;
784
785         if (!cfs_bitmap_check(lod->lod_ost_bitmap, index)) {
786                 QOS_DEBUG("OST%d: been used in conflicting mirror component\n",
787                           index);
788                 return true;
789         }
790
791         /**
792          * we've tried our best, all available OSTs have been used in
793          * overlapped components in the other mirror
794          */
795         if (lag->lag_ost_avail == 0)
796                 return false;
797
798         /* check OSS use */
799         for (i = 0; i < lag->lag_oaa_count; i++) {
800                 if (lag->lag_oss_avoid_array[i] == lsq->lsq_id) {
801                         used = true;
802                         break;
803                 }
804         }
805         /**
806          * if the OSS which OST[index] resides has not been used, we'd like to
807          * use it
808          */
809         if (!used)
810                 return false;
811
812         /* if the OSS has been used, check whether the OST has been used */
813         if (!cfs_bitmap_check(lag->lag_ost_avoid_bitmap, index))
814                 used = false;
815         else
816                 QOS_DEBUG("OST%d: been used in conflicting mirror component\n",
817                           index);
818         return used;
819 }
820
821 static int lod_check_and_reserve_ost(const struct lu_env *env,
822                                      struct lod_object *lo,
823                                      struct lod_layout_component *lod_comp,
824                                      struct obd_statfs *sfs, __u32 ost_idx,
825                                      __u32 speed, __u32 *s_idx,
826                                      struct dt_object **stripe,
827                                      __u32 *ost_indices,
828                                      struct thandle *th,
829                                      bool *overstriped)
830 {
831         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
832         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
833         struct dt_object   *o;
834         __u32 stripe_idx = *s_idx;
835         int rc;
836         ENTRY;
837
838         rc = lod_statfs_and_check(env, lod, ost_idx, sfs);
839         if (rc)
840                 RETURN(rc);
841
842         /*
843          * We expect number of precreated objects in f_ffree at
844          * the first iteration, skip OSPs with no objects ready
845          */
846         if (sfs->os_fprecreated == 0 && speed == 0) {
847                 QOS_DEBUG("#%d: precreation is empty\n", ost_idx);
848                 RETURN(rc);
849         }
850
851         /*
852          * try to use another OSP if this one is degraded
853          */
854         if (sfs->os_state & OS_STATE_DEGRADED && speed < 2) {
855                 QOS_DEBUG("#%d: degraded\n", ost_idx);
856                 RETURN(rc);
857         }
858
859         /*
860          * try not allocate on OST which has been used by other
861          * component
862          */
863         if (speed == 0 && lod_comp_is_ost_used(env, lo, ost_idx)) {
864                 QOS_DEBUG("iter %d: OST%d used by other component\n",
865                           speed, ost_idx);
866                 RETURN(rc);
867         }
868
869         /**
870          * try not allocate OSTs used by conflicting component of other mirrors
871          * for the first and second time.
872          */
873         if (speed < 2 && lod_should_avoid_ost(lo, lag, ost_idx)) {
874                 QOS_DEBUG("iter %d: OST%d used by conflicting mirror "
875                           "component\n", speed, ost_idx);
876                 RETURN(rc);
877         }
878
879         /* do not put >1 objects on a single OST, except for overstriping */
880         if (lod_qos_is_ost_used(env, ost_idx, stripe_idx)) {
881                 if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
882                         *overstriped = true;
883                 else
884                         RETURN(rc);
885         }
886
887         o = lod_qos_declare_object_on(env, lod, ost_idx, th);
888         if (IS_ERR(o)) {
889                 CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
890                        ost_idx, (int) PTR_ERR(o));
891                 rc = PTR_ERR(o);
892                 RETURN(rc);
893         }
894
895         /*
896          * We've successfully declared (reserved) an object
897          */
898         lod_avoid_update(lo, lag);
899         lod_qos_ost_in_use(env, stripe_idx, ost_idx);
900         stripe[stripe_idx] = o;
901         ost_indices[stripe_idx] = ost_idx;
902         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_LOV_CREATE_RACE, 2);
903         stripe_idx++;
904         *s_idx = stripe_idx;
905
906         RETURN(rc);
907 }
908
909 /**
910  * Allocate a striping using round-robin algorithm.
911  *
912  * Allocates a new striping using round-robin algorithm. The function refreshes
913  * all the internal structures (statfs cache, array of available OSTs sorted
914  * with regard to OSS, etc). The number of stripes required is taken from the
915  * object (must be prepared by the caller), but can change if the flag
916  * LOV_USES_DEFAULT_STRIPE is supplied. The caller should ensure nobody else
917  * is trying to create a striping on the object in parallel. All the internal
918  * structures (like pools, etc) are protected and no additional locking is
919  * required. The function succeeds even if a single stripe is allocated. To save
920  * time we give priority to targets which already have objects precreated.
921  * Full OSTs are skipped (see lod_qos_dev_is_full() for the details).
922  *
923  * \param[in] env               execution environment for this thread
924  * \param[in] lo                LOD object
925  * \param[out] stripe           striping created
926  * \param[out] ost_indices      ost indices of striping created
927  * \param[in] flags             allocation flags (0 or LOV_USES_DEFAULT_STRIPE)
928  * \param[in] th                transaction handle
929  * \param[in] comp_idx          index of ldo_comp_entries
930  *
931  * \retval 0            on success
932  * \retval -ENOSPC      if not enough OSTs are found
933  * \retval negative     negated errno for other failures
934  */
935 static int lod_alloc_rr(const struct lu_env *env, struct lod_object *lo,
936                         struct dt_object **stripe, __u32 *ost_indices,
937                         int flags, struct thandle *th, int comp_idx)
938 {
939         struct lod_layout_component *lod_comp;
940         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
941         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
942         struct pool_desc  *pool = NULL;
943         struct ost_pool   *osts;
944         struct lu_qos_rr *lqr;
945         unsigned int    i, array_idx;
946         __u32 ost_start_idx_temp;
947         __u32 stripe_idx = 0;
948         __u32 stripe_count, stripe_count_min, ost_idx;
949         int rc, speed = 0, ost_connecting = 0;
950         int stripes_per_ost = 1;
951         bool overstriped = false;
952         ENTRY;
953
954         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
955         lod_comp = &lo->ldo_comp_entries[comp_idx];
956         stripe_count = lod_comp->llc_stripe_count;
957         stripe_count_min = min_stripe_count(stripe_count, flags);
958
959         if (lod_comp->llc_pool != NULL)
960                 pool = lod_find_pool(m, lod_comp->llc_pool);
961
962         if (pool != NULL) {
963                 down_read(&pool_tgt_rw_sem(pool));
964                 osts = &(pool->pool_obds);
965                 lqr = &(pool->pool_rr);
966         } else {
967                 osts = &(m->lod_pool_info);
968                 lqr = &(m->lod_qos.lq_rr);
969         }
970
971         rc = lod_qos_calc_rr(m, osts, lqr);
972         if (rc)
973                 GOTO(out, rc);
974
975         rc = lod_qos_ost_in_use_clear(env, stripe_count);
976         if (rc)
977                 GOTO(out, rc);
978
979         down_read(&m->lod_qos.lq_rw_sem);
980         spin_lock(&lqr->lqr_alloc);
981         if (--lqr->lqr_start_count <= 0) {
982                 lqr->lqr_start_idx = cfs_rand() % osts->op_count;
983                 lqr->lqr_start_count =
984                         (LOV_CREATE_RESEED_MIN / max(osts->op_count, 1U) +
985                          LOV_CREATE_RESEED_MULT) * max(osts->op_count, 1U);
986         } else if (stripe_count_min >= osts->op_count ||
987                         lqr->lqr_start_idx > osts->op_count) {
988                 /* If we have allocated from all of the OSTs, slowly
989                  * precess the next start if the OST/stripe count isn't
990                  * already doing this for us. */
991                 lqr->lqr_start_idx %= osts->op_count;
992                 if (stripe_count > 1 && (osts->op_count % stripe_count) != 1)
993                         ++lqr->lqr_offset_idx;
994         }
995         ost_start_idx_temp = lqr->lqr_start_idx;
996
997 repeat_find:
998
999         QOS_DEBUG("pool '%s' want %d start_idx %d start_count %d offset %d "
1000                   "active %d count %d\n",
1001                   lod_comp->llc_pool ? lod_comp->llc_pool : "",
1002                   stripe_count, lqr->lqr_start_idx, lqr->lqr_start_count,
1003                   lqr->lqr_offset_idx, osts->op_count, osts->op_count);
1004
1005         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1006                 stripes_per_ost =
1007                         (lod_comp->llc_stripe_count - 1)/osts->op_count + 1;
1008
1009         for (i = 0; i < osts->op_count * stripes_per_ost
1010              && stripe_idx < stripe_count; i++) {
1011                 array_idx = (lqr->lqr_start_idx + lqr->lqr_offset_idx) %
1012                                 osts->op_count;
1013                 ++lqr->lqr_start_idx;
1014                 ost_idx = lqr->lqr_pool.op_array[array_idx];
1015
1016                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
1017                           i, lqr->lqr_start_idx, /* XXX: active*/ 0,
1018                           stripe_idx, array_idx, ost_idx);
1019
1020                 if ((ost_idx == LOV_QOS_EMPTY) ||
1021                     !cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1022                         continue;
1023
1024                 /* Fail Check before osc_precreate() is called
1025                    so we can only 'fail' single OSC. */
1026                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1027                         continue;
1028
1029                 spin_unlock(&lqr->lqr_alloc);
1030                 rc = lod_check_and_reserve_ost(env, lo, lod_comp, sfs, ost_idx,
1031                                                speed, &stripe_idx, stripe,
1032                                                ost_indices, th, &overstriped);
1033                 spin_lock(&lqr->lqr_alloc);
1034
1035                 if (rc != 0 && OST_TGT(m, ost_idx)->ltd_connecting)
1036                         ost_connecting = 1;
1037         }
1038         if ((speed < 2) && (stripe_idx < stripe_count_min)) {
1039                 /* Try again, allowing slower OSCs */
1040                 speed++;
1041                 lqr->lqr_start_idx = ost_start_idx_temp;
1042
1043                 ost_connecting = 0;
1044                 goto repeat_find;
1045         }
1046
1047         spin_unlock(&lqr->lqr_alloc);
1048         up_read(&m->lod_qos.lq_rw_sem);
1049
1050         /* If there are enough OSTs, a component with overstriping requested
1051          * will not actually end up overstriped.  The comp should reflect this.
1052          */
1053         if (!overstriped)
1054                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1055
1056         if (stripe_idx) {
1057                 lod_comp->llc_stripe_count = stripe_idx;
1058                 /* at least one stripe is allocated */
1059                 rc = 0;
1060         } else {
1061                 /* nobody provided us with a single object */
1062                 if (ost_connecting)
1063                         rc = -EINPROGRESS;
1064                 else
1065                         rc = -ENOSPC;
1066         }
1067
1068 out:
1069         if (pool != NULL) {
1070                 up_read(&pool_tgt_rw_sem(pool));
1071                 /* put back ref got by lod_find_pool() */
1072                 lod_pool_putref(pool);
1073         }
1074
1075         RETURN(rc);
1076 }
1077
1078 /**
1079  * Allocate a specific striping layout on a user defined set of OSTs.
1080  *
1081  * Allocates new striping using the OST index range provided by the data from
1082  * the lmm_obejcts contained in the lov_user_md passed to this method. Full
1083  * OSTs are not considered. The exact order of OSTs requested by the user
1084  * is respected as much as possible depending on OST status. The number of
1085  * stripes needed and stripe offset are taken from the object. If that number
1086  * can not be met, then the function returns a failure and then it's the
1087  * caller's responsibility to release the stripes allocated. All the internal
1088  * structures are protected, but no concurrent allocation is allowed on the
1089  * same objects.
1090  *
1091  * \param[in] env               execution environment for this thread
1092  * \param[in] lo                LOD object
1093  * \param[out] stripe           striping created
1094  * \param[out] ost_indices      ost indices of striping created
1095  * \param[in] th                transaction handle
1096  * \param[in] comp_idx          index of ldo_comp_entries
1097  *
1098  * \retval 0            on success
1099  * \retval -ENODEV      OST index does not exist on file system
1100  * \retval -EINVAL      requested OST index is invalid
1101  * \retval negative     negated errno on error
1102  */
1103 static int lod_alloc_ost_list(const struct lu_env *env, struct lod_object *lo,
1104                               struct dt_object **stripe, __u32 *ost_indices,
1105                               struct thandle *th, int comp_idx)
1106 {
1107         struct lod_layout_component *lod_comp;
1108         struct lod_device       *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1109         struct obd_statfs       *sfs = &lod_env_info(env)->lti_osfs;
1110         struct dt_object        *o;
1111         unsigned int            array_idx = 0;
1112         int                     stripe_count = 0;
1113         int                     i;
1114         int                     rc = -EINVAL;
1115         ENTRY;
1116
1117         /* for specific OSTs layout */
1118         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1119         lod_comp = &lo->ldo_comp_entries[comp_idx];
1120         LASSERT(lod_comp->llc_ostlist.op_array);
1121         LASSERT(lod_comp->llc_ostlist.op_count);
1122
1123         rc = lod_qos_ost_in_use_clear(env, lod_comp->llc_stripe_count);
1124         if (rc < 0)
1125                 RETURN(rc);
1126
1127         if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT)
1128                 lod_comp->llc_stripe_offset =
1129                                 lod_comp->llc_ostlist.op_array[0];
1130
1131         for (i = 0; i < lod_comp->llc_stripe_count; i++) {
1132                 if (lod_comp->llc_ostlist.op_array[i] ==
1133                     lod_comp->llc_stripe_offset) {
1134                         array_idx = i;
1135                         break;
1136                 }
1137         }
1138         if (i == lod_comp->llc_stripe_count) {
1139                 CDEBUG(D_OTHER,
1140                        "%s: start index %d not in the specified list of OSTs\n",
1141                        lod2obd(m)->obd_name, lod_comp->llc_stripe_offset);
1142                 RETURN(-EINVAL);
1143         }
1144
1145         for (i = 0; i < lod_comp->llc_stripe_count;
1146              i++, array_idx = (array_idx + 1) % lod_comp->llc_stripe_count) {
1147                 __u32 ost_idx = lod_comp->llc_ostlist.op_array[array_idx];
1148
1149                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx)) {
1150                         rc = -ENODEV;
1151                         break;
1152                 }
1153
1154                 /* do not put >1 objects on a single OST, except for
1155                  * overstriping
1156                  */
1157                 if (lod_qos_is_ost_used(env, ost_idx, stripe_count) &&
1158                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)) {
1159                         rc = -EINVAL;
1160                         break;
1161                 }
1162
1163                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1164                 if (rc < 0) /* this OSP doesn't feel well */
1165                         break;
1166
1167                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1168                 if (IS_ERR(o)) {
1169                         rc = PTR_ERR(o);
1170                         CDEBUG(D_OTHER,
1171                                "%s: can't declare new object on #%u: %d\n",
1172                                lod2obd(m)->obd_name, ost_idx, rc);
1173                         break;
1174                 }
1175
1176                 /*
1177                  * We've successfully declared (reserved) an object
1178                  */
1179                 lod_qos_ost_in_use(env, stripe_count, ost_idx);
1180                 stripe[stripe_count] = o;
1181                 ost_indices[stripe_count] = ost_idx;
1182                 stripe_count++;
1183         }
1184
1185         RETURN(rc);
1186 }
1187
1188 /**
1189  * Allocate a striping on a predefined set of OSTs.
1190  *
1191  * Allocates new layout starting from OST index in lo->ldo_stripe_offset.
1192  * Full OSTs are not considered. The exact order of OSTs is not important and
1193  * varies depending on OST status. The allocation procedure prefers the targets
1194  * with precreated objects ready. The number of stripes needed and stripe
1195  * offset are taken from the object. If that number cannot be met, then the
1196  * function returns an error and then it's the caller's responsibility to
1197  * release the stripes allocated. All the internal structures are protected,
1198  * but no concurrent allocation is allowed on the same objects.
1199  *
1200  * \param[in] env               execution environment for this thread
1201  * \param[in] lo                LOD object
1202  * \param[out] stripe           striping created
1203  * \param[out] ost_indices      ost indices of striping created
1204  * \param[in] flags             not used
1205  * \param[in] th                transaction handle
1206  * \param[in] comp_idx          index of ldo_comp_entries
1207  *
1208  * \retval 0            on success
1209  * \retval -ENOSPC      if no OST objects are available at all
1210  * \retval -EFBIG       if not enough OST objects are found
1211  * \retval -EINVAL      requested offset is invalid
1212  * \retval negative     errno on failure
1213  */
1214 static int lod_alloc_specific(const struct lu_env *env, struct lod_object *lo,
1215                               struct dt_object **stripe, __u32 *ost_indices,
1216                               int flags, struct thandle *th, int comp_idx)
1217 {
1218         struct lod_layout_component *lod_comp;
1219         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1220         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
1221         struct dt_object *o;
1222         __u32 ost_idx;
1223         unsigned int i, array_idx, ost_count;
1224         int rc, stripe_num = 0;
1225         int speed = 0;
1226         struct pool_desc  *pool = NULL;
1227         struct ost_pool   *osts;
1228         int stripes_per_ost = 1;
1229         bool overstriped = false;
1230         ENTRY;
1231
1232         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1233         lod_comp = &lo->ldo_comp_entries[comp_idx];
1234
1235         rc = lod_qos_ost_in_use_clear(env, lod_comp->llc_stripe_count);
1236         if (rc)
1237                 GOTO(out, rc);
1238
1239         if (lod_comp->llc_pool != NULL)
1240                 pool = lod_find_pool(m, lod_comp->llc_pool);
1241
1242         if (pool != NULL) {
1243                 down_read(&pool_tgt_rw_sem(pool));
1244                 osts = &(pool->pool_obds);
1245         } else {
1246                 osts = &(m->lod_pool_info);
1247         }
1248
1249         ost_count = osts->op_count;
1250
1251 repeat_find:
1252         /* search loi_ost_idx in ost array */
1253         array_idx = 0;
1254         for (i = 0; i < ost_count; i++) {
1255                 if (osts->op_array[i] == lod_comp->llc_stripe_offset) {
1256                         array_idx = i;
1257                         break;
1258                 }
1259         }
1260         if (i == ost_count) {
1261                 CERROR("Start index %d not found in pool '%s'\n",
1262                        lod_comp->llc_stripe_offset,
1263                        lod_comp->llc_pool ? lod_comp->llc_pool : "");
1264                 GOTO(out, rc = -EINVAL);
1265         }
1266
1267         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1268                 stripes_per_ost =
1269                         (lod_comp->llc_stripe_count - 1)/ost_count + 1;
1270
1271         for (i = 0; i < ost_count * stripes_per_ost;
1272                         i++, array_idx = (array_idx + 1) % ost_count) {
1273                 ost_idx = osts->op_array[array_idx];
1274
1275                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1276                         continue;
1277
1278                 /* Fail Check before osc_precreate() is called
1279                    so we can only 'fail' single OSC. */
1280                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1281                         continue;
1282
1283                 /*
1284                  * do not put >1 objects on a single OST, except for
1285                  * overstriping, where it is intended
1286                  */
1287                 if (lod_qos_is_ost_used(env, ost_idx, stripe_num)) {
1288                         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1289                                 overstriped = true;
1290                         else
1291                                 continue;
1292                 }
1293
1294                 /*
1295                  * try not allocate on the OST used by other component
1296                  */
1297                 if (speed == 0 && i != 0 &&
1298                     lod_comp_is_ost_used(env, lo, ost_idx))
1299                         continue;
1300
1301                 /* Drop slow OSCs if we can, but not for requested start idx.
1302                  *
1303                  * This means "if OSC is slow and it is not the requested
1304                  * start OST, then it can be skipped, otherwise skip it only
1305                  * if it is inactive/recovering/out-of-space." */
1306
1307                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1308                 if (rc) {
1309                         /* this OSP doesn't feel well */
1310                         continue;
1311                 }
1312
1313                 /*
1314                  * We expect number of precreated objects at the first
1315                  * iteration.  Skip OSPs with no objects ready.  Don't apply
1316                  * this logic to OST specified with stripe_offset.
1317                  */
1318                 if (i != 0 && sfs->os_fprecreated == 0 && speed == 0)
1319                         continue;
1320
1321                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1322                 if (IS_ERR(o)) {
1323                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
1324                                ost_idx, (int) PTR_ERR(o));
1325                         continue;
1326                 }
1327
1328                 /*
1329                  * We've successfully declared (reserved) an object
1330                  */
1331                 lod_qos_ost_in_use(env, stripe_num, ost_idx);
1332                 stripe[stripe_num] = o;
1333                 ost_indices[stripe_num] = ost_idx;
1334                 stripe_num++;
1335
1336                 /* We have enough stripes */
1337                 if (stripe_num == lod_comp->llc_stripe_count)
1338                         GOTO(out, rc = 0);
1339         }
1340         if (speed < 2) {
1341                 /* Try again, allowing slower OSCs */
1342                 speed++;
1343                 goto repeat_find;
1344         }
1345
1346         /* If we were passed specific striping params, then a failure to
1347          * meet those requirements is an error, since we can't reallocate
1348          * that memory (it might be part of a larger array or something).
1349          */
1350         CERROR("can't lstripe objid "DFID": have %d want %u\n",
1351                PFID(lu_object_fid(lod2lu_obj(lo))), stripe_num,
1352                lod_comp->llc_stripe_count);
1353         rc = stripe_num == 0 ? -ENOSPC : -EFBIG;
1354
1355         /* If there are enough OSTs, a component with overstriping requessted
1356          * will not actually end up overstriped.  The comp should reflect this.
1357          */
1358         if (rc == 0 && !overstriped)
1359                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1360
1361 out:
1362         if (pool != NULL) {
1363                 up_read(&pool_tgt_rw_sem(pool));
1364                 /* put back ref got by lod_find_pool() */
1365                 lod_pool_putref(pool);
1366         }
1367
1368         RETURN(rc);
1369 }
1370
1371 /**
1372  * Check whether QoS allocation should be used.
1373  *
1374  * A simple helper to decide when QoS allocation should be used:
1375  * if it's just a single available target or the used space is
1376  * evenly distributed among the targets at the moment, then QoS
1377  * allocation algorithm should not be used.
1378  *
1379  * \param[in] lod       LOD device
1380  *
1381  * \retval 0            should not be used
1382  * \retval 1            should be used
1383  */
1384 static inline int lod_qos_is_usable(struct lod_device *lod)
1385 {
1386 #ifdef FORCE_QOS
1387         /* to be able to debug QoS code */
1388         return 1;
1389 #endif
1390
1391         /* Detect -EAGAIN early, before expensive lock is taken. */
1392         if (!lod->lod_qos.lq_dirty && lod->lod_qos.lq_same_space)
1393                 return 0;
1394
1395         if (lod->lod_desc.ld_active_tgt_count < 2)
1396                 return 0;
1397
1398         return 1;
1399 }
1400
1401 /**
1402  * Allocate a striping using an algorithm with weights.
1403  *
1404  * The function allocates OST objects to create a striping. The algorithm
1405  * used is based on weights (currently only using the free space), and it's
1406  * trying to ensure the space is used evenly by OSTs and OSSs. The striping
1407  * configuration (# of stripes, offset, pool) is taken from the object and
1408  * is prepared by the caller.
1409  *
1410  * If LOV_USES_DEFAULT_STRIPE is not passed and prepared configuration can't
1411  * be met due to too few OSTs, then allocation fails. If the flag is passed
1412  * fewer than 3/4 of the requested number of stripes can be allocated, then
1413  * allocation fails.
1414  *
1415  * No concurrent allocation is allowed on the object and this must be ensured
1416  * by the caller. All the internal structures are protected by the function.
1417  *
1418  * The algorithm has two steps: find available OSTs and calculate their
1419  * weights, then select the OSTs with their weights used as the probability.
1420  * An OST with a higher weight is proportionately more likely to be selected
1421  * than one with a lower weight.
1422  *
1423  * \param[in] env               execution environment for this thread
1424  * \param[in] lo                LOD object
1425  * \param[out] stripe           striping created
1426  * \param[out] ost_indices      ost indices of striping created
1427  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
1428  * \param[in] th                transaction handle
1429  * \param[in] comp_idx          index of ldo_comp_entries
1430  *
1431  * \retval 0            on success
1432  * \retval -EAGAIN      not enough OSTs are found for specified stripe count
1433  * \retval -EINVAL      requested OST index is invalid
1434  * \retval negative     errno on failure
1435  */
1436 static int lod_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1437                          struct dt_object **stripe, __u32 *ost_indices,
1438                          int flags, struct thandle *th, int comp_idx)
1439 {
1440         struct lod_layout_component *lod_comp;
1441         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1442         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
1443         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
1444         struct lod_tgt_desc *ost;
1445         struct dt_object *o;
1446         __u64 total_weight = 0;
1447         struct pool_desc *pool = NULL;
1448         struct ost_pool *osts;
1449         unsigned int i;
1450         __u32 nfound, good_osts, stripe_count, stripe_count_min;
1451         bool overstriped = false;
1452         int stripes_per_ost = 1;
1453         int rc = 0;
1454         ENTRY;
1455
1456         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1457         lod_comp = &lo->ldo_comp_entries[comp_idx];
1458         stripe_count = lod_comp->llc_stripe_count;
1459         stripe_count_min = min_stripe_count(stripe_count, flags);
1460         if (stripe_count_min < 1)
1461                 RETURN(-EINVAL);
1462
1463         if (lod_comp->llc_pool != NULL)
1464                 pool = lod_find_pool(lod, lod_comp->llc_pool);
1465
1466         if (pool != NULL) {
1467                 down_read(&pool_tgt_rw_sem(pool));
1468                 osts = &(pool->pool_obds);
1469         } else {
1470                 osts = &(lod->lod_pool_info);
1471         }
1472
1473         /* Detect -EAGAIN early, before expensive lock is taken. */
1474         if (!lod_qos_is_usable(lod))
1475                 GOTO(out_nolock, rc = -EAGAIN);
1476
1477         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1478                 stripes_per_ost =
1479                         (lod_comp->llc_stripe_count - 1)/osts->op_count + 1;
1480
1481         /* Do actual allocation, use write lock here. */
1482         down_write(&lod->lod_qos.lq_rw_sem);
1483
1484         /*
1485          * Check again, while we were sleeping on @lq_rw_sem things could
1486          * change.
1487          */
1488         if (!lod_qos_is_usable(lod))
1489                 GOTO(out, rc = -EAGAIN);
1490
1491         rc = lod_qos_calc_ppo(lod);
1492         if (rc)
1493                 GOTO(out, rc);
1494
1495         rc = lod_qos_ost_in_use_clear(env, lod_comp->llc_stripe_count);
1496         if (rc)
1497                 GOTO(out, rc);
1498
1499         good_osts = 0;
1500         /* Find all the OSTs that are valid stripe candidates */
1501         for (i = 0; i < osts->op_count; i++) {
1502                 if (!cfs_bitmap_check(lod->lod_ost_bitmap, osts->op_array[i]))
1503                         continue;
1504
1505                 ost = OST_TGT(lod, osts->op_array[i]);
1506                 ost->ltd_qos.ltq_usable = 0;
1507
1508                 rc = lod_statfs_and_check(env, lod, osts->op_array[i], sfs);
1509                 if (rc) {
1510                         /* this OSP doesn't feel well */
1511                         continue;
1512                 }
1513
1514                 if (sfs->os_state & OS_STATE_DEGRADED)
1515                         continue;
1516
1517                 /* Fail Check before osc_precreate() is called
1518                    so we can only 'fail' single OSC. */
1519                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) &&
1520                                    osts->op_array[i] == 0)
1521                         continue;
1522
1523                 ost->ltd_qos.ltq_usable = 1;
1524                 lod_qos_calc_weight(lod, osts->op_array[i]);
1525                 total_weight += ost->ltd_qos.ltq_weight;
1526
1527                 good_osts++;
1528         }
1529
1530         QOS_DEBUG("found %d good osts\n", good_osts);
1531
1532         if (good_osts < stripe_count_min)
1533                 GOTO(out, rc = -EAGAIN);
1534
1535         /* If we do not have enough OSTs for the requested stripe count, do not
1536          * put more stripes per OST than requested.
1537          */
1538         if (stripe_count / stripes_per_ost > good_osts)
1539                 stripe_count = good_osts * stripes_per_ost;
1540
1541         /* Find enough OSTs with weighted random allocation. */
1542         nfound = 0;
1543         while (nfound < stripe_count) {
1544                 __u64 rand, cur_weight;
1545
1546                 cur_weight = 0;
1547                 rc = -ENOSPC;
1548
1549                 if (total_weight) {
1550 #if BITS_PER_LONG == 32
1551                         rand = cfs_rand() % (unsigned)total_weight;
1552                         /* If total_weight > 32-bit, first generate the high
1553                          * 32 bits of the random number, then add in the low
1554                          * 32 bits (truncated to the upper limit, if needed) */
1555                         if (total_weight > 0xffffffffULL)
1556                                 rand = (__u64)(cfs_rand() %
1557                                         (unsigned)(total_weight >> 32)) << 32;
1558                         else
1559                                 rand = 0;
1560
1561                         if (rand == (total_weight & 0xffffffff00000000ULL))
1562                                 rand |= cfs_rand() % (unsigned)total_weight;
1563                         else
1564                                 rand |= cfs_rand();
1565
1566 #else
1567                         rand = ((__u64)cfs_rand() << 32 | cfs_rand()) %
1568                                 total_weight;
1569 #endif
1570                 } else {
1571                         rand = 0;
1572                 }
1573
1574                 /* On average, this will hit larger-weighted OSTs more often.
1575                  * 0-weight OSTs will always get used last (only when rand=0) */
1576                 for (i = 0; i < osts->op_count; i++) {
1577                         __u32 idx = osts->op_array[i];
1578
1579                         if (lod_should_avoid_ost(lo, lag, idx))
1580                                 continue;
1581
1582                         ost = OST_TGT(lod, idx);
1583
1584                         if (!ost->ltd_qos.ltq_usable)
1585                                 continue;
1586
1587                         cur_weight += ost->ltd_qos.ltq_weight;
1588                         QOS_DEBUG("stripe_count=%d nfound=%d cur_weight=%llu "
1589                                   "rand=%llu total_weight=%llu\n",
1590                                   stripe_count, nfound, cur_weight, rand,
1591                                   total_weight);
1592
1593                         if (cur_weight < rand)
1594                                 continue;
1595
1596                         QOS_DEBUG("stripe=%d to idx=%d\n", nfound, idx);
1597                         /*
1598                          * do not put >1 objects on a single OST, except for
1599                          * overstriping
1600                          */
1601                         if ((lod_comp_is_ost_used(env, lo, idx)) &&
1602                             !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
1603                                 continue;
1604
1605                         if (lod_qos_is_ost_used(env, idx, nfound)) {
1606                                 if (lod_comp->llc_pattern &
1607                                     LOV_PATTERN_OVERSTRIPING)
1608                                         overstriped = true;
1609                                 else
1610                                         continue;
1611                         }
1612
1613                         o = lod_qos_declare_object_on(env, lod, idx, th);
1614                         if (IS_ERR(o)) {
1615                                 QOS_DEBUG("can't declare object on #%u: %d\n",
1616                                           idx, (int) PTR_ERR(o));
1617                                 continue;
1618                         }
1619
1620                         lod_avoid_update(lo, lag);
1621                         lod_qos_ost_in_use(env, nfound, idx);
1622                         stripe[nfound] = o;
1623                         ost_indices[nfound] = idx;
1624                         lod_qos_used(lod, osts, idx, &total_weight);
1625                         nfound++;
1626                         rc = 0;
1627                         break;
1628                 }
1629
1630                 if (rc) {
1631                         /* no OST found on this iteration, give up */
1632                         break;
1633                 }
1634         }
1635
1636         if (unlikely(nfound != stripe_count)) {
1637                 /*
1638                  * when the decision to use weighted algorithm was made
1639                  * we had enough appropriate OSPs, but this state can
1640                  * change anytime (no space on OST, broken connection, etc)
1641                  * so it's possible OSP won't be able to provide us with
1642                  * an object due to just changed state
1643                  */
1644                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1645                           lod2obd(lod)->obd_name, stripe_count, nfound);
1646                 for (i = 0; i < nfound; i++) {
1647                         LASSERT(stripe[i] != NULL);
1648                         dt_object_put(env, stripe[i]);
1649                         stripe[i] = NULL;
1650                 }
1651
1652                 /* makes sense to rebalance next time */
1653                 lod->lod_qos.lq_dirty = 1;
1654                 lod->lod_qos.lq_same_space = 0;
1655
1656                 rc = -EAGAIN;
1657         }
1658
1659         /* If there are enough OSTs, a component with overstriping requessted
1660          * will not actually end up overstriped.  The comp should reflect this.
1661          */
1662         if (rc == 0 && !overstriped)
1663                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1664
1665 out:
1666         up_write(&lod->lod_qos.lq_rw_sem);
1667
1668 out_nolock:
1669         if (pool != NULL) {
1670                 up_read(&pool_tgt_rw_sem(pool));
1671                 /* put back ref got by lod_find_pool() */
1672                 lod_pool_putref(pool);
1673         }
1674
1675         RETURN(rc);
1676 }
1677
1678 /**
1679  * Check stripe count the caller can use.
1680  *
1681  * For new layouts (no initialized components), check the total size of the
1682  * layout against the maximum EA size from the backing file system.  This
1683  * stops us from creating a layout which will be too large once initialized.
1684  *
1685  * For existing layouts (with initialized components):
1686  * Find the maximal possible stripe count not greater than \a stripe_count.
1687  * If the provided stripe count is 0, then the filesystem's default is used.
1688  *
1689  * \param[in] lod       LOD device
1690  * \param[in] lo        The lod_object
1691  * \param[in] stripe_count      count the caller would like to use
1692  *
1693  * \retval              the maximum usable stripe count
1694  */
1695 __u16 lod_get_stripe_count(struct lod_device *lod, struct lod_object *lo,
1696                            __u16 stripe_count, bool overstriping)
1697 {
1698         __u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
1699         /* max stripe count is based on OSD ea size */
1700         unsigned int easize = lod->lod_osd_max_easize;
1701         int i;
1702
1703
1704         if (!stripe_count)
1705                 stripe_count = lod->lod_desc.ld_default_stripe_count;
1706         if (!stripe_count)
1707                 stripe_count = 1;
1708         /* Overstriping allows more stripes than targets */
1709         if (stripe_count > lod->lod_desc.ld_active_tgt_count && !overstriping)
1710                 stripe_count = lod->lod_desc.ld_active_tgt_count;
1711
1712         if (lo->ldo_is_composite) {
1713                 struct lod_layout_component *lod_comp;
1714                 unsigned int header_sz = sizeof(struct lov_comp_md_v1);
1715                 unsigned int init_comp_sz = 0;
1716                 unsigned int total_comp_sz = 0;
1717                 unsigned int comp_sz;
1718
1719                 header_sz += sizeof(struct lov_comp_md_entry_v1) *
1720                                 lo->ldo_comp_cnt;
1721
1722                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
1723                         lod_comp = &lo->ldo_comp_entries[i];
1724                         comp_sz = lov_mds_md_size(lod_comp->llc_stripe_count,
1725                                                   LOV_MAGIC_V3);
1726                         total_comp_sz += comp_sz;
1727                         if (lod_comp->llc_flags & LCME_FL_INIT)
1728                                 init_comp_sz += comp_sz;
1729                 }
1730
1731                 if (init_comp_sz > 0)
1732                         total_comp_sz = init_comp_sz;
1733
1734                 header_sz += total_comp_sz;
1735
1736                 if (easize > header_sz)
1737                         easize -= header_sz;
1738                 else
1739                         easize = 0;
1740         }
1741
1742         max_stripes = lov_mds_md_max_stripe_count(easize, LOV_MAGIC_V3);
1743
1744         return (stripe_count < max_stripes) ? stripe_count : max_stripes;
1745 }
1746
1747 /**
1748  * Create in-core respresentation for a fully-defined striping
1749  *
1750  * When the caller passes a fully-defined striping (i.e. everything including
1751  * OST object FIDs are defined), then we still need to instantiate LU-cache
1752  * with the objects representing the stripes defined. This function completes
1753  * that task.
1754  *
1755  * \param[in] env       execution environment for this thread
1756  * \param[in] mo        LOD object
1757  * \param[in] buf       buffer containing the striping
1758  *
1759  * \retval 0            on success
1760  * \retval negative     negated errno on error
1761  */
1762 int lod_use_defined_striping(const struct lu_env *env,
1763                              struct lod_object *mo,
1764                              const struct lu_buf *buf)
1765 {
1766         struct lod_layout_component *lod_comp;
1767         struct lov_mds_md_v1   *v1 = buf->lb_buf;
1768         struct lov_mds_md_v3   *v3 = buf->lb_buf;
1769         struct lov_comp_md_v1  *comp_v1 = NULL;
1770         struct lov_ost_data_v1 *objs;
1771         __u32   magic;
1772         __u16   comp_cnt;
1773         __u16   mirror_cnt;
1774         int     rc = 0, i;
1775         ENTRY;
1776
1777         mutex_lock(&mo->ldo_layout_mutex);
1778         lod_striping_free_nolock(env, mo);
1779
1780         magic = le32_to_cpu(v1->lmm_magic) & ~LOV_MAGIC_DEFINED;
1781
1782         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3 &&
1783             magic != LOV_MAGIC_COMP_V1 && magic != LOV_MAGIC_FOREIGN)
1784                 GOTO(unlock, rc = -EINVAL);
1785
1786         if (magic == LOV_MAGIC_COMP_V1) {
1787                 comp_v1 = buf->lb_buf;
1788                 comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
1789                 if (comp_cnt == 0)
1790                         GOTO(unlock, rc = -EINVAL);
1791                 mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
1792                 mo->ldo_flr_state = le16_to_cpu(comp_v1->lcm_flags) &
1793                                         LCM_FL_FLR_MASK;
1794                 mo->ldo_is_composite = 1;
1795         } else if (magic == LOV_MAGIC_FOREIGN) {
1796                 struct lov_foreign_md *foreign;
1797                 size_t length;
1798
1799                 if (buf->lb_len < offsetof(typeof(*foreign), lfm_value)) {
1800                         CDEBUG(D_LAYOUT,
1801                                "buf len %zu < min lov_foreign_md size (%zu)\n",
1802                                buf->lb_len,
1803                                offsetof(typeof(*foreign), lfm_value));
1804                         GOTO(out, rc = -EINVAL);
1805                 }
1806                 foreign = (struct lov_foreign_md *)buf->lb_buf;
1807                 length = foreign_size_le(foreign);
1808                 if (buf->lb_len < length) {
1809                         CDEBUG(D_LAYOUT,
1810                                "buf len %zu < this lov_foreign_md size (%zu)\n",
1811                                buf->lb_len, length);
1812                         GOTO(out, rc = -EINVAL);
1813                 }
1814
1815                 /* just cache foreign LOV EA raw */
1816                 rc = lod_alloc_foreign_lov(mo, length);
1817                 if (rc)
1818                         GOTO(out, rc);
1819                 memcpy(mo->ldo_foreign_lov, buf->lb_buf, length);
1820                 GOTO(out, rc);
1821         } else {
1822                 mo->ldo_is_composite = 0;
1823                 comp_cnt = 1;
1824                 mirror_cnt = 0;
1825         }
1826         mo->ldo_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
1827
1828         rc = lod_alloc_comp_entries(mo, mirror_cnt, comp_cnt);
1829         if (rc)
1830                 GOTO(unlock, rc);
1831
1832         for (i = 0; i < comp_cnt; i++) {
1833                 struct lu_extent *ext;
1834                 char    *pool_name;
1835                 __u32   offs;
1836
1837                 lod_comp = &mo->ldo_comp_entries[i];
1838
1839                 if (mo->ldo_is_composite) {
1840                         offs = le32_to_cpu(comp_v1->lcm_entries[i].lcme_offset);
1841                         v1 = (struct lov_mds_md_v1 *)((char *)comp_v1 + offs);
1842                         v3 = (struct lov_mds_md_v3 *)v1;
1843                         magic = le32_to_cpu(v1->lmm_magic);
1844
1845                         ext = &comp_v1->lcm_entries[i].lcme_extent;
1846                         lod_comp->llc_extent.e_start =
1847                                 le64_to_cpu(ext->e_start);
1848                         lod_comp->llc_extent.e_end = le64_to_cpu(ext->e_end);
1849                         lod_comp->llc_flags =
1850                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags);
1851                         if (lod_comp->llc_flags & LCME_FL_NOSYNC)
1852                                 lod_comp->llc_timestamp = le64_to_cpu(
1853                                         comp_v1->lcm_entries[i].lcme_timestamp);
1854                         lod_comp->llc_id =
1855                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_id);
1856                         if (lod_comp->llc_id == LCME_ID_INVAL)
1857                                 GOTO(out, rc = -EINVAL);
1858                 }
1859
1860                 pool_name = NULL;
1861                 if (magic == LOV_MAGIC_V1) {
1862                         objs = &v1->lmm_objects[0];
1863                 } else if (magic == LOV_MAGIC_V3) {
1864                         objs = &v3->lmm_objects[0];
1865                         if (v3->lmm_pool_name[0] != '\0')
1866                                 pool_name = v3->lmm_pool_name;
1867                 } else {
1868                         CDEBUG(D_LAYOUT, "Invalid magic %x\n", magic);
1869                         GOTO(out, rc = -EINVAL);
1870                 }
1871
1872                 lod_comp->llc_pattern = le32_to_cpu(v1->lmm_pattern);
1873                 lod_comp->llc_stripe_size = le32_to_cpu(v1->lmm_stripe_size);
1874                 lod_comp->llc_stripe_count = le16_to_cpu(v1->lmm_stripe_count);
1875                 lod_comp->llc_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
1876                 /**
1877                  * The stripe_offset of an uninit-ed component is stored in
1878                  * the lmm_layout_gen
1879                  */
1880                 if (mo->ldo_is_composite && !lod_comp_inited(lod_comp))
1881                         lod_comp->llc_stripe_offset = lod_comp->llc_layout_gen;
1882                 lod_obj_set_pool(mo, i, pool_name);
1883
1884                 if ((!mo->ldo_is_composite || lod_comp_inited(lod_comp)) &&
1885                     !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
1886                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT)) {
1887                         rc = lod_initialize_objects(env, mo, objs, i);
1888                         if (rc)
1889                                 GOTO(out, rc);
1890                 }
1891         }
1892
1893         rc = lod_fill_mirrors(mo);
1894         GOTO(out, rc);
1895 out:
1896         if (rc)
1897                 lod_striping_free_nolock(env, mo);
1898 unlock:
1899         mutex_unlock(&mo->ldo_layout_mutex);
1900
1901         RETURN(rc);
1902 }
1903
1904 /**
1905  * Parse suggested striping configuration.
1906  *
1907  * The caller gets a suggested striping configuration from a number of sources
1908  * including per-directory default and applications. Then it needs to verify
1909  * the suggested striping is valid, apply missing bits and store the resulting
1910  * configuration in the object to be used by the allocator later. Must not be
1911  * called concurrently against the same object. It's OK to provide a
1912  * fully-defined striping.
1913  *
1914  * \param[in] env       execution environment for this thread
1915  * \param[in] lo        LOD object
1916  * \param[in] buf       buffer containing the striping
1917  *
1918  * \retval 0            on success
1919  * \retval negative     negated errno on error
1920  */
1921 int lod_qos_parse_config(const struct lu_env *env, struct lod_object *lo,
1922                          const struct lu_buf *buf)
1923 {
1924         struct lod_layout_component *lod_comp;
1925         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
1926         struct lov_desc *desc = &d->lod_desc;
1927         struct lov_user_md_v1 *v1 = NULL;
1928         struct lov_user_md_v3 *v3 = NULL;
1929         struct lov_comp_md_v1 *comp_v1 = NULL;
1930         struct lov_foreign_md *lfm = NULL;
1931         char def_pool[LOV_MAXPOOLNAME + 1];
1932         __u32 magic;
1933         __u16 comp_cnt;
1934         __u16 mirror_cnt;
1935         int i, rc;
1936         ENTRY;
1937
1938         if (buf == NULL || buf->lb_buf == NULL || buf->lb_len == 0)
1939                 RETURN(0);
1940
1941         memset(def_pool, 0, sizeof(def_pool));
1942         if (lo->ldo_comp_entries != NULL)
1943                 lod_layout_get_pool(lo->ldo_comp_entries, lo->ldo_comp_cnt,
1944                                     def_pool, sizeof(def_pool));
1945
1946         /* free default striping info */
1947         if (lo->ldo_is_foreign)
1948                 lod_free_foreign_lov(lo);
1949         else
1950                 lod_free_comp_entries(lo);
1951
1952         rc = lod_verify_striping(d, lo, buf, false);
1953         if (rc)
1954                 RETURN(-EINVAL);
1955
1956         v3 = buf->lb_buf;
1957         v1 = buf->lb_buf;
1958         comp_v1 = buf->lb_buf;
1959         /* {lmm,lfm}_magic position/length work for all LOV formats */
1960         magic = v1->lmm_magic;
1961
1962         if (unlikely(le32_to_cpu(magic) & LOV_MAGIC_DEFINED)) {
1963                 /* try to use as fully defined striping */
1964                 rc = lod_use_defined_striping(env, lo, buf);
1965                 RETURN(rc);
1966         }
1967
1968         switch (magic) {
1969         case __swab32(LOV_USER_MAGIC_V1):
1970                 lustre_swab_lov_user_md_v1(v1);
1971                 magic = v1->lmm_magic;
1972                 /* fall through */
1973         case LOV_USER_MAGIC_V1:
1974                 break;
1975         case __swab32(LOV_USER_MAGIC_V3):
1976                 lustre_swab_lov_user_md_v3(v3);
1977                 magic = v3->lmm_magic;
1978                 /* fall through */
1979         case LOV_USER_MAGIC_V3:
1980                 break;
1981         case __swab32(LOV_USER_MAGIC_SPECIFIC):
1982                 lustre_swab_lov_user_md_v3(v3);
1983                 lustre_swab_lov_user_md_objects(v3->lmm_objects,
1984                                                 v3->lmm_stripe_count);
1985                 magic = v3->lmm_magic;
1986                 /* fall through */
1987         case LOV_USER_MAGIC_SPECIFIC:
1988                 break;
1989         case __swab32(LOV_USER_MAGIC_COMP_V1):
1990                 lustre_swab_lov_comp_md_v1(comp_v1);
1991                 magic = comp_v1->lcm_magic;
1992                 /* fall trhough */
1993         case LOV_USER_MAGIC_COMP_V1:
1994                 break;
1995         case __swab32(LOV_USER_MAGIC_FOREIGN):
1996                 lfm = buf->lb_buf;
1997                 __swab32s(&lfm->lfm_magic);
1998                 __swab32s(&lfm->lfm_length);
1999                 __swab32s(&lfm->lfm_type);
2000                 __swab32s(&lfm->lfm_flags);
2001                 magic = lfm->lfm_magic;
2002                 /* fall through */
2003         case LOV_USER_MAGIC_FOREIGN:
2004                 if (!lfm)
2005                         lfm = buf->lb_buf;
2006                 rc = lod_alloc_foreign_lov(lo, foreign_size(lfm));
2007                 if (rc)
2008                         RETURN(rc);
2009                 memcpy(lo->ldo_foreign_lov, buf->lb_buf, foreign_size(lfm));
2010                 RETURN(0);
2011         default:
2012                 CERROR("%s: unrecognized magic %X\n",
2013                        lod2obd(d)->obd_name, magic);
2014                 RETURN(-EINVAL);
2015         }
2016
2017         lustre_print_user_md(D_OTHER, v1, "parse config");
2018
2019         if (magic == LOV_USER_MAGIC_COMP_V1) {
2020                 comp_cnt = comp_v1->lcm_entry_count;
2021                 if (comp_cnt == 0)
2022                         RETURN(-EINVAL);
2023                 mirror_cnt =  comp_v1->lcm_mirror_count + 1;
2024                 if (mirror_cnt > 1)
2025                         lo->ldo_flr_state = LCM_FL_RDONLY;
2026                 lo->ldo_is_composite = 1;
2027         } else {
2028                 comp_cnt = 1;
2029                 mirror_cnt = 0;
2030                 lo->ldo_is_composite = 0;
2031         }
2032
2033         rc = lod_alloc_comp_entries(lo, mirror_cnt, comp_cnt);
2034         if (rc)
2035                 RETURN(rc);
2036
2037         LASSERT(lo->ldo_comp_entries);
2038
2039         for (i = 0; i < comp_cnt; i++) {
2040                 struct pool_desc        *pool;
2041                 struct lu_extent        *ext;
2042                 char    *pool_name;
2043
2044                 lod_comp = &lo->ldo_comp_entries[i];
2045
2046                 if (lo->ldo_is_composite) {
2047                         v1 = (struct lov_user_md *)((char *)comp_v1 +
2048                                         comp_v1->lcm_entries[i].lcme_offset);
2049                         ext = &comp_v1->lcm_entries[i].lcme_extent;
2050                         lod_comp->llc_extent = *ext;
2051                         lod_comp->llc_flags =
2052                                 comp_v1->lcm_entries[i].lcme_flags &
2053                                         LCME_USER_FLAGS;
2054                 }
2055
2056                 pool_name = NULL;
2057                 if (v1->lmm_magic == LOV_USER_MAGIC_V3 ||
2058                     v1->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2059                         v3 = (struct lov_user_md_v3 *)v1;
2060                         if (v3->lmm_pool_name[0] != '\0')
2061                                 pool_name = v3->lmm_pool_name;
2062
2063                         if (v3->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2064                                 rc = lod_comp_copy_ost_lists(lod_comp, v3);
2065                                 if (rc)
2066                                         GOTO(free_comp, rc);
2067                         }
2068                 }
2069
2070                 if (pool_name == NULL && def_pool[0] != '\0')
2071                         pool_name = def_pool;
2072
2073                 if (v1->lmm_pattern == 0)
2074                         v1->lmm_pattern = LOV_PATTERN_RAID0;
2075                 if (lov_pattern(v1->lmm_pattern) != LOV_PATTERN_RAID0 &&
2076                     lov_pattern(v1->lmm_pattern) != LOV_PATTERN_MDT &&
2077                     lov_pattern(v1->lmm_pattern) !=
2078                         (LOV_PATTERN_RAID0 | LOV_PATTERN_OVERSTRIPING)) {
2079                         CDEBUG(D_LAYOUT, "%s: invalid pattern: %x\n",
2080                                lod2obd(d)->obd_name, v1->lmm_pattern);
2081                         GOTO(free_comp, rc = -EINVAL);
2082                 }
2083
2084                 lod_comp->llc_pattern = v1->lmm_pattern;
2085                 lod_comp->llc_stripe_size = desc->ld_default_stripe_size;
2086                 if (v1->lmm_stripe_size)
2087                         lod_comp->llc_stripe_size = v1->lmm_stripe_size;
2088
2089                 lod_comp->llc_stripe_count = desc->ld_default_stripe_count;
2090                 if (v1->lmm_stripe_count ||
2091                     lov_pattern(v1->lmm_pattern) == LOV_PATTERN_MDT)
2092                         lod_comp->llc_stripe_count = v1->lmm_stripe_count;
2093
2094                 lod_comp->llc_stripe_offset = v1->lmm_stripe_offset;
2095                 lod_obj_set_pool(lo, i, pool_name);
2096
2097                 LASSERT(ergo(lov_pattern(lod_comp->llc_pattern) ==
2098                              LOV_PATTERN_MDT, lod_comp->llc_stripe_count == 0));
2099
2100                 if (pool_name == NULL)
2101                         continue;
2102
2103                 /* In the function below, .hs_keycmp resolves to
2104                  * pool_hashkey_keycmp() */
2105                 /* coverity[overrun-buffer-val] */
2106                 pool = lod_find_pool(d, pool_name);
2107                 if (pool == NULL)
2108                         continue;
2109
2110                 if (lod_comp->llc_stripe_offset != LOV_OFFSET_DEFAULT) {
2111                         rc = lod_check_index_in_pool(
2112                                         lod_comp->llc_stripe_offset, pool);
2113                         if (rc < 0) {
2114                                 lod_pool_putref(pool);
2115                                 CDEBUG(D_LAYOUT, "%s: invalid offset, %u\n",
2116                                        lod2obd(d)->obd_name,
2117                                        lod_comp->llc_stripe_offset);
2118                                 GOTO(free_comp, rc = -EINVAL);
2119                         }
2120                 }
2121
2122                 if (lod_comp->llc_stripe_count > pool_tgt_count(pool) &&
2123                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
2124                         lod_comp->llc_stripe_count = pool_tgt_count(pool);
2125
2126                 lod_pool_putref(pool);
2127         }
2128
2129         RETURN(0);
2130
2131 free_comp:
2132         lod_free_comp_entries(lo);
2133         RETURN(rc);
2134 }
2135
2136 /**
2137  * prepare enough OST avoidance bitmap space
2138  */
2139 int lod_prepare_avoidance(const struct lu_env *env, struct lod_object *lo)
2140 {
2141         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2142         struct lod_tgt_descs *ltds = &lod->lod_ost_descs;
2143         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2144         struct cfs_bitmap *bitmap = NULL;
2145         __u32 *new_oss = NULL;
2146
2147         lag->lag_ost_avail = ltds->ltd_tgtnr;
2148
2149         /* reset OSS avoid guide array */
2150         lag->lag_oaa_count = 0;
2151         if (lag->lag_oss_avoid_array && lag->lag_oaa_size < ltds->ltd_tgtnr) {
2152                 OBD_FREE(lag->lag_oss_avoid_array,
2153                          sizeof(__u32) * lag->lag_oaa_size);
2154                 lag->lag_oss_avoid_array = NULL;
2155                 lag->lag_oaa_size = 0;
2156         }
2157
2158         /* init OST avoid guide bitmap */
2159         if (lag->lag_ost_avoid_bitmap) {
2160                 if (ltds->ltd_tgtnr <= lag->lag_ost_avoid_bitmap->size) {
2161                         CFS_RESET_BITMAP(lag->lag_ost_avoid_bitmap);
2162                 } else {
2163                         CFS_FREE_BITMAP(lag->lag_ost_avoid_bitmap);
2164                         lag->lag_ost_avoid_bitmap = NULL;
2165                 }
2166         }
2167
2168         if (!lag->lag_ost_avoid_bitmap) {
2169                 bitmap = CFS_ALLOCATE_BITMAP(ltds->ltd_tgtnr);
2170                 if (!bitmap)
2171                         return -ENOMEM;
2172         }
2173
2174         if (!lag->lag_oss_avoid_array) {
2175                 /**
2176                  * usually there are multiple OSTs in one OSS, but we don't
2177                  * know the exact OSS number, so we choose a safe option,
2178                  * using OST count to allocate the array to store the OSS
2179                  * id.
2180                  */
2181                 OBD_ALLOC(new_oss, sizeof(*new_oss) * ltds->ltd_tgtnr);
2182                 if (!new_oss) {
2183                         CFS_FREE_BITMAP(bitmap);
2184                         return -ENOMEM;
2185                 }
2186         }
2187
2188         if (new_oss) {
2189                 lag->lag_oss_avoid_array = new_oss;
2190                 lag->lag_oaa_size = ltds->ltd_tgtnr;
2191         }
2192         if (bitmap)
2193                 lag->lag_ost_avoid_bitmap = bitmap;
2194
2195         return 0;
2196 }
2197
2198 /**
2199  * Collect information of used OSTs and OSSs in the overlapped components
2200  * of other mirrors
2201  */
2202 void lod_collect_avoidance(struct lod_object *lo, struct lod_avoid_guide *lag,
2203                            int comp_idx)
2204 {
2205         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2206         struct lod_layout_component *lod_comp = &lo->ldo_comp_entries[comp_idx];
2207         struct cfs_bitmap *bitmap = lag->lag_ost_avoid_bitmap;
2208         int i, j;
2209
2210         /* iterate mirrors */
2211         for (i = 0; i < lo->ldo_mirror_count; i++) {
2212                 struct lod_layout_component *comp;
2213
2214                 /**
2215                  * skip mirror containing component[comp_idx], we only
2216                  * collect OSTs info of conflicting component in other mirrors,
2217                  * so that during read, if OSTs of a mirror's component are
2218                  * not available, we still have other mirror with different
2219                  * OSTs to read the data.
2220                  */
2221                 comp = &lo->ldo_comp_entries[lo->ldo_mirrors[i].lme_start];
2222                 if (comp->llc_id != LCME_ID_INVAL &&
2223                     mirror_id_of(comp->llc_id) ==
2224                                                 mirror_id_of(lod_comp->llc_id))
2225                         continue;
2226
2227                 /* iterate components of a mirror */
2228                 lod_foreach_mirror_comp(comp, lo, i) {
2229                         /**
2230                          * skip non-overlapped or un-instantiated components,
2231                          * NOTE: don't use lod_comp_inited(comp) to judge
2232                          * whether @comp has been inited, since during
2233                          * declare phase, comp->llc_stripe has been allocated
2234                          * while it's init flag not been set until the exec
2235                          * phase.
2236                          */
2237                         if (!lu_extent_is_overlapped(&comp->llc_extent,
2238                                                      &lod_comp->llc_extent) ||
2239                             !comp->llc_stripe)
2240                                 continue;
2241
2242                         /**
2243                          * collect used OSTs index and OSS info from a
2244                          * component
2245                          */
2246                         for (j = 0; j < comp->llc_stripe_count; j++) {
2247                                 struct lod_tgt_desc *ost;
2248                                 struct lu_svr_qos *lsq;
2249                                 int k;
2250
2251                                 ost = OST_TGT(lod, comp->llc_ost_indices[j]);
2252                                 lsq = ost->ltd_qos.ltq_svr;
2253
2254                                 if (cfs_bitmap_check(bitmap, ost->ltd_index))
2255                                         continue;
2256
2257                                 QOS_DEBUG("OST%d used in conflicting mirror "
2258                                           "component\n", ost->ltd_index);
2259                                 cfs_bitmap_set(bitmap, ost->ltd_index);
2260                                 lag->lag_ost_avail--;
2261
2262                                 for (k = 0; k < lag->lag_oaa_count; k++) {
2263                                         if (lag->lag_oss_avoid_array[k] ==
2264                                             lsq->lsq_id)
2265                                                 break;
2266                                 }
2267                                 if (k == lag->lag_oaa_count) {
2268                                         lag->lag_oss_avoid_array[k] =
2269                                                                 lsq->lsq_id;
2270                                         lag->lag_oaa_count++;
2271                                 }
2272                         }
2273                 }
2274         }
2275 }
2276
2277 /**
2278  * Create a striping for an obejct.
2279  *
2280  * The function creates a new striping for the object. The function tries QoS
2281  * algorithm first unless free space is distributed evenly among OSTs, but
2282  * by default RR algorithm is preferred due to internal concurrency (QoS is
2283  * serialized). The caller must ensure no concurrent calls to the function
2284  * are made against the same object.
2285  *
2286  * \param[in] env       execution environment for this thread
2287  * \param[in] lo        LOD object
2288  * \param[in] attr      attributes OST objects will be declared with
2289  * \param[in] th        transaction handle
2290  * \param[in] comp_idx  index of ldo_comp_entries
2291  *
2292  * \retval 0            on success
2293  * \retval negative     negated errno on error
2294  */
2295 int lod_qos_prep_create(const struct lu_env *env, struct lod_object *lo,
2296                         struct lu_attr *attr, struct thandle *th,
2297                         int comp_idx)
2298 {
2299         struct lod_layout_component *lod_comp;
2300         struct lod_device      *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2301         int                     stripe_len;
2302         int                     flag = LOV_USES_ASSIGNED_STRIPE;
2303         int                     i, rc = 0;
2304         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2305         struct dt_object **stripe = NULL;
2306         __u32 *ost_indices = NULL;
2307         ENTRY;
2308
2309         LASSERT(lo);
2310         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
2311         lod_comp = &lo->ldo_comp_entries[comp_idx];
2312
2313         /* A released component is being created */
2314         if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
2315                 RETURN(0);
2316
2317         /* A Data-on-MDT component is being created */
2318         if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT)
2319                 RETURN(0);
2320
2321         if (likely(lod_comp->llc_stripe == NULL)) {
2322                 /*
2323                  * no striping has been created so far
2324                  */
2325                 LASSERT(lod_comp->llc_stripe_count);
2326                 /*
2327                  * statfs and check OST targets now, since ld_active_tgt_count
2328                  * could be changed if some OSTs are [de]activated manually.
2329                  */
2330                 lod_qos_statfs_update(env, d);
2331                 stripe_len = lod_get_stripe_count(d, lo,
2332                                                   lod_comp->llc_stripe_count,
2333                                                   lod_comp->llc_pattern &
2334                                                   LOV_PATTERN_OVERSTRIPING);
2335
2336                 if (stripe_len == 0)
2337                         GOTO(out, rc = -ERANGE);
2338                 lod_comp->llc_stripe_count = stripe_len;
2339                 OBD_ALLOC(stripe, sizeof(stripe[0]) * stripe_len);
2340                 if (stripe == NULL)
2341                         GOTO(out, rc = -ENOMEM);
2342                 OBD_ALLOC(ost_indices, sizeof(*ost_indices) * stripe_len);
2343                 if (!ost_indices)
2344                         GOTO(out, rc = -ENOMEM);
2345
2346                 lod_getref(&d->lod_ost_descs);
2347                 /* XXX: support for non-0 files w/o objects */
2348                 CDEBUG(D_OTHER, "tgt_count %d stripe_count %d\n",
2349                                 d->lod_desc.ld_tgt_count, stripe_len);
2350
2351                 if (lod_comp->llc_ostlist.op_array &&
2352                     lod_comp->llc_ostlist.op_count) {
2353                         rc = lod_alloc_ost_list(env, lo, stripe, ost_indices,
2354                                                 th, comp_idx);
2355                 } else if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT) {
2356                         /**
2357                          * collect OSTs and OSSs used in other mirrors whose
2358                          * components cross the ldo_comp_entries[comp_idx]
2359                          */
2360                         rc = lod_prepare_avoidance(env, lo);
2361                         if (rc)
2362                                 GOTO(put_ldts, rc);
2363
2364                         QOS_DEBUG("collecting conflict osts for comp[%d]\n",
2365                                   comp_idx);
2366                         lod_collect_avoidance(lo, lag, comp_idx);
2367
2368                         rc = lod_alloc_qos(env, lo, stripe, ost_indices, flag,
2369                                            th, comp_idx);
2370                         if (rc == -EAGAIN)
2371                                 rc = lod_alloc_rr(env, lo, stripe, ost_indices,
2372                                                   flag, th, comp_idx);
2373                 } else {
2374                         rc = lod_alloc_specific(env, lo, stripe, ost_indices,
2375                                                 flag, th, comp_idx);
2376                 }
2377 put_ldts:
2378                 lod_putref(d, &d->lod_ost_descs);
2379                 if (rc < 0) {
2380                         for (i = 0; i < stripe_len; i++)
2381                                 if (stripe[i] != NULL)
2382                                         dt_object_put(env, stripe[i]);
2383                         lod_comp->llc_stripe_count = 0;
2384                 } else {
2385                         lod_comp->llc_stripe = stripe;
2386                         lod_comp->llc_ost_indices = ost_indices;
2387                         lod_comp->llc_stripes_allocated = stripe_len;
2388                 }
2389         } else {
2390                 /*
2391                  * lod_qos_parse_config() found supplied buf as a predefined
2392                  * striping (not a hint), so it allocated all the object
2393                  * now we need to create them
2394                  */
2395                 for (i = 0; i < lod_comp->llc_stripe_count; i++) {
2396                         struct dt_object  *o;
2397
2398                         o = lod_comp->llc_stripe[i];
2399                         LASSERT(o);
2400
2401                         rc = lod_sub_declare_create(env, o, attr, NULL,
2402                                                     NULL, th);
2403                         if (rc < 0) {
2404                                 CERROR("can't declare create: %d\n", rc);
2405                                 break;
2406                         }
2407                 }
2408                 /**
2409                  * Clear LCME_FL_INIT for the component so that
2410                  * lod_striping_create() can create the striping objects
2411                  * in replay.
2412                  */
2413                 lod_comp_unset_init(lod_comp);
2414         }
2415
2416 out:
2417         if (rc < 0) {
2418                 if (stripe)
2419                         OBD_FREE(stripe, sizeof(stripe[0]) * stripe_len);
2420                 if (ost_indices)
2421                         OBD_FREE(ost_indices,
2422                                  sizeof(*ost_indices) * stripe_len);
2423         }
2424         RETURN(rc);
2425 }
2426
2427 int lod_prepare_create(const struct lu_env *env, struct lod_object *lo,
2428                        struct lu_attr *attr, const struct lu_buf *buf,
2429                        struct thandle *th)
2430
2431 {
2432         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2433         uint64_t size = 0;
2434         int i;
2435         int rc;
2436         ENTRY;
2437
2438         LASSERT(lo);
2439
2440         /* no OST available */
2441         /* XXX: should we be waiting a bit to prevent failures during
2442          * cluster initialization? */
2443         if (d->lod_ostnr == 0)
2444                 RETURN(-EIO);
2445
2446         /*
2447          * by this time, the object's ldo_stripe_count and ldo_stripe_size
2448          * contain default value for striping: taken from the parent
2449          * or from filesystem defaults
2450          *
2451          * in case the caller is passing lovea with new striping config,
2452          * we may need to parse lovea and apply new configuration
2453          */
2454         rc = lod_qos_parse_config(env, lo, buf);
2455         if (rc)
2456                 RETURN(rc);
2457
2458         if (attr->la_valid & LA_SIZE)
2459                 size = attr->la_size;
2460
2461         /**
2462          * prepare OST object creation for the component covering file's
2463          * size, the 1st component (including plain layout file) is always
2464          * instantiated.
2465          */
2466         for (i = 0; i < lo->ldo_comp_cnt; i++) {
2467                 struct lod_layout_component *lod_comp;
2468                 struct lu_extent *extent;
2469
2470                 lod_comp = &lo->ldo_comp_entries[i];
2471                 extent = &lod_comp->llc_extent;
2472                 QOS_DEBUG("comp[%d] %lld "DEXT"\n", i, size, PEXT(extent));
2473                 if (!lo->ldo_is_composite || size >= extent->e_start) {
2474                         rc = lod_qos_prep_create(env, lo, attr, th, i);
2475                         if (rc)
2476                                 break;
2477                 }
2478         }
2479
2480         RETURN(rc);
2481 }