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