Whamcloud - gitweb
LU-15900 hsm: don't return error on state change during mount
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.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 (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2017, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <obd_support.h>
43 #include <lustre_export.h>
44 #include <obd.h>
45 #include <lprocfs_status.h>
46 #include <lustre_log.h>
47 #include <lustre_kernelcomm.h>
48 #include "mdt_internal.h"
49
50 /**
51  * get obj and HSM attributes on a fid
52  * \param mti [IN] context
53  * \param fid [IN] object fid
54  * \param hsm [OUT] HSM meta data
55  * \retval obj or error (-ENOENT if not found)
56  */
57 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
58                                       const struct lu_fid *fid,
59                                       struct md_hsm *hsm)
60 {
61         struct md_attr          *ma;
62         struct mdt_object       *obj;
63         int                      rc;
64         ENTRY;
65
66         ma = &mti->mti_attr;
67         ma->ma_need = MA_HSM;
68         ma->ma_valid = 0;
69
70         /* find object by FID */
71         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
72         if (IS_ERR(obj))
73                 RETURN(obj);
74
75         if (!mdt_object_exists(obj)) {
76                 /* no more object */
77                 mdt_object_put(mti->mti_env, obj);
78                 RETURN(ERR_PTR(-ENOENT));
79         }
80
81         rc = mdt_attr_get_complex(mti, obj, ma);
82         if (rc) {
83                 mdt_object_put(mti->mti_env, obj);
84                 RETURN(ERR_PTR(rc));
85         }
86
87         if (ma->ma_valid & MA_HSM)
88                 *hsm = ma->ma_hsm;
89         else
90                 memset(hsm, 0, sizeof(*hsm));
91         ma->ma_valid = 0;
92         RETURN(obj);
93 }
94
95 void mdt_hsm_dump_hal(int level, const char *prefix,
96                       struct hsm_action_list *hal)
97 {
98         int                      i, sz;
99         struct hsm_action_item  *hai;
100         char                     buf[12];
101
102         CDEBUG(level, "%s: HAL header: version %X count %d"
103                       " archive_id %d flags %#llx\n",
104                prefix, hal->hal_version, hal->hal_count,
105                hal->hal_archive_id, hal->hal_flags);
106
107         hai = hai_first(hal);
108         for (i = 0; i < hal->hal_count; i++) {
109                 sz = hai->hai_len - sizeof(*hai);
110                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
111                        " cookie=%#llx"
112                        " action=%s extent=%#llx-%#llx gid=%#llx"
113                        " datalen=%d data=[%s]\n",
114                        prefix, i,
115                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
116                        hai->hai_cookie,
117                        hsm_copytool_action2name(hai->hai_action),
118                        hai->hai_extent.offset,
119                        hai->hai_extent.length,
120                        hai->hai_gid, sz,
121                        hai_dump_data_field(hai, buf, sizeof(buf)));
122                 hai = hai_next(hai);
123         }
124 }
125
126 /**
127  * data passed to llog_cat_process() callback
128  * to scan requests and take actions
129  */
130 struct hsm_scan_request {
131         int                      hal_sz;
132         int                      hal_used_sz;
133         struct hsm_action_list  *hal;
134 };
135
136 struct hsm_scan_data {
137         struct mdt_thread_info  *hsd_mti;
138         char                     hsd_fsname[MTI_NAME_MAXLEN + 1];
139         /* are we scanning the logs for housekeeping, or just looking
140          * for new work?
141          */
142         bool                     hsd_housekeeping;
143         bool                     hsd_one_restore;
144         u32                      hsd_start_cat_idx;
145         u32                      hsd_start_rec_idx;
146         int                      hsd_action_count;
147         int                      hsd_request_len; /* array alloc len */
148         int                      hsd_request_count; /* array used count */
149         struct hsm_scan_request *hsd_request;
150 };
151
152 static int mdt_cdt_waiting_cb(const struct lu_env *env,
153                               struct mdt_device *mdt,
154                               struct llog_handle *llh,
155                               struct llog_agent_req_rec *larr,
156                               struct hsm_scan_data *hsd)
157 {
158         struct coordinator *cdt = &mdt->mdt_coordinator;
159         struct hsm_scan_request *request;
160         struct hsm_action_item *hai;
161         size_t hai_size;
162         u32 archive_id;
163         bool wrapped;
164         int i;
165
166         /* Are agents full? */
167         if (atomic_read(&cdt->cdt_request_count) >= cdt->cdt_max_requests)
168                 RETURN(hsd->hsd_housekeeping ? 0 : LLOG_PROC_BREAK);
169
170         if (hsd->hsd_action_count + atomic_read(&cdt->cdt_request_count) >=
171             cdt->cdt_max_requests) {
172                 /* We cannot send any more request
173                  *
174                  *                     *** SPECIAL CASE ***
175                  *
176                  * Restore requests are too important not to schedule at least
177                  * one, everytime we can.
178                  */
179                 if (larr->arr_hai.hai_action != HSMA_RESTORE ||
180                     hsd->hsd_one_restore)
181                         RETURN(hsd->hsd_housekeeping ? 0 : LLOG_PROC_BREAK);
182         }
183
184         hai_size = cfs_size_round(larr->arr_hai.hai_len);
185         archive_id = larr->arr_archive_id;
186
187         /* Can we add this action to one of the existing HALs in hsd. */
188         request = NULL;
189         for (i = 0; i < hsd->hsd_request_count; i++) {
190                 if (hsd->hsd_request[i].hal->hal_archive_id == archive_id &&
191                     hsd->hsd_request[i].hal_used_sz + hai_size <=
192                     LDLM_MAXREQSIZE) {
193                         request = &hsd->hsd_request[i];
194                         break;
195                 }
196         }
197
198         /* Are we trying to force-schedule a request? */
199         if (hsd->hsd_action_count + atomic_read(&cdt->cdt_request_count) >=
200             cdt->cdt_max_requests) {
201                 /* Is there really no compatible hsm_scan_request? */
202                 if (!request) {
203                         for (i -= 1; i >= 0; i--) {
204                                 if (hsd->hsd_request[i].hal->hal_archive_id ==
205                                     archive_id) {
206                                         request = &hsd->hsd_request[i];
207                                         break;
208                                 }
209                         }
210                 }
211
212                 /* Make room for the hai */
213                 if (request) {
214                         /* Discard the last hai until there is enough space */
215                         do {
216                                 request->hal->hal_count--;
217
218                                 hai = hai_first(request->hal);
219                                 for (i = 0; i < request->hal->hal_count; i++)
220                                         hai = hai_next(hai);
221                                 request->hal_used_sz -=
222                                         cfs_size_round(hai->hai_len);
223                                 hsd->hsd_action_count--;
224                         } while (request->hal_used_sz + hai_size >
225                                  LDLM_MAXREQSIZE);
226                 } else if (hsd->hsd_housekeeping) {
227                         struct hsm_scan_request *tmp;
228
229                         /* Discard the (whole) last hal */
230                         hsd->hsd_request_count--;
231                         LASSERT(hsd->hsd_request_count >= 0);
232                         tmp = &hsd->hsd_request[hsd->hsd_request_count];
233                         hsd->hsd_action_count -= tmp->hal->hal_count;
234                         LASSERT(hsd->hsd_action_count >= 0);
235                         OBD_FREE(tmp->hal, tmp->hal_sz);
236                 } else {
237                         /* Bailing out, this code path is too hot */
238                         RETURN(LLOG_PROC_BREAK);
239
240                 }
241         }
242
243         if (!request) {
244                 struct hsm_action_list *hal;
245
246                 LASSERT(hsd->hsd_request_count < hsd->hsd_request_len);
247                 request = &hsd->hsd_request[hsd->hsd_request_count];
248
249                 /* allocates hai vector size just needs to be large
250                  * enough */
251                 request->hal_sz = sizeof(*request->hal) +
252                         cfs_size_round(MTI_NAME_MAXLEN + 1) + 2 * hai_size;
253                 OBD_ALLOC_LARGE(hal, request->hal_sz);
254                 if (!hal)
255                         RETURN(-ENOMEM);
256
257                 hal->hal_version = HAL_VERSION;
258                 strlcpy(hal->hal_fsname, hsd->hsd_fsname, MTI_NAME_MAXLEN + 1);
259                 hal->hal_archive_id = larr->arr_archive_id;
260                 hal->hal_flags = larr->arr_flags;
261                 hal->hal_count = 0;
262                 request->hal_used_sz = hal_size(hal);
263                 request->hal = hal;
264                 hsd->hsd_request_count++;
265         } else if (request->hal_sz < request->hal_used_sz + hai_size) {
266                 /* Not enough room, need an extension */
267                 void *hal_buffer;
268                 int sz;
269
270                 sz = min_t(int, 2 * request->hal_sz, LDLM_MAXREQSIZE);
271                 LASSERT(request->hal_used_sz + hai_size < sz);
272
273                 OBD_ALLOC_LARGE(hal_buffer, sz);
274                 if (!hal_buffer)
275                         RETURN(-ENOMEM);
276
277                 memcpy(hal_buffer, request->hal, request->hal_used_sz);
278                 OBD_FREE_LARGE(request->hal, request->hal_sz);
279                 request->hal = hal_buffer;
280                 request->hal_sz = sz;
281         }
282
283         hai = hai_first(request->hal);
284         for (i = 0; i < request->hal->hal_count; i++)
285                 hai = hai_next(hai);
286
287         memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
288
289         request->hal_used_sz += hai_size;
290         request->hal->hal_count++;
291
292         hsd->hsd_action_count++;
293
294         switch (hai->hai_action) {
295         case HSMA_CANCEL:
296                 break;
297         case HSMA_RESTORE:
298                 hsd->hsd_one_restore = true;
299                 fallthrough;
300         default:
301                 cdt_agent_record_hash_add(cdt, hai->hai_cookie,
302                                           llh->lgh_hdr->llh_cat_idx,
303                                           larr->arr_hdr.lrh_index);
304         }
305
306         wrapped = llh->lgh_hdr->llh_cat_idx >= llh->lgh_last_idx &&
307                   llh->lgh_hdr->llh_count > 1;
308         if ((!wrapped && llh->lgh_hdr->llh_cat_idx > hsd->hsd_start_cat_idx) ||
309             (wrapped && llh->lgh_hdr->llh_cat_idx < hsd->hsd_start_cat_idx) ||
310             (llh->lgh_hdr->llh_cat_idx == hsd->hsd_start_cat_idx &&
311              larr->arr_hdr.lrh_index > hsd->hsd_start_rec_idx)) {
312                 hsd->hsd_start_cat_idx = llh->lgh_hdr->llh_cat_idx;
313                 hsd->hsd_start_rec_idx = larr->arr_hdr.lrh_index;
314         }
315
316         RETURN(0);
317 }
318
319 static int mdt_cdt_started_cb(const struct lu_env *env,
320                               struct mdt_device *mdt,
321                               struct llog_handle *llh,
322                               struct llog_agent_req_rec *larr,
323                               struct hsm_scan_data *hsd)
324 {
325         struct coordinator *cdt = &mdt->mdt_coordinator;
326         struct hsm_action_item *hai = &larr->arr_hai;
327         struct cdt_agent_req *car;
328         time64_t now = ktime_get_real_seconds();
329         time64_t last;
330         enum changelog_rec_flags clf_flags;
331         int rc;
332
333         if (!hsd->hsd_housekeeping)
334                 RETURN(0);
335
336         /* we search for a running request
337          * error may happen if coordinator crashes or stopped
338          * with running request
339          */
340         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
341         if (car == NULL) {
342                 last = larr->arr_req_change;
343         } else {
344                 last = car->car_req_update;
345         }
346
347         /* test if request too long, if yes cancel it
348          * the same way the copy tool acknowledge a cancel request */
349         if (now <= last + cdt->cdt_active_req_timeout)
350                 GOTO(out_car, rc = 0);
351
352         dump_llog_agent_req_rec("request timed out, start cleaning", larr);
353
354         if (car != NULL) {
355                 car->car_req_update = now;
356                 mdt_hsm_agent_update_statistics(cdt, 0, 1, 0, &car->car_uuid);
357                 /* Remove car from memory list (LU-9075) */
358                 mdt_cdt_remove_request(cdt, hai->hai_cookie);
359         }
360
361         /* Emit a changelog record for the failed action.*/
362         clf_flags = 0;
363         hsm_set_cl_error(&clf_flags, ECANCELED);
364
365         switch (hai->hai_action) {
366         case HSMA_ARCHIVE:
367                 hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
368                 break;
369         case HSMA_RESTORE:
370                 hsm_set_cl_event(&clf_flags, HE_RESTORE);
371                 break;
372         case HSMA_REMOVE:
373                 hsm_set_cl_event(&clf_flags, HE_REMOVE);
374                 break;
375         case HSMA_CANCEL:
376                 hsm_set_cl_event(&clf_flags, HE_CANCEL);
377                 break;
378         default:
379                 /* Unknown record type, skip changelog. */
380                 clf_flags = 0;
381                 break;
382         }
383
384         if (clf_flags != 0)
385                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
386                              &hai->hai_fid);
387
388         if (hai->hai_action == HSMA_RESTORE)
389                 cdt_restore_handle_del(hsd->hsd_mti, cdt, &hai->hai_fid);
390
391         larr->arr_status = ARS_CANCELED;
392         larr->arr_req_change = now;
393         rc = llog_write(hsd->hsd_mti->mti_env, llh, &larr->arr_hdr,
394                         larr->arr_hdr.lrh_index);
395         if (rc < 0) {
396                 CERROR("%s: cannot update agent log: rc = %d\n",
397                        mdt_obd_name(mdt), rc);
398                 rc = LLOG_DEL_RECORD;
399         }
400
401         /* ct has completed a request, so a slot is available,
402          * signal the coordinator to find new work */
403         mdt_hsm_cdt_event(cdt);
404 out_car:
405         if (car != NULL)
406                 mdt_cdt_put_request(car);
407
408         RETURN(rc);
409 }
410
411 /**
412  *  llog_cat_process() callback, used to:
413  *  - find waiting request and start action
414  *  - purge canceled and done requests
415  * \param env [IN] environment
416  * \param llh [IN] llog handle
417  * \param hdr [IN] llog record
418  * \param data [IN/OUT] cb data = struct hsm_scan_data
419  * \retval 0 success
420  * \retval -ve failure
421  */
422 static int mdt_coordinator_cb(const struct lu_env *env,
423                               struct llog_handle *llh,
424                               struct llog_rec_hdr *hdr,
425                               void *data)
426 {
427         struct llog_agent_req_rec *larr = (struct llog_agent_req_rec *)hdr;
428         struct hsm_scan_data *hsd = data;
429         struct mdt_device *mdt = hsd->hsd_mti->mti_mdt;
430         struct coordinator *cdt = &mdt->mdt_coordinator;
431         ENTRY;
432
433         larr = (struct llog_agent_req_rec *)hdr;
434         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
435         switch (larr->arr_status) {
436         case ARS_WAITING:
437                 RETURN(mdt_cdt_waiting_cb(env, mdt, llh, larr, hsd));
438         case ARS_STARTED:
439                 RETURN(mdt_cdt_started_cb(env, mdt, llh, larr, hsd));
440         default:
441                 if (!hsd->hsd_housekeeping)
442                         RETURN(0);
443
444                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
445                     ktime_get_real_seconds()) {
446                         cdt_agent_record_hash_del(cdt,
447                                                   larr->arr_hai.hai_cookie);
448                         RETURN(LLOG_DEL_RECORD);
449                 }
450
451                 RETURN(0);
452         }
453 }
454
455 /* Release the ressource used by the coordinator. Called when the
456  * coordinator is stopping. */
457 static void mdt_hsm_cdt_cleanup(struct mdt_device *mdt)
458 {
459         struct coordinator              *cdt = &mdt->mdt_coordinator;
460         struct cdt_agent_req            *car, *tmp1;
461         struct hsm_agent                *ha, *tmp2;
462         struct cdt_restore_handle       *crh, *tmp3;
463         struct mdt_thread_info          *cdt_mti;
464
465         /* start cleaning */
466         down_write(&cdt->cdt_request_lock);
467         list_for_each_entry_safe(car, tmp1, &cdt->cdt_request_list,
468                                  car_request_list) {
469                 cfs_hash_del(cdt->cdt_request_cookie_hash,
470                              &car->car_hai->hai_cookie,
471                              &car->car_cookie_hash);
472                 list_del(&car->car_request_list);
473                 mdt_cdt_put_request(car);
474         }
475         up_write(&cdt->cdt_request_lock);
476
477         down_write(&cdt->cdt_agent_lock);
478         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
479                 list_del(&ha->ha_list);
480                 if (ha->ha_archive_cnt != 0)
481                         OBD_FREE_PTR_ARRAY(ha->ha_archive_id,
482                                            ha->ha_archive_cnt);
483                 OBD_FREE_PTR(ha);
484         }
485         up_write(&cdt->cdt_agent_lock);
486
487         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
488         mutex_lock(&cdt->cdt_restore_lock);
489         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_handle_list,
490                                  crh_list) {
491                 list_del(&crh->crh_list);
492                 /* give back layout lock */
493                 mdt_object_unlock(cdt_mti, NULL, &crh->crh_lh, 1);
494                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
495         }
496         mutex_unlock(&cdt->cdt_restore_lock);
497 }
498
499 /*
500  * Coordinator state transition table, indexed on enum cdt_states, taking
501  * from and to states. For instance since CDT_INIT to CDT_RUNNING is a
502  * valid transition, cdt_transition[CDT_INIT][CDT_RUNNING] is true.
503  */
504 static bool cdt_transition[CDT_STATES_COUNT][CDT_STATES_COUNT] = {
505         /* from -> to:    stopped init   running disable stopping */
506         /* stopped */   { true,   true,  false,  false,  false },
507         /* init */      { true,   false, true,   false,  false },
508         /* running */   { false,  false, true,   true,   true },
509         /* disable */   { false,  false, true,   true,   true },
510         /* stopping */  { true,   false, false,  false,  false }
511 };
512
513 /**
514  * Change coordinator thread state
515  * Some combinations are not valid, so catch them here.
516  *
517  * Returns 0 on success, with old_state set if not NULL, or -EINVAL if
518  * the transition was not possible.
519  */
520 static int set_cdt_state_locked(struct coordinator *cdt,
521                                 enum cdt_states new_state)
522 {
523         int rc;
524         enum cdt_states state;
525
526         state = cdt->cdt_state;
527
528         if (cdt_transition[state][new_state]) {
529                 cdt->cdt_state = new_state;
530                 rc = 0;
531         } else {
532                 CDEBUG(D_HSM,
533                        "unexpected coordinator transition, from=%s, to=%s\n",
534                        cdt_mdt_state2str(state), cdt_mdt_state2str(new_state));
535                 rc = -EINVAL;
536         }
537
538         return rc;
539 }
540
541 static int set_cdt_state(struct coordinator *cdt, enum cdt_states new_state)
542 {
543         int rc;
544
545         mutex_lock(&cdt->cdt_state_lock);
546         rc = set_cdt_state_locked(cdt, new_state);
547         mutex_unlock(&cdt->cdt_state_lock);
548
549         return rc;
550 }
551
552 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti);
553
554 static void cdt_start_pending_restore(struct mdt_device *mdt,
555                                       struct coordinator *cdt)
556 {
557         struct mdt_thread_info *cdt_mti;
558         unsigned int i = 0;
559         int rc;
560
561         /* wait until MDD initialize hsm actions llog */
562         while (!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state) && i < obd_timeout) {
563                 schedule_timeout_interruptible(cfs_time_seconds(1));
564                 i++;
565         }
566         if (!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state))
567                 CWARN("%s: trying to init HSM before MDD\n", mdt_obd_name(mdt));
568
569         /* set up list of started restore requests */
570         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
571         rc = mdt_hsm_pending_restore(cdt_mti);
572         if (rc)
573                 CERROR("%s: cannot take the layout locks needed for registered restore: %d\n",
574                        mdt_obd_name(mdt), rc);
575
576 }
577
578 /**
579  * coordinator thread
580  * \param data [IN] obd device
581  * \retval 0 success
582  * \retval -ve failure
583  */
584 static int mdt_coordinator(void *data)
585 {
586         struct mdt_thread_info  *mti = data;
587         struct mdt_device       *mdt = mti->mti_mdt;
588         struct coordinator      *cdt = &mdt->mdt_coordinator;
589         struct hsm_scan_data     hsd = { NULL };
590         time64_t                 last_housekeeping = 0;
591         size_t request_sz = 0;
592         int rc;
593         ENTRY;
594
595         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
596                mdt_obd_name(mdt), current->pid);
597
598         hsd.hsd_mti = mti;
599         obd_uuid2fsname(hsd.hsd_fsname, mdt_obd_name(mdt),
600                         sizeof(hsd.hsd_fsname));
601
602         set_cdt_state(cdt, CDT_RUNNING);
603
604         /* Inform mdt_hsm_cdt_start(). */
605         wake_up(&cdt->cdt_waitq);
606         cdt_start_pending_restore(mdt, cdt);
607
608         while (1) {
609                 int i;
610                 int update_idx = 0;
611                 int updates_sz;
612                 int updates_cnt;
613                 u32 start_cat_idx;
614                 u32 start_rec_idx;
615                 struct hsm_record_update *updates;
616
617                 /* Limit execution of the expensive requests traversal
618                  * to at most one second. This prevents repeatedly
619                  * locking/unlocking the catalog for each request
620                  * and preventing other HSM operations from happening
621                  */
622                 wait_event_interruptible_timeout(cdt->cdt_waitq,
623                                                  kthread_should_stop() ||
624                                                  cdt->cdt_wakeup_coordinator,
625                                                  cfs_time_seconds(1));
626
627                 cdt->cdt_wakeup_coordinator = false;
628                 CDEBUG(D_HSM, "coordinator resumes\n");
629
630                 if (kthread_should_stop()) {
631                         CDEBUG(D_HSM, "Coordinator stops\n");
632                         rc = 0;
633                         break;
634                 }
635
636                 /* if coordinator is suspended continue to wait */
637                 if (cdt->cdt_state == CDT_DISABLE) {
638                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
639                         continue;
640                 }
641
642                 /* If no event, and no housekeeping to do, continue to
643                  * wait. */
644                 if (last_housekeeping + cdt->cdt_loop_period <=
645                     ktime_get_real_seconds()) {
646                         last_housekeeping = ktime_get_real_seconds();
647                         hsd.hsd_housekeeping = true;
648                         start_cat_idx = 0;
649                         start_rec_idx = 0;
650                 } else if (cdt->cdt_event) {
651                         hsd.hsd_housekeeping = false;
652                         start_cat_idx = hsd.hsd_start_cat_idx;
653                         start_rec_idx = hsd.hsd_start_rec_idx;
654                 } else {
655                         continue;
656                 }
657
658                 cdt->cdt_event = false;
659
660                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
661
662                 if (hsd.hsd_request_len != cdt->cdt_max_requests) {
663                         /* cdt_max_requests has changed,
664                          * we need to allocate a new buffer
665                          */
666                         struct hsm_scan_request *tmp = NULL;
667                         int max_requests = cdt->cdt_max_requests;
668                         OBD_ALLOC_LARGE(tmp, max_requests *
669                                         sizeof(struct hsm_scan_request));
670                         if (!tmp) {
671                                 CERROR("Failed to resize request buffer, "
672                                        "keeping it at %d\n",
673                                        hsd.hsd_request_len);
674                         } else {
675                                 if (hsd.hsd_request != NULL)
676                                         OBD_FREE_LARGE(hsd.hsd_request,
677                                                        request_sz);
678
679                                 hsd.hsd_request_len = max_requests;
680                                 request_sz = hsd.hsd_request_len *
681                                         sizeof(struct hsm_scan_request);
682                                 hsd.hsd_request = tmp;
683                         }
684                 }
685
686                 hsd.hsd_action_count = 0;
687                 hsd.hsd_request_count = 0;
688                 hsd.hsd_one_restore = false;
689
690                 rc = cdt_llog_process(mti->mti_env, mdt, mdt_coordinator_cb,
691                                       &hsd, start_cat_idx, start_rec_idx,
692                                       WRITE);
693                 if (rc < 0)
694                         goto clean_cb_alloc;
695
696                 CDEBUG(D_HSM, "found %d requests to send\n",
697                        hsd.hsd_request_count);
698
699                 if (list_empty(&cdt->cdt_agents)) {
700                         CDEBUG(D_HSM, "no agent available, "
701                                       "coordinator sleeps\n");
702                         /* reset HSM scanning index range. */
703                         hsd.hsd_start_cat_idx = start_cat_idx;
704                         hsd.hsd_start_rec_idx = start_rec_idx;
705                         goto clean_cb_alloc;
706                 }
707
708                 /* Compute how many HAI we have in all the requests */
709                 updates_cnt = 0;
710                 for (i = 0; i < hsd.hsd_request_count; i++) {
711                         const struct hsm_scan_request *request =
712                                 &hsd.hsd_request[i];
713
714                         updates_cnt += request->hal->hal_count;
715                 }
716
717                 /* Allocate a temporary array to store the cookies to
718                  * update, and their status. */
719                 updates_sz = updates_cnt * sizeof(*updates);
720                 OBD_ALLOC_LARGE(updates, updates_sz);
721                 if (updates == NULL) {
722                         CERROR("%s: Cannot allocate memory (%d bytes) "
723                                "for %d updates. Too many HSM requests?\n",
724                                mdt_obd_name(mdt), updates_sz, updates_cnt);
725                         goto clean_cb_alloc;
726                 }
727
728                 /* here hsd contains a list of requests to be started */
729                 for (i = 0; i < hsd.hsd_request_count; i++) {
730                         struct hsm_scan_request *request = &hsd.hsd_request[i];
731                         struct hsm_action_list  *hal = request->hal;
732                         struct hsm_action_item  *hai;
733                         int                      j;
734
735                         /* still room for work ? */
736                         if (atomic_read(&cdt->cdt_request_count) >=
737                             cdt->cdt_max_requests)
738                                 break;
739
740                         rc = mdt_hsm_agent_send(mti, hal, 0);
741                         /* if failure, we suppose it is temporary
742                          * if the copy tool failed to do the request
743                          * it has to use hsm_progress
744                          */
745
746                         /* set up cookie vector to set records status
747                          * after copy tools start or failed
748                          */
749                         hai = hai_first(hal);
750                         for (j = 0; j < hal->hal_count; j++) {
751                                 updates[update_idx].cookie = hai->hai_cookie;
752                                 updates[update_idx].status =
753                                         (rc ? ARS_WAITING : ARS_STARTED);
754                                 hai = hai_next(hai);
755                                 update_idx++;
756                         }
757
758                         /* TODO: narrow down the HSM action range that already
759                          * scanned accroding to the cookies when a failure
760                          * occurs.
761                          */
762                         if (rc) {
763                                 hsd.hsd_start_cat_idx = start_cat_idx;
764                                 hsd.hsd_start_rec_idx = start_rec_idx;
765                         }
766                 }
767
768                 if (update_idx) {
769                         rc = mdt_agent_record_update(mti, updates, update_idx);
770                         if (rc)
771                                 CERROR("%s: mdt_agent_record_update() failed, "
772                                        "rc=%d, cannot update records "
773                                        "for %d cookies\n",
774                                        mdt_obd_name(mdt), rc, update_idx);
775                 }
776
777                 OBD_FREE_LARGE(updates, updates_sz);
778
779 clean_cb_alloc:
780                 /* free hal allocated by callback */
781                 for (i = 0; i < hsd.hsd_request_count; i++) {
782                         struct hsm_scan_request *request = &hsd.hsd_request[i];
783
784                         OBD_FREE_LARGE(request->hal, request->hal_sz);
785                 }
786         }
787
788         if (hsd.hsd_request != NULL)
789                 OBD_FREE_LARGE(hsd.hsd_request, request_sz);
790
791         mdt_hsm_cdt_cleanup(mdt);
792
793         if (rc != 0)
794                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
795                        mdt_obd_name(mdt), current->pid, rc);
796         else
797                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
798                               " no error\n",
799                        mdt_obd_name(mdt), current->pid);
800
801         RETURN(rc);
802 }
803
804 int cdt_restore_handle_add(struct mdt_thread_info *mti, struct coordinator *cdt,
805                            const struct lu_fid *fid,
806                            const struct hsm_extent *he)
807 {
808         struct cdt_restore_handle *crh;
809         struct mdt_object *obj;
810         int rc;
811         ENTRY;
812
813         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
814         if (crh == NULL)
815                 RETURN(-ENOMEM);
816
817         crh->crh_fid = *fid;
818         /* in V1 all file is restored
819          * crh->extent.start = he->offset;
820          * crh->extent.end = he->offset + he->length;
821          */
822         crh->crh_extent.start = 0;
823         crh->crh_extent.end = he->length;
824         /* get the layout lock */
825         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
826         obj = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
827                                    MDS_INODELOCK_LAYOUT);
828         if (IS_ERR(obj))
829                 GOTO(out_crh, rc = PTR_ERR(obj));
830
831         /* We do not keep a reference on the object during the restore
832          * which can be very long. */
833         mdt_object_put(mti->mti_env, obj);
834
835         mutex_lock(&cdt->cdt_restore_lock);
836         if (unlikely(cdt->cdt_state == CDT_STOPPED ||
837                      cdt->cdt_state == CDT_STOPPING)) {
838                 mutex_unlock(&cdt->cdt_restore_lock);
839                 GOTO(out_lh, rc = -EAGAIN);
840         }
841
842         list_add_tail(&crh->crh_list, &cdt->cdt_restore_handle_list);
843         mutex_unlock(&cdt->cdt_restore_lock);
844
845         RETURN(0);
846 out_lh:
847         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
848 out_crh:
849         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
850
851         return rc;
852 }
853
854 /**
855  * lookup a restore handle by FID
856  * caller needs to hold cdt_restore_lock
857  * \param cdt [IN] coordinator
858  * \param fid [IN] FID
859  * \retval cdt_restore_handle found
860  * \retval NULL not found
861  */
862 struct cdt_restore_handle *cdt_restore_handle_find(struct coordinator *cdt,
863                                                    const struct lu_fid *fid)
864 {
865         struct cdt_restore_handle *crh;
866         ENTRY;
867
868         list_for_each_entry(crh, &cdt->cdt_restore_handle_list, crh_list) {
869                 if (lu_fid_eq(&crh->crh_fid, fid))
870                         RETURN(crh);
871         }
872
873         RETURN(NULL);
874 }
875
876 void cdt_restore_handle_del(struct mdt_thread_info *mti,
877                             struct coordinator *cdt, const struct lu_fid *fid)
878 {
879         struct cdt_restore_handle *crh;
880
881         /* give back layout lock */
882         mutex_lock(&cdt->cdt_restore_lock);
883         crh = cdt_restore_handle_find(cdt, fid);
884         if (crh != NULL)
885                 list_del(&crh->crh_list);
886         mutex_unlock(&cdt->cdt_restore_lock);
887
888         if (crh == NULL)
889                 return;
890
891         /* XXX We pass a NULL object since the restore handle does not
892          * keep a reference on the object being restored. */
893         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
894         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
895 }
896
897 /**
898  * data passed to llog_cat_process() callback
899  * to scan requests and take actions
900  */
901 struct hsm_restore_data {
902         struct mdt_thread_info  *hrd_mti;
903 };
904
905 /**
906  *  llog_cat_process() callback, used to:
907  *  - find restore request and allocate the restore handle
908  * \param env [IN] environment
909  * \param llh [IN] llog handle
910  * \param hdr [IN] llog record
911  * \param data [IN/OUT] cb data = struct hsm_restore_data
912  * \retval 0 success
913  * \retval -ve failure
914  */
915 static int hsm_restore_cb(const struct lu_env *env,
916                           struct llog_handle *llh,
917                           struct llog_rec_hdr *hdr, void *data)
918 {
919         struct llog_agent_req_rec       *larr;
920         struct hsm_restore_data         *hrd;
921         struct hsm_action_item          *hai;
922         struct mdt_thread_info          *mti;
923         struct coordinator              *cdt;
924         int rc;
925         ENTRY;
926
927         hrd = data;
928         mti = hrd->hrd_mti;
929         cdt = &mti->mti_mdt->mdt_coordinator;
930
931         larr = (struct llog_agent_req_rec *)hdr;
932         hai = &larr->arr_hai;
933         if (hai->hai_cookie >= cdt->cdt_last_cookie) {
934                 /* update the cookie to avoid collision */
935                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
936         }
937
938         if (hai->hai_action != HSMA_RESTORE ||
939             agent_req_in_final_state(larr->arr_status))
940                 RETURN(0);
941
942         /* restore request not in a final state */
943
944         /* force replay of restore requests left in started state from previous
945          * CDT context, to be canceled later if finally found to be incompatible
946          * when being re-started */
947         if (larr->arr_status == ARS_STARTED) {
948                 larr->arr_status = ARS_WAITING;
949                 larr->arr_req_change = ktime_get_real_seconds();
950                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
951                 if (rc != 0)
952                         GOTO(out, rc);
953         }
954
955         rc = cdt_restore_handle_add(mti, cdt, &hai->hai_fid, &hai->hai_extent);
956 out:
957         RETURN(rc);
958 }
959
960 /**
961  * restore coordinator state at startup
962  * the goal is to take a layout lock for each registered restore request
963  * \param mti [IN] context
964  */
965 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
966 {
967         struct hsm_restore_data  hrd;
968         int                      rc;
969         ENTRY;
970
971         hrd.hrd_mti = mti;
972
973         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, hsm_restore_cb, &hrd,
974                               0, 0, WRITE);
975
976         RETURN(rc);
977 }
978
979 int hsm_init_ucred(struct lu_ucred *uc)
980 {
981         ENTRY;
982         uc->uc_valid = UCRED_OLD;
983         uc->uc_o_uid = 0;
984         uc->uc_o_gid = 0;
985         uc->uc_o_fsuid = 0;
986         uc->uc_o_fsgid = 0;
987         uc->uc_uid = 0;
988         uc->uc_gid = 0;
989         uc->uc_fsuid = 0;
990         uc->uc_fsgid = 0;
991         uc->uc_suppgids[0] = -1;
992         uc->uc_suppgids[1] = -1;
993         uc->uc_cap = cap_combine(CAP_FS_SET, CAP_NFSD_SET);
994         uc->uc_umask = 0777;
995         uc->uc_ginfo = NULL;
996         uc->uc_identity = NULL;
997         /* always record internal HSM activity if also enabled globally */
998         uc->uc_enable_audit = 1;
999
1000         RETURN(0);
1001 }
1002
1003 /**
1004  * initialize coordinator struct
1005  * \param mdt [IN] device
1006  * \retval 0 success
1007  * \retval -ve failure
1008  */
1009 int mdt_hsm_cdt_init(struct mdt_device *mdt)
1010 {
1011         struct coordinator      *cdt = &mdt->mdt_coordinator;
1012         struct mdt_thread_info  *cdt_mti = NULL;
1013         int                      rc;
1014         ENTRY;
1015
1016         init_waitqueue_head(&cdt->cdt_waitq);
1017         init_rwsem(&cdt->cdt_llog_lock);
1018         init_rwsem(&cdt->cdt_agent_lock);
1019         init_rwsem(&cdt->cdt_request_lock);
1020         mutex_init(&cdt->cdt_restore_lock);
1021         mutex_init(&cdt->cdt_state_lock);
1022         set_cdt_state(cdt, CDT_STOPPED);
1023
1024         INIT_LIST_HEAD(&cdt->cdt_request_list);
1025         INIT_LIST_HEAD(&cdt->cdt_agents);
1026         INIT_LIST_HEAD(&cdt->cdt_restore_handle_list);
1027
1028         cdt->cdt_request_cookie_hash = cfs_hash_create("REQUEST_COOKIE_HASH",
1029                                                        CFS_HASH_BITS_MIN,
1030                                                        CFS_HASH_BITS_MAX,
1031                                                        CFS_HASH_BKT_BITS,
1032                                                        0 /* extra bytes */,
1033                                                        CFS_HASH_MIN_THETA,
1034                                                        CFS_HASH_MAX_THETA,
1035                                                 &cdt_request_cookie_hash_ops,
1036                                                        CFS_HASH_DEFAULT);
1037         if (cdt->cdt_request_cookie_hash == NULL)
1038                 RETURN(-ENOMEM);
1039
1040         cdt->cdt_agent_record_hash = cfs_hash_create("AGENT_RECORD_HASH",
1041                                                      CFS_HASH_BITS_MIN,
1042                                                      CFS_HASH_BITS_MAX,
1043                                                      CFS_HASH_BKT_BITS,
1044                                                      0 /* extra bytes */,
1045                                                      CFS_HASH_MIN_THETA,
1046                                                      CFS_HASH_MAX_THETA,
1047                                                      &cdt_agent_record_hash_ops,
1048                                                      CFS_HASH_DEFAULT);
1049         if (cdt->cdt_agent_record_hash == NULL)
1050                 GOTO(out_request_cookie_hash, rc = -ENOMEM);
1051
1052         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
1053         if (rc < 0)
1054                 GOTO(out_agent_record_hash, rc);
1055
1056         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1057         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
1058         if (rc < 0)
1059                 GOTO(out_env, rc);
1060
1061         lu_context_enter(&cdt->cdt_session);
1062         cdt->cdt_env.le_ses = &cdt->cdt_session;
1063
1064         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1065         LASSERT(cdt_mti != NULL);
1066
1067         cdt_mti->mti_env = &cdt->cdt_env;
1068         cdt_mti->mti_mdt = mdt;
1069
1070         hsm_init_ucred(mdt_ucred(cdt_mti));
1071
1072         /* default values for sysfs tunnables
1073          * can be override by MGS conf */
1074         cdt->cdt_default_archive_id = 1;
1075         cdt->cdt_grace_delay = 60;
1076         cdt->cdt_loop_period = 10;
1077         cdt->cdt_max_requests = 3;
1078         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1079         cdt->cdt_active_req_timeout = 3600;
1080
1081         /* by default do not remove archives on last unlink */
1082         cdt->cdt_remove_archive_on_last_unlink = false;
1083
1084         RETURN(0);
1085
1086 out_env:
1087         lu_env_fini(&cdt->cdt_env);
1088 out_agent_record_hash:
1089         cfs_hash_putref(cdt->cdt_agent_record_hash);
1090         cdt->cdt_agent_record_hash = NULL;
1091 out_request_cookie_hash:
1092         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1093         cdt->cdt_request_cookie_hash = NULL;
1094
1095         return rc;
1096 }
1097
1098 /**
1099  * free a coordinator thread
1100  * \param mdt [IN] device
1101  */
1102 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
1103 {
1104         struct coordinator *cdt = &mdt->mdt_coordinator;
1105         ENTRY;
1106
1107         lu_context_exit(cdt->cdt_env.le_ses);
1108         lu_context_fini(cdt->cdt_env.le_ses);
1109
1110         lu_env_fini(&cdt->cdt_env);
1111
1112         cfs_hash_putref(cdt->cdt_agent_record_hash);
1113         cdt->cdt_agent_record_hash = NULL;
1114
1115         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1116         cdt->cdt_request_cookie_hash = NULL;
1117
1118         RETURN(0);
1119 }
1120
1121 /**
1122  * start a coordinator thread
1123  * \param mdt [IN] device
1124  * \retval 0 success
1125  * \retval -ve failure
1126  */
1127 static int mdt_hsm_cdt_start(struct mdt_device *mdt)
1128 {
1129         struct coordinator *cdt = &mdt->mdt_coordinator;
1130         struct mdt_thread_info *cdt_mti;
1131         int rc;
1132         void *ptr;
1133         struct task_struct *task;
1134         ENTRY;
1135
1136         /* functions defined but not yet used
1137          * this avoid compilation warning
1138          */
1139         ptr = dump_requests;
1140
1141         rc = set_cdt_state(cdt, CDT_INIT);
1142         if (rc) {
1143                 CERROR("%s: Coordinator already started or stopping\n",
1144                        mdt_obd_name(mdt));
1145                 RETURN(-EALREADY);
1146         }
1147
1148         BUILD_BUG_ON(BIT(CDT_POLICY_SHIFT_COUNT - 1) != CDT_POLICY_LAST);
1149         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1150
1151         /* just need to be larger than previous one */
1152         /* cdt_last_cookie is protected by cdt_llog_lock */
1153         cdt->cdt_last_cookie = ktime_get_real_seconds();
1154         atomic_set(&cdt->cdt_request_count, 0);
1155         atomic_set(&cdt->cdt_archive_count, 0);
1156         atomic_set(&cdt->cdt_restore_count, 0);
1157         atomic_set(&cdt->cdt_remove_count, 0);
1158         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
1159         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
1160         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
1161
1162         /* to avoid deadlock when start is made through sysfs
1163          * sysfs entries are created by the coordinator thread
1164          */
1165         if (mdt->mdt_bottom->dd_rdonly)
1166                 RETURN(0);
1167
1168         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1169         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
1170         if (IS_ERR(task)) {
1171                 rc = PTR_ERR(task);
1172                 set_cdt_state(cdt, CDT_STOPPED);
1173                 CERROR("%s: error starting coordinator thread: %d\n",
1174                        mdt_obd_name(mdt), rc);
1175         } else {
1176                 cdt->cdt_task = task;
1177                 wait_event(cdt->cdt_waitq,
1178                            cdt->cdt_state != CDT_INIT);
1179                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
1180                        mdt_obd_name(mdt));
1181                 rc = 0;
1182         }
1183
1184         RETURN(rc);
1185 }
1186
1187 /**
1188  * stop a coordinator thread
1189  * \param mdt [IN] device
1190  */
1191 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
1192 {
1193         struct coordinator *cdt = &mdt->mdt_coordinator;
1194         int rc;
1195
1196         ENTRY;
1197         /* stop coordinator thread */
1198         rc = set_cdt_state(cdt, CDT_STOPPING);
1199         if (rc == 0) {
1200                 kthread_stop(cdt->cdt_task);
1201                 cdt->cdt_task = NULL;
1202                 set_cdt_state(cdt, CDT_STOPPED);
1203         }
1204
1205         RETURN(rc);
1206 }
1207
1208 static int mdt_hsm_set_exists(struct mdt_thread_info *mti,
1209                               const struct lu_fid *fid,
1210                               u32 archive_id)
1211 {
1212         struct mdt_object *obj;
1213         struct md_hsm mh;
1214         int rc;
1215
1216         obj = mdt_hsm_get_md_hsm(mti, fid, &mh);
1217         if (IS_ERR(obj))
1218                 GOTO(out, rc = PTR_ERR(obj));
1219
1220         if (mh.mh_flags & HS_EXISTS &&
1221             mh.mh_arch_id == archive_id)
1222                 GOTO(out_obj, rc = 0);
1223
1224         mh.mh_flags |= HS_EXISTS;
1225         mh.mh_arch_id = archive_id;
1226         rc = mdt_hsm_attr_set(mti, obj, &mh);
1227
1228 out_obj:
1229         mdt_object_put(mti->mti_env, obj);
1230 out:
1231         return rc;
1232 }
1233
1234 /**
1235  * register all requests from an hal in the memory list
1236  * \param mti [IN] context
1237  * \param hal [IN] request
1238  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1239  *  which is running the CT
1240  * \retval 0 success
1241  * \retval -ve failure
1242  */
1243 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1244                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1245 {
1246         struct mdt_device       *mdt = mti->mti_mdt;
1247         struct coordinator      *cdt = &mdt->mdt_coordinator;
1248         struct hsm_action_item  *hai;
1249         int                      rc = 0, i;
1250         ENTRY;
1251
1252         /* register request in memory list */
1253         hai = hai_first(hal);
1254         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1255                 struct cdt_agent_req *car;
1256
1257                 /* in case of a cancel request, we first mark the ondisk
1258                  * record of the request we want to stop as canceled
1259                  * this does not change the cancel record
1260                  * it will be done when updating the request status
1261                  */
1262                 if (hai->hai_action == HSMA_CANCEL) {
1263                         struct hsm_record_update update = {
1264                                 .cookie = hai->hai_cookie,
1265                                 .status = ARS_CANCELED,
1266                         };
1267
1268                         rc = mdt_agent_record_update(mti, &update, 1);
1269                         if (rc) {
1270                                 CERROR("%s: mdt_agent_record_update() failed, "
1271                                        "rc=%d, cannot update status to %s "
1272                                        "for cookie %#llx\n",
1273                                        mdt_obd_name(mdt), rc,
1274                                        agent_req_status2name(ARS_CANCELED),
1275                                        hai->hai_cookie);
1276                                 GOTO(out, rc);
1277                         }
1278
1279                         /* find the running request to set it canceled */
1280                         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
1281                         if (car != NULL) {
1282                                 car->car_canceled = 1;
1283                                 /* uuid has to be changed to the one running the
1284                                 * request to cancel */
1285                                 *uuid = car->car_uuid;
1286                                 mdt_cdt_put_request(car);
1287                         }
1288                         /* no need to memorize cancel request
1289                          * this also avoid a deadlock when we receive
1290                          * a purge all requests command
1291                          */
1292                         continue;
1293                 }
1294
1295                 if (hai->hai_action == HSMA_ARCHIVE) {
1296                         rc = mdt_hsm_set_exists(mti, &hai->hai_fid,
1297                                                 hal->hal_archive_id);
1298                         if (rc == -ENOENT)
1299                                 continue;
1300                         else if (rc < 0)
1301                                 GOTO(out, rc);
1302                 }
1303
1304                 car = mdt_cdt_alloc_request(hal->hal_archive_id, hal->hal_flags,
1305                                             uuid, hai);
1306                 if (IS_ERR(car))
1307                         GOTO(out, rc = PTR_ERR(car));
1308
1309                 rc = mdt_cdt_add_request(cdt, car);
1310                 if (rc != 0)
1311                         mdt_cdt_free_request(car);
1312         }
1313 out:
1314         RETURN(rc);
1315 }
1316
1317 /**
1318  * swap layouts between 2 fids
1319  * \param mti [IN] context
1320  * \param obj [IN]
1321  * \param dfid [IN]
1322  * \param mh_common [IN] MD HSM
1323  */
1324 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1325                             struct mdt_object *obj, const struct lu_fid *dfid,
1326                             struct md_hsm *mh_common)
1327 {
1328         struct mdt_object       *dobj;
1329         struct mdt_lock_handle  *dlh;
1330         int                      rc;
1331         ENTRY;
1332
1333         if (!mdt_object_exists(obj))
1334                 GOTO(out, rc = -ENOENT);
1335
1336         /* we already have layout lock on obj so take only
1337          * on dfid */
1338         dlh = &mti->mti_lh[MDT_LH_OLD];
1339         mdt_lock_reg_init(dlh, LCK_EX);
1340         dobj = mdt_object_find_lock(mti, dfid, dlh, MDS_INODELOCK_LAYOUT);
1341         if (IS_ERR(dobj))
1342                 GOTO(out, rc = PTR_ERR(dobj));
1343
1344         /* if copy tool closes the volatile before sending the final
1345          * progress through llapi_hsm_copy_end(), all the objects
1346          * are removed and mdd_swap_layout LBUG */
1347         if (!mdt_object_exists(dobj)) {
1348                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1349                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1350                 GOTO(out_dobj, rc = -ENOENT);
1351         }
1352         /* Since we only handle restores here, unconditionally use
1353          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1354          * be preserved in case of failure during swap_layout and not
1355          * leave a file in an intermediate but incoherent state.
1356          * But need to setup HSM xattr of data FID before, reuse
1357          * mti and mh presets for FID in hsm_cdt_request_completed(),
1358          * only need to clear RELEASED and DIRTY.
1359          */
1360         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1361         rc = mdt_hsm_attr_set(mti, dobj, mh_common);
1362         if (rc == 0)
1363                 rc = mo_swap_layouts(mti->mti_env,
1364                                      mdt_object_child(obj),
1365                                      mdt_object_child(dobj),
1366                                      SWAP_LAYOUTS_MDS_HSM);
1367         if (rc == 0) {
1368                 rc = mdt_lsom_downgrade(mti, obj);
1369                 if (rc)
1370                         CDEBUG(D_INODE,
1371                                "%s: File fid="DFID" SOM "
1372                                "downgrade failed, rc = %d\n",
1373                                mdt_obd_name(mti->mti_mdt),
1374                                PFID(mdt_object_fid(obj)), rc);
1375         }
1376 out_dobj:
1377         mdt_object_unlock_put(mti, dobj, dlh, 1);
1378 out:
1379         RETURN(rc);
1380 }
1381
1382 /**
1383  * update status of a completed request
1384  * \param mti [IN] context
1385  * \param pgs [IN] progress of the copy tool
1386  * \retval 0 success
1387  * \retval -ve failure
1388  */
1389 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1390                                      struct hsm_progress_kernel *pgs,
1391                                      const struct cdt_agent_req *car,
1392                                      enum agent_req_status *status)
1393 {
1394         const struct lu_env *env = mti->mti_env;
1395         struct mdt_device *mdt = mti->mti_mdt;
1396         struct coordinator *cdt = &mdt->mdt_coordinator;
1397         struct mdt_object *obj = NULL;
1398         enum changelog_rec_flags clf_flags = 0;
1399         struct md_hsm mh;
1400         bool is_mh_changed;
1401         bool need_changelog = true;
1402         int rc = 0;
1403
1404         ENTRY;
1405         /* default is to retry */
1406         *status = ARS_WAITING;
1407
1408         /* find object by FID, mdt_hsm_get_md_hsm() returns obj or err
1409          * if error/removed continue anyway to get correct reporting done */
1410         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1411         /* we will update MD HSM only if needed */
1412         is_mh_changed = false;
1413
1414         /* no need to change mh->mh_arch_id
1415          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1416          */
1417         if (pgs->hpk_errval != 0) {
1418                 switch (pgs->hpk_errval) {
1419                 case ENOSYS:
1420                         /* the copy tool does not support cancel
1421                          * so the cancel request is failed
1422                          * As we cannot distinguish a cancel progress
1423                          * from another action progress (they have the
1424                          * same cookie), we suppose here the CT returns
1425                          * ENOSYS only if does not support cancel
1426                          */
1427                         /* this can also happen when cdt calls it to
1428                          * for a timed out request */
1429                         *status = ARS_FAILED;
1430                         /* to have a cancel event in changelog */
1431                         pgs->hpk_errval = ECANCELED;
1432                         break;
1433                 case ECANCELED:
1434                         /* the request record has already been set to
1435                          * ARS_CANCELED, this set the cancel request
1436                          * to ARS_SUCCEED */
1437                         *status = ARS_SUCCEED;
1438                         break;
1439                 default:
1440                         /* retry only if current policy or requested, and
1441                          * object is not on error/removed */
1442                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1443                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ||
1444                                    IS_ERR(obj)) ? ARS_FAILED : ARS_WAITING;
1445                         break;
1446                 }
1447
1448                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1449                         CERROR("%s: Request %#llx on "DFID
1450                                " failed, error code %d too large\n",
1451                                mdt_obd_name(mdt),
1452                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1453                                pgs->hpk_errval);
1454                         hsm_set_cl_error(&clf_flags, CLF_HSM_ERROVERFLOW);
1455                         rc = -EINVAL;
1456                 } else {
1457                         hsm_set_cl_error(&clf_flags, pgs->hpk_errval);
1458                 }
1459
1460                 switch (car->car_hai->hai_action) {
1461                 case HSMA_ARCHIVE:
1462                         hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
1463                         break;
1464                 case HSMA_RESTORE:
1465                         hsm_set_cl_event(&clf_flags, HE_RESTORE);
1466                         break;
1467                 case HSMA_REMOVE:
1468                         hsm_set_cl_event(&clf_flags, HE_REMOVE);
1469                         break;
1470                 case HSMA_CANCEL:
1471                         hsm_set_cl_event(&clf_flags, HE_CANCEL);
1472                         CERROR("%s: Failed request %#llx on "DFID
1473                                " cannot be a CANCEL\n",
1474                                mdt_obd_name(mdt),
1475                                pgs->hpk_cookie,
1476                                PFID(&pgs->hpk_fid));
1477                         break;
1478                 default:
1479                         CERROR("%s: Failed request %#llx on "DFID
1480                                " %d is an unknown action\n",
1481                                mdt_obd_name(mdt),
1482                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1483                                car->car_hai->hai_action);
1484                         rc = -EINVAL;
1485                         break;
1486                 }
1487         } else {
1488                 *status = ARS_SUCCEED;
1489                 switch (car->car_hai->hai_action) {
1490                 case HSMA_ARCHIVE:
1491                         hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
1492                         /* set ARCHIVE keep EXIST and clear LOST and
1493                          * DIRTY */
1494                         mh.mh_arch_ver = pgs->hpk_data_version;
1495                         mh.mh_flags |= HS_ARCHIVED;
1496                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1497                         is_mh_changed = true;
1498                         break;
1499                 case HSMA_RESTORE:
1500                         hsm_set_cl_event(&clf_flags, HE_RESTORE);
1501
1502                         /* do not clear RELEASED and DIRTY here
1503                          * this will occur in hsm_swap_layouts()
1504                          */
1505
1506                         /* Restoring has changed the file version on
1507                          * disk. */
1508                         mh.mh_arch_ver = pgs->hpk_data_version;
1509                         is_mh_changed = true;
1510                         break;
1511                 case HSMA_REMOVE:
1512                         hsm_set_cl_event(&clf_flags, HE_REMOVE);
1513                         /* clear ARCHIVED EXISTS and LOST */
1514                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1515                         is_mh_changed = true;
1516                         break;
1517                 case HSMA_CANCEL:
1518                         hsm_set_cl_event(&clf_flags, HE_CANCEL);
1519                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1520                                mdt_obd_name(mdt),
1521                                pgs->hpk_cookie,
1522                                PFID(&pgs->hpk_fid));
1523                         break;
1524                 default:
1525                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1526                                mdt_obd_name(mdt),
1527                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1528                                car->car_hai->hai_action);
1529                         rc = -EINVAL;
1530                         break;
1531                 }
1532         }
1533
1534         /* rc != 0 means error when analysing action, it may come from
1535          * a crasy CT no need to manage DIRTY
1536          * and if mdt_hsm_get_md_hsm() has returned an error, mh has not been
1537          * filled
1538          */
1539         if (rc == 0 && !IS_ERR(obj))
1540                 hsm_set_cl_flags(&clf_flags,
1541                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1542
1543         /* unlock is done later, after layout lock management */
1544         if (is_mh_changed && !IS_ERR(obj))
1545                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1546
1547         /* we give back layout lock only if restore was successful or
1548          * if no retry will be attempted and if object is still alive,
1549          * in other cases we just unlock the object */
1550         if (car->car_hai->hai_action == HSMA_RESTORE) {
1551                 struct mdt_lock_handle *lh;
1552
1553                 /* restore in data FID done, we swap the layouts
1554                  * only if restore is successful */
1555                 if (pgs->hpk_errval == 0 && !IS_ERR(obj)) {
1556                         rc = hsm_swap_layouts(mti, obj, &car->car_hai->hai_dfid,
1557                                               &mh);
1558                         if (rc) {
1559                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1560                                         *status = ARS_FAILED;
1561                                 pgs->hpk_errval = -rc;
1562                         }
1563                 }
1564                 /* we have to retry, so keep layout lock */
1565                 if (*status == ARS_WAITING)
1566                         GOTO(out, rc);
1567
1568                 /* restore special case, need to create ChangeLog record
1569                  * before to give back layout lock to avoid concurrent
1570                  * file updater to post out of order ChangeLog */
1571                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
1572                              &car->car_hai->hai_fid);
1573                 need_changelog = false;
1574
1575                 cdt_restore_handle_del(mti, cdt, &car->car_hai->hai_fid);
1576                 if (!IS_ERR_OR_NULL(obj)) {
1577                         /* flush UPDATE lock so attributes are upadated */
1578                         lh = &mti->mti_lh[MDT_LH_OLD];
1579                         mdt_lock_reg_init(lh, LCK_EX);
1580                         mdt_object_lock(mti, obj, lh, MDS_INODELOCK_UPDATE);
1581                         mdt_object_unlock(mti, obj, lh, 1);
1582                 }
1583         }
1584
1585         GOTO(out, rc);
1586
1587 out:
1588         /* always add a ChangeLog record */
1589         if (need_changelog)
1590                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
1591                              &car->car_hai->hai_fid);
1592
1593         if (!IS_ERR(obj))
1594                 mdt_object_put(mti->mti_env, obj);
1595
1596         RETURN(rc);
1597 }
1598
1599 /**
1600  * update status of a request
1601  * \param mti [IN] context
1602  * \param pgs [IN] progress of the copy tool
1603  * \retval 0 success
1604  * \retval -ve failure
1605  */
1606 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1607                                  struct hsm_progress_kernel *pgs)
1608 {
1609         struct mdt_device       *mdt = mti->mti_mdt;
1610         struct coordinator      *cdt = &mdt->mdt_coordinator;
1611         struct cdt_agent_req    *car;
1612         int                      rc = 0;
1613         ENTRY;
1614
1615         /* no coordinator started, so we cannot serve requests */
1616         if (cdt->cdt_state == CDT_STOPPED)
1617                 RETURN(-EAGAIN);
1618
1619         /* first do sanity checks */
1620         car = mdt_cdt_update_request(cdt, pgs);
1621         if (IS_ERR(car)) {
1622                 CERROR("%s: Cannot find running request for cookie %#llx"
1623                        " on fid="DFID"\n",
1624                        mdt_obd_name(mdt),
1625                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1626
1627                 RETURN(PTR_ERR(car));
1628         }
1629
1630         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1631                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1632                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1633                       hsm_copytool_action2name(car->car_hai->hai_action),
1634                       pgs->hpk_flags, pgs->hpk_errval,
1635                       PFID(&car->car_hai->hai_fid),
1636                       PFID(&car->car_hai->hai_dfid));
1637
1638         /* progress is done on FID or data FID depending of the action and
1639          * of the copy progress */
1640         /* for restore progress is used to send back the data FID to cdt */
1641         if (car->car_hai->hai_action == HSMA_RESTORE &&
1642             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1643                 car->car_hai->hai_dfid = pgs->hpk_fid;
1644
1645         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1646              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1647             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1648              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1649                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1650                        " does not match request FID "DFID" nor data FID "
1651                        DFID"\n",
1652                        mdt_obd_name(mdt),
1653                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1654                        PFID(&car->car_hai->hai_fid),
1655                        PFID(&car->car_hai->hai_dfid));
1656                 GOTO(out, rc = -EINVAL);
1657         }
1658
1659         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1660                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1661                        " is not coherent (err=%d and not completed"
1662                        " (flags=%d))\n",
1663                        mdt_obd_name(mdt),
1664                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1665                        hsm_copytool_action2name(car->car_hai->hai_action),
1666                        pgs->hpk_errval, pgs->hpk_flags);
1667                 GOTO(out, rc = -EINVAL);
1668         }
1669
1670         /* now progress is valid */
1671
1672         /* we use a root like ucred */
1673         hsm_init_ucred(mdt_ucred(mti));
1674
1675         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1676                 enum agent_req_status status;
1677                 struct hsm_record_update update;
1678                 int rc1;
1679
1680                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1681
1682                 CDEBUG(D_HSM, "updating record: fid="DFID" cookie=%#llx action=%s "
1683                               "status=%s\n",
1684                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1685                        hsm_copytool_action2name(car->car_hai->hai_action),
1686                        agent_req_status2name(status));
1687
1688                 /* update record first (LU-9075) */
1689                 update.cookie = pgs->hpk_cookie;
1690                 update.status = status;
1691
1692                 rc1 = mdt_agent_record_update(mti, &update, 1);
1693                 if (rc1)
1694                         CERROR("%s: mdt_agent_record_update() failed,"
1695                                " rc=%d, cannot update status to %s"
1696                                " for cookie %#llx\n",
1697                                mdt_obd_name(mdt), rc1,
1698                                agent_req_status2name(status),
1699                                pgs->hpk_cookie);
1700                 rc = (rc != 0 ? rc : rc1);
1701
1702                 /* then remove request from memory list (LU-9075) */
1703                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1704
1705                 /* ct has completed a request, so a slot is available,
1706                  * signal the coordinator to find new work */
1707                 mdt_hsm_cdt_event(cdt);
1708         } else {
1709                 /* if copytool send a progress on a canceled request
1710                  * we inform copytool it should stop
1711                  */
1712                 if (car->car_canceled == 1)
1713                         rc = -ECANCELED;
1714         }
1715         GOTO(out, rc);
1716
1717 out:
1718         /* remove ref got from mdt_cdt_update_request() */
1719         mdt_cdt_put_request(car);
1720
1721         return rc;
1722 }
1723
1724
1725 /**
1726  *  llog_cat_process() callback, used to:
1727  *  - purge all requests
1728  * \param env [IN] environment
1729  * \param llh [IN] llog handle
1730  * \param hdr [IN] llog record
1731  * \param data [IN] cb data = struct mdt_thread_info
1732  * \retval 0 success
1733  * \retval -ve failure
1734  */
1735 static int mdt_cancel_all_cb(const struct lu_env *env,
1736                              struct llog_handle *llh,
1737                              struct llog_rec_hdr *hdr, void *data)
1738 {
1739         struct llog_agent_req_rec *larr = (struct llog_agent_req_rec *)hdr;
1740         struct hsm_action_item *hai = &larr->arr_hai;
1741         struct mdt_thread_info  *mti = data;
1742         struct coordinator *cdt = &mti->mti_mdt->mdt_coordinator;
1743         int rc;
1744         ENTRY;
1745
1746         if (larr->arr_status != ARS_WAITING &&
1747             larr->arr_status != ARS_STARTED)
1748                 RETURN(0);
1749
1750         /* Unlock the EX layout lock */
1751         if (hai->hai_action == HSMA_RESTORE)
1752                 cdt_restore_handle_del(mti, cdt, &hai->hai_fid);
1753
1754         larr->arr_status = ARS_CANCELED;
1755         larr->arr_req_change = ktime_get_real_seconds();
1756         rc = llog_write(env, llh, hdr, hdr->lrh_index);
1757         if (rc < 0) {
1758                 CERROR("%s: cannot update agent log: rc = %d\n",
1759                        mdt_obd_name(mti->mti_mdt), rc);
1760                 rc = LLOG_DEL_RECORD;
1761         }
1762
1763         RETURN(rc);
1764 }
1765
1766 /**
1767  * cancel all actions
1768  * \param obd [IN] MDT device
1769  */
1770 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1771 {
1772         struct lu_env                    env;
1773         struct lu_context                session;
1774         struct mdt_thread_info          *mti;
1775         struct coordinator              *cdt = &mdt->mdt_coordinator;
1776         struct cdt_agent_req            *car;
1777         struct hsm_action_list          *hal = NULL;
1778         struct hsm_action_item          *hai;
1779         int                              hal_sz = 0, hal_len, rc;
1780         enum cdt_states                  old_state;
1781         ENTRY;
1782
1783         rc = lu_env_init(&env, LCT_MD_THREAD);
1784         if (rc < 0)
1785                 RETURN(rc);
1786
1787         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1788         rc = lu_context_init(&session, LCT_SERVER_SESSION);
1789         if (rc < 0)
1790                 GOTO(out_env, rc);
1791
1792         lu_context_enter(&session);
1793         env.le_ses = &session;
1794
1795         mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
1796         LASSERT(mti != NULL);
1797
1798         mti->mti_env = &env;
1799         mti->mti_mdt = mdt;
1800
1801         hsm_init_ucred(mdt_ucred(mti));
1802
1803         mutex_lock(&cdt->cdt_state_lock);
1804         old_state = cdt->cdt_state;
1805
1806         /* disable coordinator */
1807         rc = set_cdt_state_locked(cdt, CDT_DISABLE);
1808         if (rc)
1809                 GOTO(out_cdt_state_unlock, rc);
1810
1811         /* send cancel to all running requests */
1812         down_read(&cdt->cdt_request_lock);
1813         list_for_each_entry(car, &cdt->cdt_request_list, car_request_list) {
1814                 mdt_cdt_get_request(car);
1815                 /* request is not yet removed from list, it will be done
1816                  * when copytool will return progress
1817                  */
1818
1819                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1820                         mdt_cdt_put_request(car);
1821                         continue;
1822                 }
1823
1824                 /* needed size */
1825                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1826                           cfs_size_round(car->car_hai->hai_len);
1827
1828                 if (hal_len > hal_sz && hal_sz > 0) {
1829                         /* not enough room, free old buffer */
1830                         OBD_FREE(hal, hal_sz);
1831                         hal = NULL;
1832                 }
1833
1834                 /* empty buffer, allocate one */
1835                 if (hal == NULL) {
1836                         hal_sz = hal_len;
1837                         OBD_ALLOC(hal, hal_sz);
1838                         if (hal == NULL) {
1839                                 mdt_cdt_put_request(car);
1840                                 up_read(&cdt->cdt_request_lock);
1841                                 GOTO(out_cdt_state, rc = -ENOMEM);
1842                         }
1843                 }
1844
1845                 hal->hal_version = HAL_VERSION;
1846                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1847                                 MTI_NAME_MAXLEN);
1848                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1849                 hal->hal_archive_id = car->car_archive_id;
1850                 hal->hal_flags = car->car_flags;
1851                 hal->hal_count = 0;
1852
1853                 hai = hai_first(hal);
1854                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1855                 hai->hai_action = HSMA_CANCEL;
1856                 hal->hal_count = 1;
1857
1858                 /* it is possible to safely call mdt_hsm_agent_send()
1859                  * (ie without a deadlock on cdt_request_lock), because the
1860                  * write lock is taken only if we are not in purge mode
1861                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1862                  *   nor mdt_cdt_remove_request())
1863                  */
1864                 /* no conflict with cdt thread because cdt is disable and we
1865                  * have the request lock */
1866                 mdt_hsm_agent_send(mti, hal, 1);
1867
1868                 mdt_cdt_put_request(car);
1869         }
1870         up_read(&cdt->cdt_request_lock);
1871
1872         if (hal != NULL)
1873                 OBD_FREE(hal, hal_sz);
1874
1875         /* cancel all on-disk records */
1876         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, mdt_cancel_all_cb,
1877                               (void *)mti, 0, 0, WRITE);
1878 out_cdt_state:
1879         /* Enable coordinator, unless the coordinator was stopping. */
1880         set_cdt_state_locked(cdt, old_state);
1881 out_cdt_state_unlock:
1882         mutex_unlock(&cdt->cdt_state_lock);
1883
1884         lu_context_exit(&session);
1885         lu_context_fini(&session);
1886 out_env:
1887         lu_env_fini(&env);
1888
1889         RETURN(rc);
1890 }
1891
1892 /**
1893  * check if a request is compatible with file status
1894  * \param hai [IN] request description
1895  * \param archive_id [IN] request archive id
1896  * \param rq_flags [IN] request flags
1897  * \param hsm [IN] file HSM metadata
1898  * \retval boolean
1899  */
1900 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1901                               u32 archive_id, u64 rq_flags,
1902                               const struct md_hsm *hsm)
1903 {
1904         int      is_compat = false;
1905         int      hsm_flags;
1906         ENTRY;
1907
1908         hsm_flags = hsm->mh_flags;
1909         switch (hai->hai_action) {
1910         case HSMA_ARCHIVE:
1911                 if (!(hsm_flags & HS_NOARCHIVE) &&
1912                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1913                         is_compat = true;
1914
1915                 if (hsm_flags & HS_EXISTS &&
1916                     archive_id != 0 &&
1917                     archive_id != hsm->mh_arch_id)
1918                         is_compat = false;
1919
1920                 break;
1921         case HSMA_RESTORE:
1922                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1923                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1924                         is_compat = true;
1925                 break;
1926         case HSMA_REMOVE:
1927                 if (!(hsm_flags & HS_RELEASED) &&
1928                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1929                         is_compat = true;
1930                 break;
1931         case HSMA_CANCEL:
1932                 is_compat = true;
1933                 break;
1934         }
1935         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
1936                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
1937                       PFID(&hai->hai_fid),
1938                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1939                       hai->hai_extent.offset, hai->hai_extent.length,
1940                       hsm->mh_flags,
1941                       (is_compat ? "compatible" : "uncompatible"));
1942
1943         RETURN(is_compat);
1944 }
1945
1946 /*
1947  * sysfs interface used to get/set HSM behaviour (cdt->cdt_policy)
1948  */
1949 static const struct {
1950         __u64            bit;
1951         char            *name;
1952         char            *nickname;
1953 } hsm_policy_names[] = {
1954         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1955         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1956         { 0 },
1957 };
1958
1959 /**
1960  * convert a policy name to a bit
1961  * \param name [IN] policy name
1962  * \retval 0 unknown
1963  * \retval   policy bit
1964  */
1965 static __u64 hsm_policy_str2bit(const char *name)
1966 {
1967         int      i;
1968
1969         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1970                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1971                     strcmp(hsm_policy_names[i].name, name) == 0)
1972                         return hsm_policy_names[i].bit;
1973         return 0;
1974 }
1975
1976 /**
1977  * convert a policy bit field to a string
1978  * \param mask [IN] policy bit field
1979  * \param hexa [IN] print mask before bit names
1980  * \param buffer [OUT] string
1981  * \param count [IN] size of buffer
1982  */
1983 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
1984                                 const bool hexa)
1985 {
1986         int      i, j;
1987         __u64    bit;
1988         ENTRY;
1989
1990         if (hexa)
1991                 seq_printf(m, "(%#llx) ", mask);
1992
1993         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1994                 bit = (1ULL << i);
1995
1996                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1997                         if (hsm_policy_names[j].bit == bit)
1998                                 break;
1999                 }
2000                 if (bit & mask)
2001                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
2002                 else
2003                         seq_printf(m, "%s ", hsm_policy_names[j].name);
2004         }
2005         /* remove last ' ' */
2006         m->count--;
2007         seq_putc(m, '\n');
2008 }
2009
2010 /* methods to read/write HSM policy flags */
2011 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
2012 {
2013         struct mdt_device       *mdt = m->private;
2014         struct coordinator      *cdt = &mdt->mdt_coordinator;
2015         ENTRY;
2016
2017         hsm_policy_bit2str(m, cdt->cdt_policy, false);
2018         RETURN(0);
2019 }
2020
2021 static ssize_t
2022 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
2023                          size_t count, loff_t *off)
2024 {
2025         struct seq_file         *m = file->private_data;
2026         struct mdt_device       *mdt = m->private;
2027         struct coordinator      *cdt = &mdt->mdt_coordinator;
2028         char                    *start, *token, sign;
2029         char                    *buf;
2030         __u64                    policy;
2031         __u64                    add_mask, remove_mask, set_mask;
2032         int                      rc;
2033         ENTRY;
2034
2035         if (count + 1 > PAGE_SIZE)
2036                 RETURN(-EINVAL);
2037
2038         OBD_ALLOC(buf, count + 1);
2039         if (buf == NULL)
2040                 RETURN(-ENOMEM);
2041
2042         if (copy_from_user(buf, buffer, count))
2043                 GOTO(out, rc = -EFAULT);
2044
2045         buf[count] = '\0';
2046
2047         start = buf;
2048         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
2049                start);
2050
2051         add_mask = remove_mask = set_mask = 0;
2052         do {
2053                 token = strsep(&start, "\n ");
2054                 sign = *token;
2055
2056                 if (sign == '\0')
2057                         continue;
2058
2059                 if (sign == '-' || sign == '+')
2060                         token++;
2061
2062                 policy = hsm_policy_str2bit(token);
2063                 if (policy == 0) {
2064                         CWARN("%s: '%s' is unknown, "
2065                               "supported policies are:\n", mdt_obd_name(mdt),
2066                               token);
2067                         hsm_policy_bit2str(m, 0, false);
2068                         GOTO(out, rc = -EINVAL);
2069                 }
2070                 switch (sign) {
2071                 case '-':
2072                         remove_mask |= policy;
2073                         break;
2074                 case '+':
2075                         add_mask |= policy;
2076                         break;
2077                 default:
2078                         set_mask |= policy;
2079                         break;
2080                 }
2081
2082         } while (start != NULL);
2083
2084         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
2085                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
2086
2087         /* if no sign in all string, it is a clear and set
2088          * if some sign found, all unsigned are converted
2089          * to add
2090          * P1 P2 = set to P1 and P2
2091          * P1 -P2 = add P1 clear P2 same as +P1 -P2
2092          */
2093         if (remove_mask == 0 && add_mask == 0) {
2094                 cdt->cdt_policy = set_mask;
2095         } else {
2096                 cdt->cdt_policy |= set_mask | add_mask;
2097                 cdt->cdt_policy &= ~remove_mask;
2098         }
2099
2100         GOTO(out, rc = count);
2101
2102 out:
2103         OBD_FREE(buf, count + 1);
2104         RETURN(rc);
2105 }
2106 LDEBUGFS_SEQ_FOPS(mdt_hsm_policy);
2107
2108 ssize_t loop_period_show(struct kobject *kobj, struct attribute *attr,
2109                          char *buf)
2110 {
2111         struct coordinator *cdt = container_of(kobj, struct coordinator,
2112                                                cdt_hsm_kobj);
2113
2114         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_loop_period);
2115 }
2116
2117 ssize_t loop_period_store(struct kobject *kobj, struct attribute *attr,
2118                           const char *buffer, size_t count)
2119 {
2120         struct coordinator *cdt = container_of(kobj, struct coordinator,
2121                                                cdt_hsm_kobj);
2122         unsigned int val;
2123         int rc;
2124
2125         rc = kstrtouint(buffer, 0, &val);
2126         if (rc)
2127                 return rc;
2128
2129         if (val != 0)
2130                 cdt->cdt_loop_period = val;
2131
2132         return val ? count : -EINVAL;
2133 }
2134 LUSTRE_RW_ATTR(loop_period);
2135
2136 ssize_t grace_delay_show(struct kobject *kobj, struct attribute *attr,
2137                          char *buf)
2138 {
2139         struct coordinator *cdt = container_of(kobj, struct coordinator,
2140                                                cdt_hsm_kobj);
2141
2142         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_grace_delay);
2143 }
2144
2145 ssize_t grace_delay_store(struct kobject *kobj, struct attribute *attr,
2146                           const char *buffer, size_t count)
2147 {
2148         struct coordinator *cdt = container_of(kobj, struct coordinator,
2149                                                cdt_hsm_kobj);
2150         unsigned int val;
2151         int rc;
2152
2153         rc = kstrtouint(buffer, 0, &val);
2154         if (rc)
2155                 return rc;
2156
2157         if (val != 0)
2158                 cdt->cdt_grace_delay = val;
2159
2160         return val ? count : -EINVAL;
2161 }
2162 LUSTRE_RW_ATTR(grace_delay);
2163
2164 ssize_t active_request_timeout_show(struct kobject *kobj,
2165                                     struct attribute *attr,
2166                                     char *buf)
2167 {
2168         struct coordinator *cdt = container_of(kobj, struct coordinator,
2169                                                cdt_hsm_kobj);
2170
2171         return scnprintf(buf, PAGE_SIZE, "%d\n", cdt->cdt_active_req_timeout);
2172 }
2173
2174 ssize_t active_request_timeout_store(struct kobject *kobj,
2175                                      struct attribute *attr,
2176                                      const char *buffer, size_t count)
2177 {
2178         struct coordinator *cdt = container_of(kobj, struct coordinator,
2179                                                cdt_hsm_kobj);
2180         unsigned int val;
2181         int rc;
2182
2183         rc = kstrtouint(buffer, 0, &val);
2184         if (rc)
2185                 return rc;
2186
2187         if (val != 0)
2188                 cdt->cdt_active_req_timeout = val;
2189
2190         return val ? count : -EINVAL;
2191 }
2192 LUSTRE_RW_ATTR(active_request_timeout);
2193
2194 ssize_t max_requests_show(struct kobject *kobj, struct attribute *attr,
2195                           char *buf)
2196 {
2197         struct coordinator *cdt = container_of(kobj, struct coordinator,
2198                                                cdt_hsm_kobj);
2199
2200         return scnprintf(buf, PAGE_SIZE, "%llu\n", cdt->cdt_max_requests);
2201 }
2202
2203 ssize_t max_requests_store(struct kobject *kobj, struct attribute *attr,
2204                            const char *buffer, size_t count)
2205 {
2206         struct coordinator *cdt = container_of(kobj, struct coordinator,
2207                                                cdt_hsm_kobj);
2208         unsigned long long val;
2209         int rc;
2210
2211         rc = kstrtoull(buffer, 0, &val);
2212         if (rc)
2213                 return rc;
2214
2215         if (val != 0)
2216                 cdt->cdt_max_requests = val;
2217
2218         return val ? count : -EINVAL;
2219 }
2220 LUSTRE_RW_ATTR(max_requests);
2221
2222 ssize_t default_archive_id_show(struct kobject *kobj, struct attribute *attr,
2223                                 char *buf)
2224 {
2225         struct coordinator *cdt = container_of(kobj, struct coordinator,
2226                                                cdt_hsm_kobj);
2227
2228         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_default_archive_id);
2229 }
2230
2231 ssize_t default_archive_id_store(struct kobject *kobj, struct attribute *attr,
2232                                  const char *buffer, size_t count)
2233 {
2234         struct coordinator *cdt = container_of(kobj, struct coordinator,
2235                                                cdt_hsm_kobj);
2236         unsigned int val;
2237         int rc;
2238
2239         rc = kstrtouint(buffer, 0, &val);
2240         if (rc)
2241                 return rc;
2242
2243         if (val != 0)
2244                 cdt->cdt_default_archive_id = val;
2245
2246         return val ? count : -EINVAL;
2247 }
2248 LUSTRE_RW_ATTR(default_archive_id);
2249
2250 /*
2251  * procfs write method for MDT/hsm_control
2252  * proc entry is in mdt directory so data is mdt obd_device pointer
2253  */
2254 #define CDT_ENABLE_CMD   "enabled"
2255 #define CDT_STOP_CMD     "shutdown"
2256 #define CDT_DISABLE_CMD  "disabled"
2257 #define CDT_PURGE_CMD    "purge"
2258 #define CDT_HELP_CMD     "help"
2259 #define CDT_MAX_CMD_LEN  10
2260
2261 ssize_t hsm_control_store(struct kobject *kobj, struct attribute *attr,
2262                           const char *buffer, size_t count)
2263 {
2264         struct obd_device *obd = container_of(kobj, struct obd_device,
2265                                               obd_kset.kobj);
2266         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2267         struct coordinator *cdt = &(mdt->mdt_coordinator);
2268         int usage = 0;
2269         int rc = 0;
2270
2271         if (count == 0 || count >= CDT_MAX_CMD_LEN)
2272                 return -EINVAL;
2273
2274         if (strncmp(buffer, CDT_ENABLE_CMD, strlen(CDT_ENABLE_CMD)) == 0) {
2275                 if (cdt->cdt_state == CDT_DISABLE) {
2276                         rc = set_cdt_state(cdt, CDT_RUNNING);
2277                         mdt_hsm_cdt_event(cdt);
2278                         wake_up(&cdt->cdt_waitq);
2279                 } else if (cdt->cdt_state == CDT_RUNNING) {
2280                         rc = 0;
2281                 } else {
2282                         rc = mdt_hsm_cdt_start(mdt);
2283                 }
2284         } else if (strncmp(buffer, CDT_STOP_CMD, strlen(CDT_STOP_CMD)) == 0) {
2285                 if (cdt->cdt_state == CDT_STOPPING) {
2286                         CERROR("%s: Coordinator is already stopping\n",
2287                                mdt_obd_name(mdt));
2288                         rc = -EALREADY;
2289                 } else if (cdt->cdt_state == CDT_STOPPED) {
2290                         rc = 0;
2291                 } else {
2292                         rc = mdt_hsm_cdt_stop(mdt);
2293                 }
2294         } else if (strncmp(buffer, CDT_DISABLE_CMD,
2295                            strlen(CDT_DISABLE_CMD)) == 0) {
2296                 if ((cdt->cdt_state == CDT_STOPPING) ||
2297                     (cdt->cdt_state == CDT_STOPPED)) {
2298                         /* exit gracefully if coordinator is being stopped
2299                          * or stopped already.
2300                          */
2301                         rc = 0;
2302                 } else {
2303                         rc = set_cdt_state(cdt, CDT_DISABLE);
2304                 }
2305         } else if (strncmp(buffer, CDT_PURGE_CMD,
2306                            strlen(CDT_PURGE_CMD)) == 0) {
2307                 rc = hsm_cancel_all_actions(mdt);
2308         } else if (strncmp(buffer, CDT_HELP_CMD,
2309                            strlen(CDT_HELP_CMD)) == 0) {
2310                 usage = 1;
2311         } else {
2312                 usage = 1;
2313                 rc = -EINVAL;
2314         }
2315
2316         if (usage == 1)
2317                 CERROR("%s: Valid coordinator control commands are: "
2318                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2319                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2320                        CDT_PURGE_CMD, CDT_HELP_CMD);
2321
2322         if (rc)
2323                 RETURN(rc);
2324
2325         RETURN(count);
2326 }
2327
2328 ssize_t hsm_control_show(struct kobject *kobj, struct attribute *attr,
2329                          char *buf)
2330 {
2331         struct obd_device *obd = container_of(kobj, struct obd_device,
2332                                               obd_kset.kobj);
2333         struct coordinator *cdt;
2334
2335         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2336
2337         return scnprintf(buf, PAGE_SIZE, "%s\n",
2338                          cdt_mdt_state2str(cdt->cdt_state));
2339 }
2340
2341 static int
2342 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
2343 {
2344         bool first = true;
2345         int i;
2346         ENTRY;
2347
2348         for (i = 0; i < 8 * sizeof(mask); i++) {
2349                 if (mask & (1UL << i)) {
2350                         seq_printf(m, "%s%s", first ? "" : " ",
2351                                    hsm_copytool_action2name(i));
2352                         first = false;
2353                 }
2354         }
2355         seq_putc(m, '\n');
2356
2357         RETURN(0);
2358 }
2359
2360 static int
2361 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2362 {
2363         struct mdt_device *mdt = m->private;
2364         struct coordinator *cdt = &mdt->mdt_coordinator;
2365
2366         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2367 }
2368
2369 static int
2370 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2371 {
2372         struct mdt_device *mdt = m->private;
2373         struct coordinator *cdt = &mdt->mdt_coordinator;
2374
2375         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2376 }
2377
2378 static int
2379 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2380 {
2381         struct mdt_device *mdt = m->private;
2382         struct coordinator *cdt = &mdt->mdt_coordinator;
2383
2384         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2385 }
2386
2387 static inline enum hsm_copytool_action
2388 hsm_copytool_name2action(const char *name)
2389 {
2390         if (strcasecmp(name, "NOOP") == 0)
2391                 return HSMA_NONE;
2392         else if (strcasecmp(name, "ARCHIVE") == 0)
2393                 return HSMA_ARCHIVE;
2394         else if (strcasecmp(name, "RESTORE") == 0)
2395                 return HSMA_RESTORE;
2396         else if (strcasecmp(name, "REMOVE") == 0)
2397                 return HSMA_REMOVE;
2398         else if (strcasecmp(name, "CANCEL") == 0)
2399                 return HSMA_CANCEL;
2400         else
2401                 return -1;
2402 }
2403
2404 static ssize_t
2405 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2406                             size_t user_count, __u64 *mask)
2407 {
2408         char *buf, *pos, *name;
2409         size_t buf_size;
2410         __u64 new_mask = 0;
2411         int rc;
2412         ENTRY;
2413
2414         if (!(user_count < 4096))
2415                 RETURN(-ENOMEM);
2416
2417         buf_size = user_count + 1;
2418
2419         OBD_ALLOC(buf, buf_size);
2420         if (buf == NULL)
2421                 RETURN(-ENOMEM);
2422
2423         if (copy_from_user(buf, user_buf, buf_size - 1))
2424                 GOTO(out, rc = -EFAULT);
2425
2426         buf[buf_size - 1] = '\0';
2427
2428         pos = buf;
2429         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2430                 int action;
2431
2432                 if (*name == '\0')
2433                         continue;
2434
2435                 action = hsm_copytool_name2action(name);
2436                 if (action < 0)
2437                         GOTO(out, rc = -EINVAL);
2438
2439                 new_mask |= (1UL << action);
2440         }
2441
2442         *mask = new_mask;
2443         rc = user_count;
2444 out:
2445         OBD_FREE(buf, buf_size);
2446
2447         RETURN(rc);
2448 }
2449
2450 static ssize_t
2451 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2452                                         size_t count, loff_t *off)
2453 {
2454         struct seq_file         *m = file->private_data;
2455         struct mdt_device       *mdt = m->private;
2456         struct coordinator *cdt = &mdt->mdt_coordinator;
2457
2458         return mdt_write_hsm_request_mask(file, buf, count,
2459                                            &cdt->cdt_user_request_mask);
2460 }
2461
2462 static ssize_t
2463 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2464                                         size_t count, loff_t *off)
2465 {
2466         struct seq_file         *m = file->private_data;
2467         struct mdt_device       *mdt = m->private;
2468         struct coordinator      *cdt = &mdt->mdt_coordinator;
2469
2470         return mdt_write_hsm_request_mask(file, buf, count,
2471                                            &cdt->cdt_group_request_mask);
2472 }
2473
2474 static ssize_t
2475 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2476                                         size_t count, loff_t *off)
2477 {
2478         struct seq_file         *m = file->private_data;
2479         struct mdt_device       *mdt = m->private;
2480         struct coordinator      *cdt = &mdt->mdt_coordinator;
2481
2482         return mdt_write_hsm_request_mask(file, buf, count,
2483                                            &cdt->cdt_other_request_mask);
2484 }
2485
2486 static ssize_t remove_archive_on_last_unlink_show(struct kobject *kobj,
2487                                                   struct attribute *attr,
2488                                                   char *buf)
2489 {
2490         struct coordinator *cdt = container_of(kobj, struct coordinator,
2491                                                cdt_hsm_kobj);
2492
2493         return scnprintf(buf, PAGE_SIZE, "%u\n",
2494                          cdt->cdt_remove_archive_on_last_unlink);
2495 }
2496
2497 static ssize_t remove_archive_on_last_unlink_store(struct kobject *kobj,
2498                                                    struct attribute *attr,
2499                                                    const char *buffer,
2500                                                    size_t count)
2501 {
2502         struct coordinator *cdt = container_of(kobj, struct coordinator,
2503                                                cdt_hsm_kobj);
2504         bool val;
2505         int rc;
2506
2507         rc = kstrtobool(buffer, &val);
2508         if (rc < 0)
2509                 return rc;
2510
2511         cdt->cdt_remove_archive_on_last_unlink = val;
2512         return count;
2513 }
2514 LUSTRE_RW_ATTR(remove_archive_on_last_unlink);
2515
2516 LDEBUGFS_SEQ_FOPS(mdt_hsm_user_request_mask);
2517 LDEBUGFS_SEQ_FOPS(mdt_hsm_group_request_mask);
2518 LDEBUGFS_SEQ_FOPS(mdt_hsm_other_request_mask);
2519
2520 /* Read-only sysfs files for request counters */
2521 static ssize_t archive_count_show(struct kobject *kobj, struct attribute *attr,
2522                                   char *buf)
2523 {
2524         struct coordinator *cdt = container_of(kobj, struct coordinator,
2525                                                cdt_hsm_kobj);
2526
2527         return scnprintf(buf, PAGE_SIZE, "%d\n",
2528                          atomic_read(&cdt->cdt_archive_count));
2529 }
2530 LUSTRE_RO_ATTR(archive_count);
2531
2532 static ssize_t restore_count_show(struct kobject *kobj, struct attribute *attr,
2533                                   char *buf)
2534 {
2535         struct coordinator *cdt = container_of(kobj, struct coordinator,
2536                                                cdt_hsm_kobj);
2537
2538         return scnprintf(buf, PAGE_SIZE, "%d\n",
2539                          atomic_read(&cdt->cdt_restore_count));
2540 }
2541 LUSTRE_RO_ATTR(restore_count);
2542
2543 static ssize_t remove_count_show(struct kobject *kobj, struct attribute *attr,
2544                                  char *buf)
2545 {
2546         struct coordinator *cdt = container_of(kobj, struct coordinator,
2547                                                cdt_hsm_kobj);
2548
2549         return scnprintf(buf, PAGE_SIZE, "%d\n",
2550                          atomic_read(&cdt->cdt_remove_count));
2551 }
2552 LUSTRE_RO_ATTR(remove_count);
2553
2554 static struct ldebugfs_vars ldebugfs_mdt_hsm_vars[] = {
2555         { .name =       "agents",
2556           .fops =       &mdt_hsm_agent_fops                     },
2557         { .name =       "actions",
2558           .fops =       &mdt_hsm_actions_fops,
2559           .proc_mode =  0444                                    },
2560         { .name =       "policy",
2561           .fops =       &mdt_hsm_policy_fops                    },
2562         { .name =       "active_requests",
2563           .fops =       &mdt_hsm_active_requests_fops           },
2564         { .name =       "user_request_mask",
2565           .fops =       &mdt_hsm_user_request_mask_fops,        },
2566         { .name =       "group_request_mask",
2567           .fops =       &mdt_hsm_group_request_mask_fops,       },
2568         { .name =       "other_request_mask",
2569           .fops =       &mdt_hsm_other_request_mask_fops,       },
2570         { 0 }
2571 };
2572
2573 static struct attribute *hsm_attrs[] = {
2574         &lustre_attr_loop_period.attr,
2575         &lustre_attr_grace_delay.attr,
2576         &lustre_attr_active_request_timeout.attr,
2577         &lustre_attr_max_requests.attr,
2578         &lustre_attr_default_archive_id.attr,
2579         &lustre_attr_remove_archive_on_last_unlink.attr,
2580         &lustre_attr_archive_count.attr,
2581         &lustre_attr_restore_count.attr,
2582         &lustre_attr_remove_count.attr,
2583         NULL,
2584 };
2585
2586 static void hsm_kobj_release(struct kobject *kobj)
2587 {
2588         struct coordinator *cdt = container_of(kobj, struct coordinator,
2589                                                cdt_hsm_kobj);
2590
2591         debugfs_remove_recursive(cdt->cdt_debugfs_dir);
2592         cdt->cdt_debugfs_dir = NULL;
2593
2594         complete(&cdt->cdt_kobj_unregister);
2595 }
2596
2597 static struct kobj_type hsm_ktype = {
2598         .default_attrs  = hsm_attrs,
2599         .sysfs_ops      = &lustre_sysfs_ops,
2600         .release        = hsm_kobj_release,
2601 };
2602
2603 /**
2604  * create sysfs entries for coordinator
2605  * \param mdt [IN]
2606  * \retval 0 success
2607  * \retval -ve failure
2608  */
2609 int hsm_cdt_tunables_init(struct mdt_device *mdt)
2610 {
2611         struct coordinator *cdt = &mdt->mdt_coordinator;
2612         struct obd_device *obd = mdt2obd_dev(mdt);
2613         int rc;
2614
2615         init_completion(&cdt->cdt_kobj_unregister);
2616         rc = kobject_init_and_add(&cdt->cdt_hsm_kobj, &hsm_ktype,
2617                                   &obd->obd_kset.kobj, "%s", "hsm");
2618         if (rc) {
2619                 kobject_put(&cdt->cdt_hsm_kobj);
2620                 return rc;
2621         }
2622
2623         /* init debugfs entries, failure is not critical */
2624         cdt->cdt_debugfs_dir = debugfs_create_dir("hsm",
2625                                                   obd->obd_debugfs_entry);
2626         ldebugfs_add_vars(cdt->cdt_debugfs_dir, ldebugfs_mdt_hsm_vars, mdt);
2627
2628         return 0;
2629 }
2630
2631 /**
2632  * remove sysfs entries for coordinator
2633  *
2634  * @mdt
2635  */
2636 void hsm_cdt_tunables_fini(struct mdt_device *mdt)
2637 {
2638         struct coordinator *cdt = &mdt->mdt_coordinator;
2639
2640         kobject_put(&cdt->cdt_hsm_kobj);
2641         wait_for_completion(&cdt->cdt_kobj_unregister);
2642 }