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