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