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