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